using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PTMedicalInsurance.Business.Core.SelfServiceMachine.Process.ReadCard
{
    class ReadCardProcess:AbstractProcess
    {

        public override CallResult Process(JObject input)
        {
            outParam = "";
            string sOutPar;
            Global.pat.bChangePIN = false;
            JObject joCardInfo = new JObject();
            //JObject joRtn = new JObject();
            //JObject joInput = new JObject();
            //CardReader_HN CardRead = new CardReader_HN();
            //g读卡
            CardReader_GS CardRead_GS = new CardReader_GS(Global.inf.cardURL, Global.inf.areaCode);
            //InvokeHelper invoker = new InvokeHelper();

            try
            {
                Global.pat.certType = "01";

                //电子凭证
                if (Global.ssmp.cardType == "02")
                {
                    Global.pat.mdtrtcertType = "01";
                    //Global.businessType = cc.businessType;
                    Global.pat.mdtrtcertType = "01";
                    Global.pat.certType = "01";
                    Random rd = new Random();
                    int iNum = rd.Next();
                    string sLSH = DateTime.Now.ToString("YYYYMMDDHHNNSS") + Global.inf.hospitalNO + iNum.ToString().Substring(0, 5);

                    joCardInfo.Add("operatorId", Global.user.ID);
                    joCardInfo.Add("operatorName", Global.user.name);
                    joCardInfo.Add("officeId", Global.user.officeID);
                    joCardInfo.Add("officeName", Global.user.officeName);
                    joCardInfo.Add("orgId", Global.inf.hospitalNO);
                    joCardInfo.Add("businessType",Global.businessType);
                    joCardInfo.Add("deviceType", Global.businessType);


                    //调用电子凭证动态库NationECCode.dll获取身份信息                        
                    JObject JoInput = new JObject();
                    JoInput.Add("orgId", Global.inf.hospitalNO);
                    JoInput.Add("transType", "ec.query");
                    JoInput.Add("data", joCardInfo);
                    JoInput.Add("extra", "");

                    CardRead_GS.NationEcTrans(Global.inf.ecURL, JoInput.ToString(), out sOutPar);
                    if (JsonHelper.getDestValue(JObject.Parse(sOutPar), "code") != "0")
                    {
                        outParam = "调用电子凭证失败：" + sOutPar;
                        return Exception(-2, "电子凭证", outParam);
                    }

                    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;
                }
                //身份证
                if (Global.ssmp.cardType == "04")
                {
                    if (Global.pat.card.SearchAdmKey != "")
                        Global.pat.insuplc_admdvs = Global.pat.card.SearchAdmCode;

                    Global.pat.mdtrtcertType = "02";
                    //Global.pat.mdtrtcertNO = cc.sP_CertNO;
                    Global.pat.certType = "01";
                    //Global.pat.certNO = cc.sP_IDNO;
                    //Global.pat.name = cc.PatName;
                    Global.pat.card.SN = "";
                }
                //社保卡
                if (Global.ssmp.cardType == "03")
                {
                    Global.pat.mdtrtcertType = "03";
                    //初始化读卡函数
                    if (CardRead_GS.Init() != 0)
                    {
                        outParam = "读卡初始化Init失败！";
                        return Exception(-2, "社保卡", outParam);
                    }

                    string basInfo = "", regInfo = "";
                    int a = CardRead_GS.ReadCardBas(out basInfo, out regInfo);

                    if (a != 0)
                    {
                        outParam = "社保卡读卡异常ReadCardBas(本地)：" + basInfo;
                        return Exception(-2, "社保卡", outParam);
                    }
                    else
                    {
                        //【社保卡读卡成功返回】
                        Global.pat.insuplc_admdvs = tools.getDestPosStrBySpliter(basInfo, 1);    //参保地
                        Global.pat.card.NO = tools.getDestPosStrBySpliter(basInfo, 2);           //社会保障号码
                        Global.pat.certNO = tools.getDestPosStrBySpliter(basInfo, 3);            //卡号
                        Global.pat.card.SN = tools.getDestPosStrBySpliter(basInfo, 4);           //卡识别码                                                
                        Global.pat.name = tools.getDestPosStrBySpliter(basInfo, 5);              //姓名
                        Global.pat.certType = "01";
                        Global.pat.mdtrtcertType = "03";
                        Global.pat.mdtrtcertNO = Global.pat.certNO;
                        Global.pat.certNO = Global.pat.card.NO;
                    }
                }


                //人脸识别
                if (Global.ssmp.cardType == "05")
                {
                    Global.pat.mdtrtcertType = "01";
                    //Global.businessType = cc.businessType;
                    Global.pat.mdtrtcertType = "01";
                    Global.pat.certType = "01";
                    Random rd = new Random();
                    int iNum = rd.Next();
                    string sLSH = DateTime.Now.ToString("YYYYMMDDHHNNSS") + Global.inf.hospitalNO + iNum.ToString().Substring(0, 5);

                    joCardInfo.Add("operatorId", Global.user.ID);
                    joCardInfo.Add("operatorName", Global.user.name);
                    joCardInfo.Add("officeId", Global.user.officeID);
                    joCardInfo.Add("officeName", Global.user.officeName);
                    joCardInfo.Add("orgId", Global.inf.hospitalNO);
                    joCardInfo.Add("businessType", Global.businessType);
                    joCardInfo.Add("deviceType", Global.businessType);

                    //1.调用人脸识别认证 cn.nhsa.ec.auth
                    joCardInfo.Add("outBizNo", sLSH);
                    joCardInfo.Add("extData", "");

                    JObject JoInputAuth = new JObject();
                    JoInputAuth.Add("orgId", Global.inf.hospitalNO);
                    JoInputAuth.Add("transType", "cn.nhsa.ec.auth");
                    JoInputAuth.Add("data", joCardInfo);
                    JoInputAuth.Add("extra", "");
                    CardReader_HN CardRead = new CardReader_HN();
                    //调用刷脸认证接口cn.nhsa.ec.auth返回授权信息authNo
                    CardRead.NationEcTrans(Global.inf.ecURL, JoInputAuth.ToString(), out sOutPar);
                    if (JsonHelper.getDestValue(JObject.Parse(sOutPar), "code") != "0")
                    {
                        outParam = "调用刷脸认证接口cn.nhsa.ec.auth失败：" + sOutPar;
                        return Exception(-2, "调用刷脸认证", outParam);
                    }
                    else
                    {

                        //成功返回授权信息
                        string auth = JsonHelper.getDestValue(JObject.Parse(sOutPar), "data.authNo");
                        JObject JoAuthCheckInput = new JObject();
                        JoAuthCheckInput.Add("orgId", Global.inf.hospitalNO);
                        JoAuthCheckInput.Add("outBizNo", DateTime.Now.ToString("yyyyMMddHHmmss") + Global.inf.hospitalNO + iNum.ToString().Substring(0, 5));
                        JoAuthCheckInput.Add("authNo", auth);
                        
                        JoAuthCheckInput.Add("businessType", Global.pat.ecBusinessType??"01102");
                        JoAuthCheckInput.Add("operatorId", Global.user.ID);
                        JoAuthCheckInput.Add("operatorName", Global.user.name);
                        JoAuthCheckInput.Add("officeId", Global.user.officeID);
                        JoAuthCheckInput.Add("officeName", Global.user.officeName);
                        JoAuthCheckInput.Add("extData", "");

                        JObject JoAuthChck = new JObject();
                        JoAuthChck.Add("orgId", Global.inf.hospitalNO);
                        JoAuthChck.Add("transType", "cn.nhsa.auth.check");
                        JoAuthChck.Add("data", JoAuthCheckInput);
                        JoAuthChck.Add("extra", "");

                        //2.调用刷脸认证接口cn.nhsa.ec.auth返回授权信息authNo
                        CardRead.NationEcTrans(Global.inf.ecURL, JoAuthChck.ToString(), out sOutPar);
                        if (JsonHelper.getDestValue(JObject.Parse(sOutPar), "code") != "0")
                        {
                            outParam = "调用刷脸授权获取医保身份接口cn.nhsa.auth.check失败：" + sOutPar;
                            return Exception(-2, "人脸识别", outParam);
                        }
                        else
                        {
                            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;
                        }

                    }
                }

                if (trade1101(out outParam) == 0)
                {
                    return Success();
                }

                return Exception(-1, "读卡", outParam);
            }
            catch (Exception ex)
            {
                return Error("异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 通过证件号获取基本信息（无卡）
        /// </summary>
        /// <param name="cardNo"></param>
        /// <param name="outParam"></param>
        /// <returns></returns>
        public int trade1101(out string outParam)
        {

            #region【1101获取身份信息】
            JObject joData = new JObject();
            joData.Add("mdtrt_cert_type", Global.pat.mdtrtcertType);
            joData.Add("mdtrt_cert_no", Global.pat.mdtrtcertNO);
            joData.Add("card_sn", Global.pat.card.SN);
            joData.Add("begntime", "");
            joData.Add("psn_cert_type", Global.pat.certType);
            joData.Add("certno", Global.pat.certNO); //证件号码
            joData.Add("psn_name", Global.pat.name);
            JObject joInput = new JObject();
            joInput.Add("data", joData);

            //InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeCenterService("1101", JsonHelper.setCenterInpar("1101", joInput));
            if (JsonHelper.parseCenterRtnValue(joRtn, out outParam) != 0)
            {
                outParam = "读卡失败：" + outParam;
                return -1;
            }
            else
            {
                //joRtn.Add("cardinfo",joCardInfo);                    
                outParam = joRtn.ToString();
                Global.pat.insuplc_admdvs = JsonHelper.getDestValue(JObject.Parse(outParam), "output.insuinfo.insuplc_admdvs"); //参保地
                Global.pat.certNO = JsonHelper.getDestValue(JObject.Parse(outParam), "output.baseinfo.certno"); //证件号码
                Global.pat.psn_no = JsonHelper.getDestValue(JObject.Parse(outParam), "output.baseinfo.psn_no"); //人员编号
                outParam = outParam.Replace(@"\", "").Replace("\"{", "{").Replace("}\"", "}");
                return 0;
            }
            #endregion
        }
    }

}
