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

namespace PTMedicalInsurance.Business.Core.SelfServiceMachine.Process.OutPat
{
    class OrganizePatientRegistrationInfo : AbstractProcess
    {
        public override CallResult Process(JObject input)
        {
            //调用服务获取门诊诊断信息
            string diagnoses;
            if (hIS.getPatDiagnoses(Global.pat, out diagnoses) != 0)
            {
                outParam = JsonHelper.setExceptionJson(-1, "getPatDiagnoses", diagnoses).ToString();
                return Exception(-1,"",outParam);
            }
            JObject joHisRtnInfo = JObject.Parse(diagnoses);


            //组织入参
            JObject joReg = new JObject();
            try
            {
                JArray jaDiagnoses = JArray.Parse(JsonHelper.getDestValue(joHisRtnInfo, "diseinfo"));

                //结算方式
                string psn_setlway = "01";//按项目结算

                //转换下主要诊断
                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;
                            }
                    }

                }


                string diseCodg = "";
                string diseName = "";
                ////如果是慢性病患者，查询慢病信息
                //if (Global.pat.medType == "14")
                //{
                    
                //    string chronicDieseaseInfo = "";
                //    if (hBus.QueryOPChronicDisease(out chronicDieseaseInfo) != 0)
                //    {
                //        outParam = "检测到患者为慢病患者，但查询中心的慢病信息出错！";
                //        return Exception();
                //    }

                //    DataTable dtChronicDiesease = JsonConvert.DeserializeObject<DataTable>(chronicDieseaseInfo);
                //    Global.writeLog("dtChronicDiesease:" + dtChronicDiesease.Rows.Count.ToString()); ;
                //    // 获取当前日期
                //    DateTime today = DateTime.Today;

                //    var filteredRows = dtChronicDiesease.AsEnumerable()
                //        .Where(row =>
                //        {
                //            var endDateStr = row.Field<string>("enddate");
                //            if (string.IsNullOrEmpty(endDateStr)) return false;

                //            if (DateTime.TryParse(endDateStr, out DateTime endDate))
                //            {
                //                return endDate >= DateTime.Today;
                //            }

                //            return false;
                //        });
                    
                //    // 构建新的 DataTable
                //    DataTable filteredTable = filteredRows.Any()
                //        ? filteredRows.CopyToDataTable()
                //        : dtChronicDiesease.Clone(); // 空数据时返回结构一致的空表
                //    Global.writeLog(filteredTable.Rows.Count.ToString());
                //    if (filteredTable.Rows.Count == 0)
                //    {
                //        outParam = "该患者为慢病处方！但在中心未查询到慢病信息！请至人工窗口处理！";
                //        return Exception();
                //    }
                //    else if (filteredTable.Rows.Count > 1)
                //    {
                //        outParam = "该患者为慢病处方！但在中心未查询到多条慢病信息！请至人工窗口处理！";
                //        return Exception();
                //    }
                //    else
                //    {
                //        diseCodg = filteredTable.Rows[0]["opsp_dise_code"].ToString();
                //        diseName = filteredTable.Rows[0]["opsp_dise_name"].ToString();
                //    }
                //}


                
                #region 组织挂号入参
                JObject joRegInpar = new JObject();
                string occurTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                joRegInpar.Add("psn_no", Global.pat.psn_no);
                joRegInpar.Add("insutype", Global.pat.insuType);
                joRegInpar.Add("begntime", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.begntime"));//挂号时间 occurTime
                joRegInpar.Add("mdtrt_cert_type", Global.pat.mdtrtcertType);
                joRegInpar.Add("mdtrt_cert_no", Global.pat.mdtrtcertNO);


                joRegInpar.Add("ipt_otp_no", Global.pat.adm_Dr.ToString());

                joRegInpar.Add("atddr_no", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.atddr_no"));
                joRegInpar.Add("dr_name", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.chfpdr_name"));
                joRegInpar.Add("dept_code", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.adm_dept_codg"));
                joRegInpar.Add("dept_name", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.adm_dept_name"));
                joRegInpar.Add("exp_content", "");
                joRegInpar.Add("caty", "A10");

                #endregion

                #region 组织就诊信息入参
                JObject joMdtrtinfo = new JObject();
                for (int i = 0; i < jaDiagnoses.Count; i++)
                {
                    jaDiagnoses[i]["vali_flag"] = new JObject();
                    jaDiagnoses[i]["vali_flag"] = "1";
                }

                joMdtrtinfo.Add("mdtrt_id", Global.pat.mdtrtID);
                joMdtrtinfo.Add("psn_no", Global.pat.psn_no);          //人员编号
                joMdtrtinfo.Add("med_type", Global.pat.medType);          //医疗类别
                joMdtrtinfo.Add("begntime", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.begntime"));          //开始时间
                joMdtrtinfo.Add("main_cond_dscr", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.main_cond_dscr"));          //主要病情描述
                joMdtrtinfo.Add("dise_codg", diseCodg);          //病种编码
                joMdtrtinfo.Add("dise_name", diseName);          //病种名称
                joMdtrtinfo.Add("birctrl_type", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.birctrl_type"));          //计划生育手术类别
                                                                                             //joMdtrtinfo.Add("birctrl_matn_date", "");          //计划生育手术或生育日期 JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.birctrl_matn_date") 20230228医保中心校验传正确时间或空
                joMdtrtinfo.Add("matn_type", JsonHelper.getDestValue(joHisRtnInfo, "mdtrtinfo.matn_type"));          //生育类别
                joMdtrtinfo.Add("expContent", "");          //字段扩展

                // 特殊2203A需要exp_content字段
                JObject ExportObj = new JObject();
                ExportObj.Add("dise_reim_mon", "");
                ExportObj.Add("deve_flag", "");
                ExportObj.Add("otp_reim_flag", "");
                ExportObj.Add("local_dise", "");              //单病种编码
                ExportObj.Add("ifen_flag", "");                 //传染性标志 
                                                                //ExportObj.Add("cla_trt_flag", frmReg.claTrtFlag);       //分级诊疗标志
                ExportObj.Add("trum_flag", "0");          //外伤标志
                                                                        //ExportObj.Add("ipt_type", frmReg.iptTypeCode);          //住院类型（离院）
                ExportObj.Add("rel_ttp_flag","0");       //涉及第三方标志
                ExportObj.Add("mdtrt_grp_type", "");   //就诊人群类型
                ExportObj.Add("elec_bill_code", "");   //电子票据代码
                ExportObj.Add("elec billno_code", ""); //电子票据号码
                ExportObj.Add("otp_er_refl_flag", ""); //门诊转急诊

                joMdtrtinfo.Add("exp_content", ExportObj);          //字段扩展
                #endregion

                #region 组织结算入参
                JObject joSetlInpar = new JObject();
                joSetlInpar.Add("psn_no", Global.pat.psn_no);
                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", "");
                joSetlInpar.Add("psn_setlway", psn_setlway); //结算方式
                joSetlInpar.Add("mdtrt_id", Global.pat.mdtrtID);
                joSetlInpar.Add("chrg_bchno", Global.pat.adm_Dr.ToString());
                joSetlInpar.Add("acct_used_flag", "1");//个人账户使用标志
                joSetlInpar.Add("insutype", Global.pat.insuType);//险种类型
                joSetlInpar.Add("pub_hosp_rfom_flag", "");
                joSetlInpar.Add("exp_content", "");
                joSetlInpar.Add("mdtrt_mode", "0");

                #endregion

                joReg.Add("data", joRegInpar);
                joReg.Add("mdtrtinfo", joMdtrtinfo);
                joReg.Add("diseinfo", jaDiagnoses);
                joReg.Add("settlement", joSetlInpar);
                joReg.Add("patInfo", input);
                outParam = joReg.ToString();

                return Success();

            }
            catch (Exception ex)
            {
                outParam = "登记界面显示异常：" + ex.Message;
                return Exception(-1,"",outParam);
            }
        }
    }
}
