using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Entity;
using PTMedicalInsurance.Entity.Local;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace PTMedicalInsurance.Common
{
    class ECTokenReader
    {
        //static string URL = "https://fuwu-test.nhsa.gov.cn/localcfc/api/hsecfc/localQrCodeQuery";

        [DllImport("NationECCode.dll", EntryPoint = "NationEcTrans", CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern string NationEcTrans(string strUrl,string InData,StringBuilder OutData);


        public static string ECQuery(string EcCertDecodeType) {
            Random rd = new Random();
            int iNum = rd.Next();
            string bizNo = DateTime.Now.ToString("yyyyMMddHHmmsss") + Global.inf.hospitalNO + iNum.ToString().Substring(0, 5);

            ECTokenData eCToken = new ECTokenData();
            eCToken.orgId = Global.inf.hospitalNO;
            eCToken.operatorId = Global.user.ID;
            eCToken.operatorName = Global.user.name;
            eCToken.officeId = Global.user.officeID;
            eCToken.officeName = Global.user.officeName;
            eCToken.businessType = Global.businessType ;
            //eCToken.outBizNo = bizNo;
            //eCToken.extData = "";

            //认证方式
            //二维码
            if (EcCertDecodeType == "0")
            {
                eCToken.deviceType = Global.businessType;
            }
            //电子凭证
            else if (EcCertDecodeType == "1")
            {
                eCToken.outBizNo = bizNo;
            }
            //刷脸、先授权后解码
            else if (EcCertDecodeType == "2") //刷脸 
            {
                //成功返回授权信息
                string auth = "";
                faceAuth(out auth, bizNo);
                if (!string.IsNullOrEmpty(auth))
                {
                    eCToken.authNo = auth;
                }
                else {
                    return "";
                }
            }
            
            string sOutPar = "";
            //调用电子凭证动态库NationECCode.dll获取身份信息
            callECQuery(eCToken,"ec.query",out sOutPar);

            //int ret = call1162(eCToken, out sOutPar);
           
            return sOutPar;
        }

        public static void faceAuth(out string outParam,string bizNo)
        {
            ECTokenData data = new ECTokenData();
            data.outBizNo = bizNo;
            data.extData = "";
            callECQuery(data, "cn.nhsa.ec.auth", out outParam);
        }

        private static JObject getECTokenInput(ECTokenData eCToken) 
        {
            ECTokenInput joData = new ECTokenInput();
            joData.data = eCToken;
            return JObject.Parse(JsonHelper.toJsonString(joData));
        }

        private static int call1162(ECTokenData eCToken, out string sOutPar)
        {
            InvokeHelper invoker = new InvokeHelper();
            JObject joInput = getECTokenInput(eCToken) ;
            JObject joRtn = invoker.invokeCenterService(TradeEnum.ReadECToken, joInput);
            string errorMsg = "";
            sOutPar = "";
            if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
            {
                Global.writeLog("获取电子凭证信息失败：" + errorMsg);
                return -1;
            }
            sOutPar = joRtn.ToString();
            return 0;
        }

        private static void callECQuery(ECTokenData eCToken,string transType,out string sOutPar)
        {
            var input = new ECTokenInput();
            input.data = eCToken;
            input.orgId = eCToken.orgId;
            input.transType = transType; // "ec.query";
            input.extra = "";
            sOutPar = "";
            try
            {
                string inputParam = JsonHelper.toJsonString(input);
                Global.writeLog("开始调用ECToken:"+ inputParam);
                StringBuilder sbOut = new StringBuilder(40960);
                string strToken = NationEcTrans(Global.inf.ecURL, inputParam, sbOut);
                sOutPar = sbOut.ToString();
                Global.writeLog("EcToken返回:"+strToken,inputParam,sOutPar);
                if (JsonHelper.getDestValue(JObject.Parse(sOutPar), "code") != "0")
                {
                    Global.writeLog("调用认证接口" + transType + "失败：" + sOutPar);
                }
            }
            catch (Exception e)
            {
                Global.writeLog("调用电子凭证【"+ Global.inf.ecURL + "】异常:"+e.Message);
            }
            
        }
    }

    class ECTokenInput 
    {
        /// <summary>
        /// 机构代码
        /// </summary>
        public string orgId { get; set; }
        /// <summary>
        /// 交易类型
        /// </summary>
        public string transType { get; set; }
        /// <summary>
        /// 请求参数
        /// </summary>
        public ECTokenData data { get; set; }
        /// <summary>
        /// 扩展参数
        /// </summary>
        public string extra { get; set; }
    }
    class ECTokenData
    {
        /// <summary>
        /// 医保定点机构代码
        /// </summary>
        public string orgId { get; set; }
        /// <summary>
        /// 用码业务类型
        /// </summary>
        public string businessType { get; set; }
        /// <summary>
        /// 收款员编号
        /// </summary>
        public object operatorId { get; set; }
        /// <summary>
        /// 收款员姓名
        /// </summary>
        public string operatorName { get; set; }
        /// <summary>
        /// 医保科室编号
        /// </summary>
        public string officeId { get; set; }
        /// <summary>
        /// 科室名称
        /// </summary>
        public string officeName { get; set; }

        public string outBizNo { get; set; }

        public string authNo { get; set; }

        public string deviceType { get; set; }

        public string extData { get; set; }

    }
}
