using TencentCloud.Common;
using TencentCloud.Ocr.V20181119.Models;
using TencentCloud.Ocr.V20181119;
using OASystem.Domain;
using OASystem.TencentOCR;
using OASystem.Domain.Dtos.Tencent;
using System.Drawing;

namespace OASystem.Tencent
{
    /// <summary>
    /// 腾讯OCR Tools
    /// </summary>
    public class TencentOCRTool
    {
        /// <summary>
        /// 初始化 腾讯云账户密钥对 SecretId，SecretKey
        /// </summary>
        Credential cred = new Credential
        {
            SecretId = "AKIDoQUHLBELagatzoScfdMpMddMnz8apqIc",
            SecretKey = "hKiGbhkX5NWWXu3zDWwAATVK3e5sWuBB"
        };

        /// <summary>
        /// ocr识别
        /// </summary>
        /// <param name="picBase64">图片base64</param>
        /// <param name="ocrEnum">转换类型</param>
        /// <param name="data">请求数据源</param>
        /// <returns></returns>
        public Result GetOCR(TencentOCREnum ocrEnum, object data)
        {
            Result result = new Result { Code = -1, Msg = "未知错误", Data = null };
            OcrClient client = new OcrClient(cred, "ap-guangzhou");

            try
            {
                switch (ocrEnum)
                {
                    case 0: //身份证识别
                        IDCardOCRDto iDCardDto = (IDCardOCRDto)data;
                        IDCardOCRRequest req = new IDCardOCRRequest();

                        if (iDCardDto.CardSide == 0) req.CardSide = "FORNT";
                        else if (iDCardDto.CardSide == 0) req.CardSide = "BACK";

                        req.ImageBase64 = iDCardDto.picBase64;
                        IDCardOCRResponse resp = client.IDCardOCRSync(req);
                        result.Data = resp;
                        break;

                }

                result.Code = 0;
                result.Msg = "成功";
                return result;
            }
            catch (Exception ex)
            {
                result.Msg = "类型：" + ex.Message;
                return result;
            }
        }


        /// <summary>
        /// 图片转Base64
        /// </summary>
        /// <param name="ImageFileName">图片的完整路径</param>
        /// <returns></returns>
        public string ImgToBase64(string ImageFileName)
        {
            try
            {
                Bitmap bmp = new Bitmap(ImageFileName);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception e)
            {
                return e.Message.ToString();
            }
        }

    }
}