using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.Api.IService.App;
using ASHermed.SinoInterface.Code;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Exception;
using ASHermed.SinoInterface.IFramework;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
using ASHermed.SinoInterface.Tools;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PoJun.Util;
using PoJun.Util.Maps;
using Renci.SshNet.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// 百度服务
	/// </summary>
	public class BaiduService : BaseService, IBaiduService
    {
        AppConfigurtaion _appConfigurtaion;
        IOutService _outService;
        private const string BaiduIdCardApiKey = "g2rpb68UKkijU2zbom1EcXeD";
        private const string BaiduIdCardSecretKey = "NMwSjbLGjdM4OHB3y6a2gYzK9Ceii7TI";
        private const string fuName = "万俟司马 上官欧阳 夏侯诸葛 闻人东方 赫连皇甫 尉迟公羊 澹台公冶 宗政濮阳 淳于单于 太叔申屠 公孙仲孙 轩辕令狐 钟离宇文 长孙慕容 司徒司空 鲜于闾丘 元官司寇 仇都子车 颛孙瑞木 巫马公西 漆雕乐正 壤驷公良 拓拔夹谷 宰父谷梁 晋楚闰法 汝鄢涂钦 段干百里 呼延归海 羊舌微生 梁丘左丘 东郭南门 东门西门 南宫岳帅 侯亢况后 有琴商牟 余饵伯赏 墨哈谯亘 年爱阳佟 第五言福";
        private readonly IFileService _fileService;
        /// <summary>
        /// 百度服务
        /// </summary>
        public BaiduService(IFileService fileService, AppConfigurtaion appConfigurtaion, IOutService outService)
        {
            _fileService = fileService;
            _appConfigurtaion = appConfigurtaion;
            _outService = outService;
        }

        /// <summary>
        /// 百度身份证识别
        /// </summary>
        /// <param name="imageUrl"></param>
        /// <param name="base64String"></param>
        /// <returns></returns>
        public async Task<IdCardDataResult> BaiduIdCardAsync(IFormFile file)
        {
            var client = new Baidu.Aip.Ocr.Ocr(BaiduIdCardApiKey, BaiduIdCardSecretKey);
            var options = new Dictionary<string, object>{
                {"detect_direction", "true"},
                {"detect_risk", "false"}
            };

            string result;
            var buffer = _fileService.CompressImage(_fileService.StreamToBytes(file.OpenReadStream()), 90, 400, true);

            result = client.Idcard(buffer, "front", options).ToString();

            var data = JObject.Parse(result);
            var cardInfo = new IdCardDataResult
            {
                IsMainSide = data["image_status"]?.ToString() != "reversed_side",
                Name = data["words_result"]?["姓名"]?["words"]?.ToString(),
                Nation = data["words_result"]?["民族"]?["words"]?.ToString(),
                Gender = data["words_result"]?["性别"]?["words"]?.ToString(),
                Birthday = data["words_result"]?["出生"]?["words"]?.ToString(),
                Address = data["words_result"]?["住址"]?["words"]?.ToString(),
                Id = data["words_result"]?["公民身份号码"]?["words"]?.ToString(),
                IssueAuthority = data["words_result"]?["签发机关"]?["words"]?.ToString(),
                IssueDate = data["words_result"]?["签发日期"]?["words"]?.ToString(),
                ExpirationDate = data["words_result"]?["失效日期"]?["words"]?.ToString()
            };
            if (cardInfo != null && !string.IsNullOrEmpty(cardInfo.Name))
            {
                var nameModel = FullCardName(cardInfo.Name);
                cardInfo.LastName = nameModel.LastName;
                cardInfo.FirstName = nameModel.FirstName;
                cardInfo.Birthday = FullCardBirthday(cardInfo.Birthday);
                cardInfo.Gender = FullCardGender(cardInfo.Gender);
                
            }
            if (cardInfo.ExpirationDate != null && cardInfo.ExpirationDate.Contains("长期"))
            {
                cardInfo.ExpirationDate = DateTime.Now.AddYears(20).ToString("yyyy-MM-dd");
            }
            return cardInfo;
        }

        private string FullCardBirthday(string birthday)
        {
            if (birthday?.Length >= 8)
            {
                birthday = birthday.Substring(0, 4) + "/" + birthday.Substring(4, 2) + "/" + birthday.Substring(6, 2);
            }
            return birthday;
        }

        public class NameModel
        {
            public string LastName { get; set; }
            public string FirstName { get; set; }
        }

        private NameModel FullCardName(string name)
        {
            NameModel cardInfo = new NameModel();
            if (name.Length == 2)
            {
                cardInfo.LastName = name.Substring(0, 1);
                cardInfo.FirstName = name.Substring(1, 1);
            }
            else if (name.Length >= 3)
            {
                var fname = name.Substring(0, 2);
                if (fuName.Contains(fname))
                {//判断是不是复姓
                    cardInfo.LastName = name.Substring(0, 2);
                    cardInfo.FirstName = name.Substring(2);
                }
                else
                {
                    cardInfo.LastName = name.Substring(0, 1);
                    cardInfo.FirstName = name.Substring(1);
                }
            }

            return cardInfo;
        }

        private string FullCardGender(string gender)
        {
            var res = string.Empty;
            if (gender == "男" || gender == "男/M")
            {
                res = "1";
            }
            if (gender == "女" || gender == "女/F")
            {
                res = "0";
            }
            return res;
        }

        // 身份证识别
        public string Idcard()
        {
            string token = "[调用鉴权接口获取的token]";
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            string base64 = GetFileBase64("[本地图片文件]");
            string str = "id_card_side=" + "front" + "&image=" + HttpUtility.UrlEncode(base64);
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            Console.WriteLine("身份证识别:");
            Console.WriteLine(result);
            return result;
        }

        public string GetFileBase64(string fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }

        public string GetAccessToken()
        {
            string authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<string, string>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", BaiduIdCardApiKey));
            paraList.Add(new KeyValuePair<string, string>("client_secret", BaiduIdCardSecretKey));
            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            //Console.WriteLine(result);
            var tokenInfo = JsonConvert.DeserializeObject<AccessToken>(result);
            return tokenInfo.access_token;
        }

        public string GetShortUrl(string url)
        {
            HttpClient client = new HttpClient();
            string authHost = "https://dwz.cn/api/v3/short-urls";
            ShortQuest quest = new ShortQuest();
            quest.urls.Add(new ShortUrl() { LongUrl = url });
            var asd = quest.ToJson();
            StringContent queryString = new StringContent(quest.urls.ToJson(), Encoding.UTF8, "application/json");
            //表头参数
            client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Dwz-Token", "12ca697bd3292480b38650a6b80d8090");
            //client.DefaultRequestHeaders.Add("Content-Language", "zh");
            HttpResponseMessage response = client.PostAsync(authHost, queryString).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            var shortModel = JsonConvert.DeserializeObject<ShortModel>(result);
            var shortUrl = shortModel?.ShortUrls?.FirstOrDefault()?.ShortUrl;
            if (string.IsNullOrEmpty(shortUrl))
            {
                return url;
            }
            return shortUrl;
        }

        // 护照识别
        public async Task<PassportDataResult> BaiduPassportAsync(IFormFile file)
        {
            string token = GetAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/passport?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            //string base64 = GetFileBase64("[本地图片文件]");
            string str = "image=" + HttpUtility.UrlEncode(Convert.ToBase64String(_fileService.CompressImage(_fileService.StreamToBytes(file.OpenReadStream()))));
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            //Console.WriteLine(result);
            var data = JObject.Parse(result);
            var cardInfo = new PassportDataResult
            {
                NationCode = data["words_result"]?["国家码"]?["words"]?.ToString(),
                IssueAddress = data["words_result"]?["护照签发地点"]?["words"]?.ToString(),
                PassportId = data["words_result"]?["护照号码"]?["words"]?.ToString(),
                Name = data["words_result"]?["姓名"]?["words"]?.ToString(),
                NamePinYin = data["words_result"]?["姓名拼音"]?["words"]?.ToString(),
                Nation = data["words_result"]?["国籍"]?["words"]?.ToString(),
                Gender = data["words_result"]?["性别"]?["words"]?.ToString(),
                Birthday = data["words_result"]?["生日"]?["words"]?.ToString(),
                Address = data["words_result"]?["出生地点"]?["words"]?.ToString(),
                IssueAuthority = data["words_result"]?["签发机关"]?["words"]?.ToString(),
                IssueDate = data["words_result"]?["签发日期"]?["words"]?.ToString(),
                ExpirationDate = data["words_result"]?["有效期至"]?["words"]?.ToString()
            };
            if (cardInfo != null && !string.IsNullOrEmpty(cardInfo.Name))
            {
                //var nameModel = FullCardName(cardInfo.Name);
                //cardInfo.LastName = nameModel.LastName;//护照识别出来的姓名放到名里面(小红说的)
                cardInfo.FirstName = cardInfo.Name;
                cardInfo.Birthday = FullCardBirthday(cardInfo.Birthday);
                cardInfo.Gender = FullCardGender(cardInfo.Gender);
            }
            return cardInfo;
        }

        // 港澳通行证识别
        public async Task<HKMacauDataResult> HKMacauExitentrypermit(IFormFile file)
        {
            string token = GetAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/HK_Macau_exitentrypermit?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            //string base64 = getFileBase64("[本地图片文件]");
            string str = "image=" + HttpUtility.UrlEncode(Convert.ToBase64String(_fileService.CompressImage(_fileService.StreamToBytes(file.OpenReadStream()))));
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            //Console.WriteLine("港澳通行证识别:");
            //Console.WriteLine(result); 
            var data = JObject.Parse(result);
            var cardInfo = new HKMacauDataResult
            {
                CardNum = data["words_result"]?["CardNum"]?["words"]?.ToString(),
                NameChn = data["words_result"]?["NameChn"]?["words"]?.ToString(),
                NameEng = data["words_result"]?["NameEng"]?["words"]?.ToString(),
                Sex = data["words_result"]?["Sex"]?["words"]?.ToString(),
                Birthday = data["words_result"]?["Birthday"]?["words"]?.ToString(),
                Address = data["words_result"]?["Address"]?["words"]?.ToString(),
                ValidDate = data["words_result"]?["ValidDate"]?["words"]?.ToString()
            };
            if (cardInfo != null && !string.IsNullOrEmpty(cardInfo.NameChn))
            {
                var nameModel = FullCardName(cardInfo.NameChn);
                cardInfo.LastName = nameModel.LastName;
                cardInfo.FirstName = nameModel.FirstName;
                cardInfo.Birthday = FullCardBirthday(cardInfo.Birthday);
                cardInfo.Sex = FullCardGender(cardInfo.Sex);
            }
            return cardInfo;
        }

        // 台湾通行证识别
        public async Task<TaiWanDataResult> TaiWanExitentrypermit(IFormFile file)
        {
            string token = GetAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/taiwan_exitentrypermit?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            //string base64 = getFileBase64("[本地图片文件]");
            string str = "image=" + HttpUtility.UrlEncode(Convert.ToBase64String(_fileService.CompressImage(_fileService.StreamToBytes(file.OpenReadStream()))));
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            //Console.WriteLine("台湾通行证识别:");
            //Console.WriteLine(result);
            var data = JObject.Parse(result);
            var cardInfo = new TaiWanDataResult
            {
                CardNum = data["words_result"]?["CardNum"]?["words"]?.ToString(),
                NameChn = data["words_result"]?["NameChn"]?["words"]?.ToString(),
                NameEng = data["words_result"]?["NameEng"]?["words"]?.ToString(),
                Sex = data["words_result"]?["Sex"]?["words"]?.ToString(),
                Birthday = data["words_result"]?["Birthday"]?["words"]?.ToString(),
                Address = data["words_result"]?["Address"]?["words"]?.ToString(),
                ValidDate = data["words_result"]?["ValidDate"]?["words"]?.ToString()
            };
            if (cardInfo != null && !string.IsNullOrEmpty(cardInfo.NameChn))
            {
                var nameModel = FullCardName(cardInfo.NameChn);
                cardInfo.LastName = nameModel.LastName;
                cardInfo.FirstName = nameModel.FirstName;
                cardInfo.Birthday = FullCardBirthday(cardInfo.Birthday);
                cardInfo.Sex = FullCardGender(cardInfo.Sex);
            }
            return cardInfo;
        }


    }
}
