using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AnHuiMI.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,out string OutData);

        static extern IntPtr NationEcTrans(StringBuilder strUrl, StringBuilder InData, StringBuilder OutData);
        public static string ECQuery(string EcCertDecodeType) {
            Random rd = new Random();
            int iNum = rd.Next();
            string bizNo = DateTime.Now.ToString("YYYYMMDDHHNNSS") + 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 "";
                }
            }

            //调用电子凭证动态库NationECCode.dll获取身份信息
            string sOutPar = "";
            callECQuery(eCToken,"ec.query",out sOutPar);

            if (!string.IsNullOrEmpty(sOutPar)) 
            {
                Global.pat.ecToken = JsonHelper.getDestValue(JObject.Parse(sOutPar), "data.ecToken");
                Global.pat.name = JsonHelper.getDestValue(JObject.Parse(sOutPar), "data.userName");
                Global.pat.IDType = JsonHelper.getDestValue(JObject.Parse(sOutPar), "data.idType");
                Global.pat.IDNO = JsonHelper.getDestValue(JObject.Parse(sOutPar), "data.idNo");
                Global.pat.insuplc_admdvs = JsonHelper.getDestValue(JObject.Parse(sOutPar), "data.insuOrg");

                Global.pat.mdtrtcertNO = Global.pat.ecToken;
                Global.pat.certType = Global.pat.IDType;
                Global.pat.certNO = Global.pat.IDNO;
            }
            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 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 = "";


            StringBuilder sbURL = new StringBuilder(Global.inf.ecURL);
            StringBuilder sbInData = new StringBuilder(JsonHelper.toJsonString(input));
            StringBuilder sbOutData = new StringBuilder(2048);

            IntPtr pRtn = NationEcTrans(sbURL, sbInData, sbOutData);
            sOutPar = sbOutData.ToString();
            string rtn = Marshal.PtrToStringAnsi(pRtn);
            if (JsonHelper.getDestValue(JObject.Parse(sOutPar), "code") != "0")
            {
                Global.writeLog("调用认证接口"+transType+"失败：" + sOutPar);
                MessageBox.Show("调用认证接口" + transType + "失败：" + sOutPar);
                sOutPar = "";
            }
            Global.writeLog("调用认证接口" + transType + "成功：" + sOutPar);
        }
    }

    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; }

    }
}
