using Newtonsoft.Json.Linq;
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.InPat
{
    class OrganizeIPPatientInparam : AbstractProcess
    {
        public override CallResult Process(JObject input)
        {
            //调用IRIS获取医保各项金额
            if (mIS.getSumFee(out errMsg) != 0)
            {
                outParam = JsonHelper.setExceptionJson(-1, "获取医保费用各项汇总金额", errMsg).ToString();
                return Exception(outParam);
            }
            JObject joSumFee = JObject.Parse(errMsg);

            if ((JsonHelper.getDestValue(joSumFee, "data.Sumamt") == "") || (JsonHelper.getDestValue(joSumFee, "data.Sumamt") == "0"))
            {
                outParam = "未检测到上传费用！";
                return Exception(outParam);
            }

            if (mIS.queryRegisterInfo(1, out outParam) != 0)
            {
                outParam = JsonHelper.setExceptionJson(-1, "查询患者云平台登记信息", outParam).ToString();
                return Exception(outParam);
            }

            JObject joReg = JObject.Parse(outParam);
            Global.pat.medType = JsonHelper.getDestValue(joReg, "data.MedicalType");
            Global.pat.insuType = JsonHelper.getDestValue(joReg, "data.InsuType");

            if ((Global.pat.mdtrtcertType == "") || (Global.pat.mdtrtcertNO == ""))
            {
                Global.pat.mdtrtcertType = JsonHelper.getDestValue(joReg, "data.CertificateType");
                Global.pat.mdtrtcertNO = JsonHelper.getDestValue(joReg, "data.CertificateNO");
            }

            //Global.pat.mdtrtcertType = JsonHelper.getDestValue(joReg, "data.CertificateType");
            //Global.pat.mdtrtcertNO = JsonHelper.getDestValue(joReg, "data.CertificateNO");

            Global.pat.certType = JsonHelper.getDestValue(joReg, "data.CertificateType");
            Global.pat.certNO = JsonHelper.getDestValue(joReg, "data.CertificateNO");  //影响后面的验密 ，
            Global.pat.insuplc_admdvs = JsonHelper.getDestValue(joReg, "data.InsuranceAreaCode");
            Global.pat.psn_type = Global.pat.insuType;   //后面再改

            //if (Global.pat.RYorCY == "2")
            //{
            //    Global.pat.DiseasecCode = JsonHelper.getDestValue(joReg, "data.DiseasecCode");
            //    Global.pat.DiseasecName = JsonHelper.getDestValue(joReg, "data.DiseasecName");
            //}

            if ((Global.pat.medType == "2101") && (JsonHelper.getDestValue(joReg, "data.DiseasecCode") == "") && (Global.pat.RYorCY == "2"))
            {
                Global.pat.DiseasecCode = JsonHelper.getDestValue(joReg, "data.MainDiagCode");
                Global.pat.DiseasecName = JsonHelper.getDestValue(joReg, "data.MainDiagName");
            }

            //调用服务获取门诊诊断信息
            string diagnoses;
            if (hIS.getPatDiagnoses(Global.pat, out diagnoses) != 0)
            {
                outParam = JsonHelper.setExceptionJson(-1, "getPatDiagnoses", diagnoses).ToString();
                return Exception(outParam);
            }
            JObject joDiagnoses = JObject.Parse(diagnoses);

            JObject joHisRtnInfo = (JObject)joDiagnoses.DeepClone();
            JArray jaDiagnoses = JArray.Parse(JsonHelper.getDestValue(joHisRtnInfo, "diseinfo"));
            //从费用核查获取，可以先按照默认走一遍试试

            //  对诊断数组进行转换 转换下主要诊断
            JArray jaConvertedDiagnoses = new JArray();
            string dscg_maindiag_code = "", dscg_maindiag_name = "";
            for (int i = 0; i < jaDiagnoses.Count; i++)
            {
                string diag_type = JsonHelper.getDestValue((JObject)jaDiagnoses[i], "diag_type");
                switch (diag_type)
                {
                    case "1":
                        {
                            jaDiagnoses[i]["diag_type_name"] = new JObject();
                            jaDiagnoses[i]["diag_type_name"] = "西医主要诊断";
                            break;
                        }
                    case "2":
                        {
                            jaDiagnoses[i]["diag_type_name"] = new JObject();
                            jaDiagnoses[i]["diag_type_name"] = "西医其他诊断";
                            break;
                        }
                    case "3":
                        {
                            jaDiagnoses[i]["diag_type_name"] = new JObject();
                            jaDiagnoses[i]["diag_type_name"] = "中医主病诊断";
                            break;
                        }
                    case "4":
                        {
                            jaDiagnoses[i]["diag_type_name"] = new JObject();
                            jaDiagnoses[i]["diag_type_name"] = "中医主证诊断";
                            break;
                        }
                }

                //出院登记 取出院诊断信息
                if (Global.pat.RYorCY == "2")
                {
                    if (jaDiagnoses[i]["diaTypeCode"].ToString() == "DIS") //ADD 入院 OPD 门诊 DIS 出院
                    {
                        jaConvertedDiagnoses.Add(jaDiagnoses[i]);
                    }
                }
                else
                {
                    if (jaDiagnoses[i]["diaTypeCode"].ToString() == "ADD") //ADD 入院 OPD 门诊 DIS 出院
                    {
                        jaConvertedDiagnoses.Add(jaDiagnoses[i]);
                    }
                }
            }

            for (int i = 0; i < jaConvertedDiagnoses.Count; i++)
            {
                jaConvertedDiagnoses[i]["diag_srt_no"] = i + 1;
                if (jaConvertedDiagnoses[i]["maindiag_flag"].ToString() == "1")
                {
                    dscg_maindiag_code = jaConvertedDiagnoses[i]["diag_code"].ToString();
                    dscg_maindiag_name = jaConvertedDiagnoses[i]["diag_name"].ToString();
                }
                //增加就诊ID
                jaConvertedDiagnoses[i]["mdtrt_id"] = new JObject();
                jaConvertedDiagnoses[i]["mdtrt_id"] = Global.pat.mdtrtID;
            }

            //费用核查
            //查询费用核查信息 regType -1表示查询全部明细
            JArray jaDisRegAuditDetail;
            int disRegAuditDetailCount =0;
            JObject joAuditInfo;
            if (mIS.queryDischargeAuditInfo(out errMsg) != 0)
            {
                return Exception(errMsg) ;
            }
            else
            {
                JObject joRtn = JObject.Parse(errMsg);
                joAuditInfo = JObject.Parse(JsonHelper.getDestValue(joRtn, "result.AuditInfo"));
                //jaAdmRegAuditDetail = JArray.Parse(JsonHelper.getDestValue(joRtn, "result.AdmReg"));
                jaDisRegAuditDetail = JArray.Parse(JsonHelper.getDestValue(joRtn, "result.DisReg"));
                //jaOutpatRegAuditDetail = JArray.Parse(JsonHelper.getDestValue(joRtn, "result.OutpatReg"));
                //admRegAuditDetailCount = int.Parse(JsonHelper.getDestValue(joRtn, "result.AdmRegCount"));
                disRegAuditDetailCount = int.Parse(JsonHelper.getDestValue(joRtn, "result.DisRegCount"));
                //outpatRegAuditDetailCount = int.Parse(JsonHelper.getDestValue(joRtn, "result.OutpatRegCount"));
            }

            int auditStatus = int.Parse(JsonHelper.getDestValue(joAuditInfo, "AuditStatus"));
            string memo = JsonHelper.getDestValue(joAuditInfo, "Memo");

            if (auditStatus == 0)
            {
                return Exception("本次就诊未进行出院审核，请联系服务人员处理！");
            }

            if (auditStatus == -1)
            {
                return Exception($"本次就诊未通过出院审核,原因为{memo}，请联系服务人员处理！");
            }

            string personSettlementWay = "";
            string halfwaySettlementFlag = "";
            string personAccountUsedFlag = "";
            foreach (JObject jo in jaDisRegAuditDetail)
            {
                //if (jo["DetailCode"].ToString() == "insutype")
                //{
                //    Global.pat.insuType = jo["Value"].ToString();
                //}

                if (jo["DetailCode"].ToString() == "med_type")
                {
                    Global.pat.medType = jo["Value"].ToString();
                }
                if (jo["DetailCode"].ToString() == "dise_codg")
                {
                    Global.pat.DiseasecCode = jo["Value"].ToString();
                }
                if (jo["DetailCode"].ToString() == "dise_name")
                {
                    Global.pat.discDiagName = jo["Value"].ToString();
                }
                if (jo["DetailCode"].ToString() == "oprn_oprt_code")
                {
                    Global.pat.operCode = jo["Value"].ToString();
                }

                if (jo["DetailCode"].ToString() == "oprn_oprt_name")
                {
                    Global.pat.operName = jo["Value"].ToString();
                }
                if (jo["DetailCode"].ToString() == "dise_type_code")
                {
                    Global.pat.DiseasecType = jo["Value"].ToString();
                }
                if (jo["DetailCode"].ToString() == "mid_setl_flag")
                {
                    halfwaySettlementFlag = jo["Value"].ToString();
                }
                if (jo["DetailCode"].ToString() == "acct_used_flag")
                {
                    personAccountUsedFlag = jo["Value"].ToString();
                }
                if (jo["DetailCode"].ToString() == "psn_setlway")
                {
                    personSettlementWay = jo["Value"].ToString();
                }
            }

            if (string.IsNullOrEmpty(personSettlementWay))
            {
                return Exception("出院审核未设置个人结算方式");
            }
            if (string.IsNullOrEmpty(halfwaySettlementFlag))
            {
                return Exception("出院审核未设置中途结算方式");
            }
            if (string.IsNullOrEmpty(personAccountUsedFlag))
            {
                return Exception("出院审核未设置账户支付方式");
            }

            if (string.IsNullOrEmpty(Global.pat.medType))
            {
                return Exception("出院审核未设置医疗类别");
            }


            JObject joDscgInfo = new JObject();
            joDscgInfo.Add("mdtrt_id", Global.pat.mdtrtID);
            joDscgInfo.Add("psn_no", Global.pat.psn_no);            //人员编号
            joDscgInfo.Add("insutype", Global.pat.insuType);        //险种类型
                                                                    //joDscgInfo.Add("coner_name", JsonHelper.getJsonValue(joHisPatInfo, "coner_name"));          //联系人姓名
                                                                    //joDscgInfo.Add("tel", JsonHelper.getJsonValue(joHisPatInfo, "tel"));          //联系电话
            joDscgInfo.Add("endtime", Global.Set.hisDischargeTime);          //结束时间DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            joDscgInfo.Add("dise_codg", Global.pat.disCode);          //病种编码
            joDscgInfo.Add("dise_name", Global.pat.disName);          //病种名称
            joDscgInfo.Add("oprn_oprt_code", Global.pat.operCode);          //手术操作代码
            joDscgInfo.Add("oprn_oprt_name", Global.pat.operName);          //手术操作名称
            joDscgInfo.Add("fpsc_no", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.fpsc_no"));          //计划生育服务证号
            joDscgInfo.Add("matn_type", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.matn_type"));          //生育类别
            joDscgInfo.Add("birctrl_type", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.birctrl_type"));          //计划生育手术类别
            joDscgInfo.Add("latechb_flag", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.latechb_flag"));          //晚育标志
            joDscgInfo.Add("geso_val", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.geso_val"));          //孕周数
            joDscgInfo.Add("fetts", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.fetts"));          //胎次
            joDscgInfo.Add("fetus_cnt", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.fetus_cnt"));          //胎儿数
            joDscgInfo.Add("pret_flag", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.pret_flag"));          //早产标志
            joDscgInfo.Add("birctrl_matn_date", "");          //计划生育手术或生育日期 JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.birctrl_matn_date") 20230228医保中心校验传正确时间或空
            joDscgInfo.Add("cop_flag", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.dise_type_code"));          //伴有并发症标志
            joDscgInfo.Add("dscg_dept_codg", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.adm_dept_codg"));          //出院科室编码
            joDscgInfo.Add("dscg_dept_name", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.adm_dept_name"));          //出院科室名称
            joDscgInfo.Add("dscg_bed", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.adm_bed"));          //出院床位
            joDscgInfo.Add("dscg_way", "1");          //离院方式
            joDscgInfo.Add("die_date", "");          //死亡日期
            joDscgInfo.Add("exp_content", "");          //字段扩展
            joDscgInfo.Add("insuplc_admdvs", Global.pat.insuplc_admdvs);          //参保地医保区划
            joDscgInfo.Add("mdtrtarea_admvs", Global.inf.areaCode);          //就医地医保区划

            JObject joRegInpar = new JObject();
            joRegInpar.Add("dscginfo", joDscgInfo);
            joRegInpar.Add("diseinfo", jaConvertedDiagnoses);


            //结算入参
            JObject joSetlInpar = new JObject();
            joSetlInpar.Add("psn_no", Global.pat.psn_no);
            joSetlInpar.Add("chrg_bchno", Global.pat.adm_Dr.ToString());
            joSetlInpar.Add("mdtrt_cert_type", Global.pat.mdtrtcertType);
            joSetlInpar.Add("mdtrt_cert_no", Global.pat.mdtrtcertNO);
            joSetlInpar.Add("med_type", Global.pat.medType);
            joSetlInpar.Add("medfee_sumamt", JsonHelper.getDestValue(joSumFee, "data.Sumamt"));
            joSetlInpar.Add("psn_setlway", personSettlementWay); //结算方式
            joSetlInpar.Add("mdtrt_id", Global.pat.mdtrtID);
            joSetlInpar.Add("acct_used_flag", personAccountUsedFlag);//个人账户使用标志
            joSetlInpar.Add("insutype", Global.pat.insuType);//险种类型
            joSetlInpar.Add("insuplc_admdvs", Global.pat.insuplc_admdvs);
            joSetlInpar.Add("mdtrtarea_admvs", Global.inf.areaCode);
            joSetlInpar.Add("invono", "");
            joSetlInpar.Add("mid_setl_flag", halfwaySettlementFlag);
            joSetlInpar.Add("fulamt_ownpay_amt", JsonHelper.getDestValue(joSumFee, "data.FullOwnPayAmount"));
            joSetlInpar.Add("overlmt_selfpay", JsonHelper.getDestValue(joSumFee, "data.OverLimitAmount"));
            joSetlInpar.Add("preselfpay_amt", JsonHelper.getDestValue(joSumFee, "data.PreSelfPayAmount"));
            joSetlInpar.Add("dscgTime", Global.Set.hisDischargeTime);

            JObject joDataExp = new JObject();
            joDataExp.Add("acct_payamt", "0.00");
            joDataExp.Add("cla_trt_flag", "");

            joSetlInpar.Add("exp_content", joDataExp); //11111

            JObject joOut = new JObject();
            joOut.Add("DischargeRegister", joRegInpar);
            joOut.Add("Settlement", joSetlInpar);
            joOut.Add("errorCode", 0);
            outParam = joOut.ToString();
            return Success();

        }
    }
}
