using Aspose.Cells;
using OASystem.API.OAMethodLib.File;
//using OASystem.API.OAMethodLib.NPOI;
using OASystem.API.OAMethodLib.TencentCloudAPI;
using OASystem.API.OAMethodLib.YouDaoAPI;
using OASystem.Domain.Dtos.CRM;
using OASystem.Domain.Dtos.Tencent;
using OASystem.Domain.ViewModels.TencentOCR;
using OASystem.Infrastructure.Repositories.CRM;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Utilities.Encoders;
using StackExchange.Redis;
using System.Net.NetworkInformation;
using TencentCloud.Ocr.V20181119.Models;
using Ubiety.Dns.Core;

namespace OASystem.API.Controllers
{
    /// <summary>
    /// TencentOCR 识别 
    /// </summary>
    [Route("api/[controller]/[action]")]
    //[ApiController]
    public class TencentOCRController : ControllerBase
    {
        private readonly VisaDeleClientRepository _visaDeleClientRepository;

        public TencentOCRController(VisaDeleClientRepository visaDeleClientRepository)
        {
            this._visaDeleClientRepository = visaDeleClientRepository;
        }

        /// <summary>
        /// 通用印刷体
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetGeneralBasic(GeneralBasicOCRDto dto)
        {
            string[] picBase64Array = dto.picBase64.Split(';');
            string picFormat = picBase64Array[0].Split('/')[1];
            if (!TencentOCRTools.ImageType(picFormat))
            {
                return Ok(JsonView("图片格式不正确!只支持 PNG、JPG、JPEG、BMP 格式!"));
            }

            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var gbData =  TencentOCRTools.GetOCR((int)TencentOCREnum.GeneralBasic, dto);

            if (gbData.Code != 0)
            {
                return Ok(JsonView(gbData.Msg));
            }

            if (gbData.Data == null)
            {
                return Ok(JsonView(gbData.Msg));
            }

            return Ok(JsonView(gbData.Data));
        }


        /// <summary>
        /// 身份证识别(国徽面/反面)
        /// 获取身份证返回数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetIDCard(IDCardOCRDto dto)
        {
            string[] picBase64Array = dto.picBase64.Split(';');
            string picFormat = picBase64Array[0].Split('/')[1];
            if (!TencentOCRTools.ImageType(picFormat))
            {
                return Ok(JsonView("图片格式不正确!只支持 PNG、JPG、JPEG、BMP 格式!"));
            }

            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var idCardData = TencentOCRTools.GetOCR((int)TencentOCREnum.IDCard, dto);

            if (idCardData.Code != 0)
            {
                return Ok(JsonView(idCardData.Msg));
            }

            if (idCardData.Data == null)
            {
                return Ok(JsonView(idCardData.Msg));
            }

            IDCardOCRAndDownUrlView iDCardOCRView = new IDCardOCRAndDownUrlView() { };


            if (dto.Language.ToLower() == "ch")
            {
                bool cerdStatus = await _visaDeleClientRepository.SetCrmUpdPassIdCardOCR(
               new SetCrmUpdPassIdCardOCRDto
               {
                   UserId = dto.UserId,
                   ClientName = idCardData.Data.Name,
                   Sex = idCardData.Data.Sex == "男" ? 0 : 1,
                   CerdNo = idCardData.Data.IdNum,
                   CerdAddress = idCardData.Data.Address,
               });
                iDCardOCRView.Status = cerdStatus;
                iDCardOCRView.Name = idCardData.Data.Name;
                iDCardOCRView.Sex = idCardData.Data.Sex;
                iDCardOCRView.Nation = idCardData.Data.Nation;
                iDCardOCRView.Birth = idCardData.Data.Birth;
                iDCardOCRView.Address = idCardData.Data.Address;
                iDCardOCRView.IdNum = idCardData.Data.IdNum;
                iDCardOCRView.Authority = idCardData.Data.Authority;
                iDCardOCRView.ValidDate = idCardData.Data.ValidDate;
            }
            else if (dto.Language.ToLower() == "en")
            {
                iDCardOCRView.Name = await YouDaoApiTools.GetOCR_ReTrans(idCardData.Data.Name);
                iDCardOCRView.Sex = await YouDaoApiTools.GetOCR_ReTrans(idCardData.Data.Sex);
                iDCardOCRView.Nation = await YouDaoApiTools.GetOCR_ReTrans(idCardData.Data.Nation);
                iDCardOCRView.Birth = await YouDaoApiTools.GetOCR_ReTrans(idCardData.Data.Birth);
                iDCardOCRView.Address = await YouDaoApiTools.GetOCR_ReTrans(idCardData.Data.Address);
                iDCardOCRView.IdNum = idCardData.Data.IdNum;
                iDCardOCRView.Authority = await YouDaoApiTools.GetOCR_ReTrans(idCardData.Data.Authority);
                iDCardOCRView.ValidDate = await YouDaoApiTools.GetOCR_ReTrans(idCardData.Data.ValidDate);
            }


            #region word生成 返回地址
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("Name", iDCardOCRView.Name);
            dic.Add("Sex", iDCardOCRView.Sex);
            dic.Add("Nation", iDCardOCRView.Nation);
            dic.Add("Birth", iDCardOCRView.Birth);
            dic.Add("Address", iDCardOCRView.Address);
            dic.Add("IdNum", iDCardOCRView.IdNum);
            dic.Add("Authority", iDCardOCRView.Authority);
            dic.Add("ValidDate", iDCardOCRView.ValidDate);

            string serverPath = "";
            if (dto.Language.ToLower() == "ch")
            {
                string fileNameCh = string.Format("{0}.doc", dic["Name"].ToString() + "身份证(人像面)[CH]" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                serverPath = AsposeHelper.ExpertWordToModel("ocr_身份证(人像面).doc", "TencentOCR", fileNameCh, dic, null);
            }
            else if (dto.Language.ToLower() == "en")
            {
                string fileNameEn = string.Format("{0}.doc", dic["Name"].ToString() + "身份证(人像面)[EN]" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                serverPath = AsposeHelper.ExpertWordToModel("(EN)ocr_身份证(人像面).doc", "TencentOCR", fileNameEn, dic, null);
            }


            iDCardOCRView.DownUrl = serverPath;
            #endregion

            return Ok(JsonView(iDCardOCRView));
        }

        /// <summary>
        /// 户口簿识别
        /// 获取户口簿返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetResidenceBookletOCR(ResidenceBookletOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var residenceBookData = TencentOCRTools.GetOCR((int)TencentOCREnum.ResidenceBooklet, dto);

            if (residenceBookData.Code != 0)
            {
                return Ok(JsonView(residenceBookData.Msg));
            }

            if (residenceBookData.Data == null)
            {
                return Ok(JsonView(residenceBookData.Msg));
            }


            return Ok(JsonView(residenceBookData.Data));
        }

        /// <summary>
        /// 营业执照识别
        /// 获取营业执照返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetBizLicenseOCR(BizLicenseOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var residenceBookData = TencentOCRTools.GetOCR((int)TencentOCREnum.BizLicense, dto);

            if (residenceBookData.Code != 0)
            {
                return Ok(JsonView(residenceBookData.Msg));
            }

            if (residenceBookData.Data == null)
            {
                return Ok(JsonView(residenceBookData.Msg));
            }


            return Ok(JsonView(residenceBookData.Data));
        }

        /// <summary>
        /// 组织结构识别
        /// 获取组织结构返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetOrgCodeCertOCR(OrgCodeCertOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var occData = TencentOCRTools.GetOCR((int)TencentOCREnum.OrgCodeCert, dto);

            if (occData.Code != 0)
            {
                return Ok(JsonView(occData.Msg));
            }

            if (occData.Data == null)
            {
                return Ok(JsonView(occData.Msg));
            }

            return Ok(JsonView(occData.Data));
        }

        /// <summary>
        /// 行驶证识别
        /// 获取行驶证返回数据 
        /// CardSide=0 主页正面（有红色印章的一面），CardSide=1 行驶证副页正面（有号码号牌的一面），CardSide=2 行驶证主页正面和副页正面。
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetVehicleLicense(VehicleLicenseOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var vehicleLicenseData = TencentOCRTools.GetOCR((int)TencentOCREnum.VehicleLicense, dto);

            if (vehicleLicenseData.Code != 0)
            {
                return Ok(JsonView(vehicleLicenseData.Msg));
            }

            if (vehicleLicenseData.Data == null)
            {
                return Ok(JsonView(vehicleLicenseData.Msg));
            }

            return Ok(JsonView(vehicleLicenseData.Data));
        }

        /// <summary>
        /// 房产证识别
        /// 获取房产证返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetPropOwnerCert(PropOwnerCertOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var pcData = TencentOCRTools.GetOCR((int)TencentOCREnum.PropOwnerCert, dto);

            if (pcData.Code != 0)
            {
                return Ok(JsonView(pcData.Msg));
            }

            if (pcData.Data == null)
            {
                return Ok(JsonView(pcData.Msg));
            }

            return Ok(JsonView(pcData.Data));
        }

        /// <summary>
        /// 结婚证识别
        /// 获取结婚证返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetMarriageLicense(MarriageLicenseOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var mlData = TencentOCRTools.GetOCR((int)TencentOCREnum.GeneralBasic, dto);

            if (mlData.Code != 0)
            {
                return Ok(JsonView(mlData.Msg));
            }

            if (mlData.Data == null)
            {
                return Ok(JsonView(mlData.Msg));
            }

            return Ok(JsonView(mlData.Data));
        }

        /// <summary>
        /// 统一信用代码识别 
        /// 获取统一信用代码返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetUniformCreditCode(UniformCreditCodeOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var gbData = TencentOCRTools.GetOCR((int)TencentOCREnum.GeneralBasic, dto);

            if (gbData.Code != 0)
            {
                return Ok(JsonView(gbData.Msg));
            }

            if (gbData.Data == null)
            {
                return Ok(JsonView(gbData.Msg));
            }

            return Ok(JsonView(gbData.Data));
        }

        /// <summary>
        /// 护照识别（中国大陆地区护照） 
        /// 获取护照识别（中国大陆地区护照）返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetPassport(PassportOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var pData = TencentOCRTools.GetOCR((int)TencentOCREnum.Passport, dto);

            if (pData.Code != 0)
            {
                return Ok(JsonView(pData.Msg));
            }

            if (pData.Data == null)
            {
                return Ok(JsonView(pData.Msg));
            }

            return Ok(JsonView(pData.Data));
        }

        /// <summary>
        /// 护照识别（港澳台地区及境外护照）
        /// 获取护照识别（港澳台地区及境外护照）返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetMLIDPassport(PassportOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            var mlidpData = TencentOCRTools.GetOCR((int)TencentOCREnum.MLIDPassport, dto);

            if (mlidpData.Code != 0)
            {
                return Ok(JsonView(mlidpData.Msg));
            }

            if (mlidpData.Data == null)
            {
                return Ok(JsonView(mlidpData.Msg));
            }

            return Ok(JsonView(mlidpData.Data));
        }

        /// <summary>
        /// 名片识别
        /// 获取名片 返回数据 
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetBusinessCard(BusinessCardOCRDto dto)
        {
            double strSize = 1024 * 1024 * 7;
            if (dto.picBase64.Length > strSize)
            {
                return Ok(JsonView("图片不能大于7M!"));
            }

            try
            {
                var mlidpData = TencentOCRTools.GetOCR((int)TencentOCREnum.BusinessCard, dto);
                if (mlidpData.Code != 0)
                {
                    return Ok(JsonView(mlidpData.Msg));
                }

                if (mlidpData.Data == null)
                {
                    return Ok(JsonView(mlidpData.Msg));
                }

                return Ok(JsonView(mlidpData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
    }
}
