using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mall.Common.Plugin
{
    /// <summary>
    /// 用于处理百度的OCR图片识别
    /// </summary>
    public class BaiDuOCRHelper
    {

        private static readonly string clientId = "OGAhU38ib8EweXMtPVqCbkpN";

        private static readonly string clientSecret = "OcqfFF5hlleWovzA6vLweykxPgwE8XF2";

        private static string accessToken = "";

        private static DateTime lastAccessTokenTime = DateTime.Now;

        /// <summary>
        /// 实例化
        /// </summary>
        public BaiDuOCRHelper()
        {
            if (accessToken.Equals(""))
            {
                InitAccessToken();
            }
            TimeSpan ts = DateTime.Now - lastAccessTokenTime;
            if (ts.TotalDays > 29)
            {
                InitAccessToken();
            }
        }

        /// <summary>
        /// 初始化Tocken
        /// </summary>
        public void InitAccessToken()
        {
            string url = "https://aip.baidubce.com/oauth/2.0/token";
            string body = $"grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}";
            string result = HttpHelper.HttpPost(url, body, "");
            JObject obj = JObject.Parse(result);
            accessToken = obj["access_token"].ToString();
            lastAccessTokenTime = DateTime.Now;
        }

        /// <summary>
        /// 识别文字
        /// </summary>
        /// <param name="sourceUrl"></param>
        /// <returns></returns>
        public JToken GetFonts(string sourceUrl)
        {
            if (accessToken == string.Empty) {
                InitAccessToken();
            }
            string url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + accessToken;
            string dataUrlFormat = "data:image/";
            if (sourceUrl.ToLower().Contains("jpg"))
            {
                dataUrlFormat += "jpg;base64,";
            }
            else if (sourceUrl.ToLower().Contains("png"))
            {
                dataUrlFormat += "png;base64,";
            }
            else if (sourceUrl.ToLower().Contains("bmp"))
            {
                dataUrlFormat += "bmp;base64,";
            }
            else
            {
                dataUrlFormat = "";
            }
            string body = $"image={System.Web.HttpUtility.UrlEncode(FileToBase64(sourceUrl))}&language_type=CHN_ENG";
            string result = HttpHelper.HttpPost(url, body, "application/x-www-form-urlencoded");
            JObject obj = JObject.Parse(result);
            return obj["words_result"];
        }

        /// <summary>
        /// 读取文件base64
        /// </summary>
        /// <param name="sourceUrl"></param>
        /// <returns></returns>
        public static String FileToBase64(string sourceUrl)
        {
            string strRet = "";
            try
            {
                FileStream fs = new FileStream(sourceUrl, FileMode.Open);
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, bt.Length);
                strRet = Convert.ToBase64String(bt);
                fs.Close();
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "FileToBase64");
                strRet = null;
            }
            return strRet;
        }
    }
}
