using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.Variables;
using PTMedicalInsurance.FormSetter;

namespace PTMedicalInsurance.Forms
{
    public partial class HospitalRegister : Form
    {
        public string DrCode = "", DrName = "", DrInsuCode = "", DrCertNo = "";

        private HisMainBusiness hBus = new HisMainBusiness();
        private InvokeHelper invoker = new InvokeHelper();
        private HisIrisServices hIS = new HisIrisServices();
        private MIIrisServices mIS = new MIIrisServices();

        public HospitalRegister()
        {
            InitializeComponent();
        }

        private void SetDBLKCombox(ref PTControl.DBLookupCombox dblcbx, DataTable dtUserInfo)
        {
            dblcbx.sDisplayField = "Code,descripts,insuUserCode,credNo";
            dblcbx.sDisplayMember = "姓名";
            dblcbx.sKeyWords = "Code,descripts";
            dblcbx.DataSource = dtUserInfo;
            dblcbx.RowFilterVisible = true;
            dblcbx.TextBox.Width = 400;
            dblcbx.DataGridView.Width = 400;
            dblcbx.DataGridView.Columns[0].Name = "编码";
            dblcbx.DataGridView.Columns[1].Name = "姓名";
            dblcbx.DataGridView.Columns[2].Name = "医保医师代码";
            dblcbx.DataGridView.Columns[3].Name = "证件号码";
            dblcbx.DataGridView.Columns[0].Width = 55;
            dblcbx.DataGridView.Columns[1].Width = 55;
            dblcbx.DataGridView.Columns[2].Width = 115;
            dblcbx.DataGridView.Columns[3].Width = 200;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void HospitalRegister_Load(object sender, EventArgs e)
        {
            //WindowState = FormWindowState.Maximized;
            dt_Begin.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_End.Value = DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(1).AddDays(-1);

            dt_St.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_Et.Value = DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(1).AddDays(-1);

            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfRestrictedDrugsInfo(dgv_MainData);
            grdSetter.SetHeaderTextOfReferralDrugsInfo(dgvReferralRecordDrugs);
            grdSetter.DatagridviewColumnWidthAdaptation(dgvReferralRecordDrugs);

            LoadRestrictedDrugsInfo(GetRestrictedDrugsInfo());

            cbb_DclaSouc.SelectedIndex = 0;
            cbb_CertType.SelectedIndex = 0;
            cbb_SpdiagFlag.SelectedIndex = 0;
            cbb_BizAppyType.SelectedIndex = 10;

            rg_type.SelectedIndex = 1;
            DrCode = "140005";

            //获取医院用户信息
            JObject joUserInfo = hIS.GetHosUserInfo("");
            DataTable dt = (DataTable)joUserInfo["result"]["rows"].ToObject(typeof(DataTable));
            SetDBLKCombox(ref cbx_DocInfo, dt);
        }

        /// <summary>
        /// 获取当前医院限制药品信息
        /// </summary>
        public JObject GetRestrictedDrugsInfo()        
        {
            string errMsg;
            JObject joTmp = new JObject();
            joTmp.Add("medCode", "");
            joTmp.Add("medDesc", "");
            joTmp.Add("subCatID", "");
            joTmp.Add("tipState", "1");

            JObject joTmp1 = new JObject();
            joTmp1.Add("pageSize", "100");
            joTmp1.Add("currentPage", "1");
            joTmp1.Add("sortColumn", "");
            joTmp1.Add("sortOrder", "");

            JObject joRtn = invoker.invokeHISService(JsonHelper.setIrisInpar_("pr01002", joTmp, joTmp1).ToString(), "获取限制药品信息");
            if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
            {
                errMsg = "获取限制药品信息失败，请联系管理员!" + errMsg;    
                return JsonHelper.setIrisReturnValue(-1, "", JObject.Parse(errMsg));
            }

            if (joRtn["data"].ToString() == "[]")
            {
                errMsg = "查询限制药品信息结果为空!";
                return JsonHelper.setIrisReturnValue(-1, "查询限制药品信息结果为空", null); 
            }

            return joRtn;
        }

        public void LoadRestrictedDrugsInfo(JObject joRtn)
        {
            DataTable dt = (DataTable)joRtn["data"].ToObject(typeof(DataTable));
            dgv_MainData.DataSource = dt;
        }

        private void btnReadCard_Click(object sender, EventArgs e)
        {
            if (hBus.readCard(out string outParam) != 0)
            {
                MessageBox.Show("读卡失败:" + outParam);
                return;
            }
            else
            {
               string patInfo = outParam;

                //展示患者信息界面
                if (hBus.showPatInfo(patInfo, out outParam) == 0)
                {
                    patInfo = outParam;

                    if (hBus.setGlobalPatAfaterShowPatInfo(patInfo, out string errMsg) != 0)
                    {
                        MessageBox.Show("患者参保信息赋值失败：" + errMsg);
                        return;
                    }

                    tb_Name.Text = Global.pat.name;
                    tb_InsuAdmvs.Text = Global.pat.insuplc_admdvs;
                    tb_PsnNo.Text = Global.pat.psn_no;
                    tb_CertNo.Text = Global.pat.certNO;
                }
            }
        }

        private int CheckParamValue(out string errMsg)
        {
            errMsg = "";
            int iRes = -1;
            Boolean bPass = false;
            if ((tb_Name.Text == "") || (tb_InsuAdmvs.Text == "") || (tb_PsnNo.Text == ""))
            {
                errMsg = ("请先操作医保读卡获取参保信息！");
                return iRes;
            }
            if (dt_Begin.Text == "")
            {
                errMsg = ("开始时间不能为空！");
                return iRes;
            }
            if (dt_End.Text == "")
            {
                errMsg = ("截止时间不能为空！");
                return iRes;
            }
            if (tb_Tel.Text == "")
            {
                errMsg = ("联系电话不能为空！");
                return iRes;
            }
            if (cbb_DclaSouc.Text == "")
            {
                errMsg = ("申报来源不能为空！");
                return iRes;
            }
            if (tb_PsnNo.Text == "")
            {
                errMsg = ("医保人员编号不能为空！");
                return iRes;
            }
            if (cbx_DocInfo.Text == "")
            {
                errMsg = ("申请医师不能为空！");
                return iRes;
            }
            if (cbb_SpdiagFlag.Text == "")
            {
                errMsg = ("治疗标识不能为空！");
                return iRes;
            }
            DataTable dtHis = (DataTable)dgv_MainData.DataSource;
            for (int i = 0; i < dtHis.Rows.Count; i++)
            {
                //申请数量
                string cnt = dtHis.Rows[i]["Cnt"].ToString();

                if (int.Parse(cnt) > 0)
                    bPass = true;

                if ((cnt != "") && (cnt != "0"))
                {
                    string HISCode = dtHis.Rows[i]["medCode"].ToString(); //HIS编码
                    string hilist_name = dtHis.Rows[i]["medDesc"].ToString(); //药品名称          

                    JObject joRtn = mIS.queryInsuContrastDirInfo(HISCode, 1);
                    if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                    {
                        errMsg = (hilist_name + "：未进行医保对照！");
                        return iRes;
                    }
                    else
                    {
                        string hilist_code = JsonHelper.getDestValue(joRtn, "result.data[0].InsuCode");
                        string list_type = JsonHelper.getDestValue(joRtn, "result.data[0].listType");
                    }
                }
            }
            if (bPass == false)
            {
                errMsg = ("申请数量不能都为0！");
                return iRes;
            }

            return 0;
        }

        private void QueryReffalDrugsInfo()
        {
            string sqlStr = " SELECT * FROM BS_ReferralRecordDrugs ";
            sqlStr = sqlStr + "WHERE Hospital_Dr=" + Global.inf.hospitalDr; //Upload=Y And 
            sqlStr = sqlStr + " and Interface_Dr= " + Global.inf.interfaceDr;
            sqlStr = sqlStr + " and OccurDateTime>'" + dt_St.Text + "'";
            sqlStr = sqlStr + " and OccurDateTime<'" + dt_Et.Text + "'";
            if (tb_CertnoQuery.Text != "")
            {
                sqlStr = sqlStr + " and Certno='" + tb_CertnoQuery.Text + "'";
            }

            switch (rg_type.SelectedIndex)
            {
                case 1:
                    {
                        sqlStr = sqlStr + " and ValidFlag='1'";
                        break;
                    }
                case 2:
                    {
                        sqlStr = sqlStr + " and ValidFlag='-1'";
                        break;
                    }
            }

            sqlStr = sqlStr + " Order By ID DESC";

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "02030012");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询特药备案申请信息");

            DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
            dgvReferralRecordDrugs.DataSource = dt;

            if (dt.Rows.Count <= 0)
                dgvReferralRecordDrugs.DataSource = null;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            QueryReffalDrugsInfo();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (dgvReferralRecordDrugs.DataSource == null)
            {
                MessageBox.Show("请先查询特药备案申请信息！");
                return;
            }

            if ((rtb_CancelReason.Text == "") || (rtb_CancelReason.Text == "请输入撤销原因"))
            {
                MessageBox.Show("请输入撤销原因！");
                return;
            }

            string OutPut, errMsg;
            int i = dgvReferralRecordDrugs.CurrentRow.Index;
            DataTable dt = (DataTable)dgvReferralRecordDrugs.DataSource;
            string RecordID = dt.Rows[i]["RecordDr"].ToString();
            string PersonalNO = dt.Rows[i]["PersonalNO"].ToString();
            string ID = dt.Rows[i]["ID"].ToString();
            string Memo = rtb_CancelReason.Text;
  
            JObject joData = new JObject();
            joData.Add("trt_dcla_detl_sn", RecordID);                  //待遇申报明细流水号
            joData.Add("psn_no", PersonalNO);        //医保个人编码
            joData.Add("memo", Memo);                //撤销原因         

            JObject joDataInput = new JObject();
            joDataInput.Add("data", joData);

            string sInput = JsonHelper.setCenterInpar("2508_A", joDataInput);
            JObject joRtn = invoker.invokeCenterService("2508_A", sInput);
            if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
            {
                MessageBox.Show("特药备案申请撤销失败：" + errMsg);
                return;
            }
            else
            {
                if (CancelReferralRecord(joDataInput, ID, RecordID, out errMsg) != 0)                
                {
                    MessageBox.Show("特药备案申请撤销成功，更新数据库失败：" + errMsg);
                    return;
                }
                else
                {
                    MessageBox.Show("特药备案申请撤销成功！");
                    QueryReffalDrugsInfo();
                }
            }
        }

        private int SaveReferralRecord(JObject joInParam,JObject joRtnParam,out string OutMsg)
        {
            int iRes;
            string errMsg;           

            //解析返回值
            string trt_dcla_detl_sn = JsonHelper.getDestValue(joRtnParam, "output.result.trt_dcla_detl_sn"); //待遇申报明细流水号

            JObject joInPut = new JObject();

            joInPut.Add("Hospital_Dr", Global.inf.hospitalDr);
            joInPut.Add("Interface_Dr", Global.inf.interfaceDr);
            joInPut.Add("PatientName", JsonHelper.getDestValue(joInParam, "psn_name"));
            joInPut.Add("PersonalNO", JsonHelper.getDestValue(joInParam, "psn_no"));
            joInPut.Add("CertNo", JsonHelper.getDestValue(joInParam, "certno"));
            joInPut.Add("InsuDrCode", JsonHelper.getDestValue(joInParam, "med_insu_dir_list[0].memo.dr_code"));
            joInPut.Add("RecordDr", trt_dcla_detl_sn);
            joInPut.Add("HISCode", JsonHelper.getDestValue(joInParam, "med_insu_dir_list[0].memo.dr_name"));
            joInPut.Add("InsuCode", JsonHelper.getDestValue(joInParam, "med_insu_dir_list[0].hilist_code"));
            joInPut.Add("InsuName", JsonHelper.getDestValue(joInParam, "med_insu_dir_list[0].hilist_name"));
            joInPut.Add("ValidFlag", 1);
            joInPut.Add("UpdateUserID", Global.user.ID);
            joInPut.Add("OccurDateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            joInPut.Add("InParam", joInParam.ToString()); //dt_Begin.Value.ToString("yyyy-MM-dd")
            joInPut.Add("BeginDate", dt_Begin.Value.ToString("yyyy-MM-dd"));
            joInPut.Add("EndDate", dt_End.Value.ToString("yyyy-MM-dd"));

            JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("02030011", joInPut).ToString(), "插入特药备案申请信息");

            if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
            {
                OutMsg = errMsg;
                return -1;
            }
            else
            {
                OutMsg = joRtn.ToString();
                return 0;
            }
        }

        private int CancelReferralRecord(JObject joInParam, string ID, string trtDclaDetlSn, out string OutMsg)        
        {
            string errMsg;

            JObject joInPut = new JObject();

            joInPut.Add("Hospital_Dr", Global.inf.hospitalDr);
            joInPut.Add("Interface_Dr", Global.inf.interfaceDr);
            joInPut.Add("RecordDr", trtDclaDetlSn);
            joInPut.Add("ValidFlag", -1);
            joInPut.Add("ID", ID);
            joInPut.Add("UpdateUserID", Global.user.ID);
            joInPut.Add("OccurDateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            joInPut.Add("InParam", joInParam.ToString());

            JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("02030013", joInPut).ToString(), "更新特药备案申请信息");

            if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
            {
                OutMsg = errMsg;
                return -1;
            }
            else
            {
                OutMsg = joRtn.ToString();
                return 0;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string errMsg, outParam;

            //校验入参
            if (CheckParamValue(out errMsg) != 0)
            {
                MessageBox.Show(errMsg);
                return;
            }

            //治疗标识
            string SpdiagFlag = cbb_SpdiagFlag.Text.Trim().Substring(0, 4);
            //申报来源
            string DclaSouc = cbb_DclaSouc.Text.Trim().Substring(0, 4).Replace(" ","");
            //申请业务类型
            string BizAppyType= cbb_BizAppyType.Text.Trim().Substring(0, 4).Replace(" ", "");

            JArray ja_med_insu_dir_list = new JArray();
            DataTable dtHis = (DataTable)dgv_MainData.DataSource;
            for (int i = 0; i < dtHis.Rows.Count; i++)
            {
                string cnt = dtHis.Rows[i]["Cnt"].ToString();  //申请数量
                string HISCode = dtHis.Rows[i]["medCode"].ToString(); //HIS编码
                string hilist_name = dtHis.Rows[i]["medDesc"].ToString(); //药品名称          
                string cnt_prcunt = dtHis.Rows[i]["medUnitDesc"].ToString(); //单位

                if ((cnt != "") && (cnt != "0"))
                {
                    JObject joHISRtn = mIS.queryInsuContrastDirInfo(HISCode, 1);
                    string hilist_code = JsonHelper.getDestValue(joHISRtn, "result.data[0].InsuCode");
                    string list_type = JsonHelper.getDestValue(joHISRtn, "result.data[0].listType");

                    if (list_type == "")
                        list_type = "101";

                    //备注memo
                    JObject joMemo = new JObject();
                    joMemo.Add("spdiag_flag", SpdiagFlag); //治疗标识
                    joMemo.Add("dr_name", DrName); //医保医师姓名
                    joMemo.Add("dr_code", DrInsuCode); //医保医师代码
                    joMemo.Add("memo", "62"); //用法

                    //医保目录列表med_insu_dir_list
                    JObject jo_med_insu_dir_list = new JObject();
                    jo_med_insu_dir_list.Add("cnt", cnt);
                    jo_med_insu_dir_list.Add("hilist_name", hilist_name);
                    jo_med_insu_dir_list.Add("hilist_code", hilist_code);
                    jo_med_insu_dir_list.Add("cnt_prcunt", cnt_prcunt);
                    jo_med_insu_dir_list.Add("list_type", list_type);
                    jo_med_insu_dir_list.Add("memo", joMemo);

                    ja_med_insu_dir_list.Add(jo_med_insu_dir_list);
                }                      
            }
           
            //定点医疗机构列表psn_fixed_evt_detl_dtos
            JObject jo_psn_fixed_evt_detl_dtos = new JObject();
            jo_psn_fixed_evt_detl_dtos.Add("evtsn", Global.inf.hospitalNO);
            jo_psn_fixed_evt_detl_dtos.Add("fixmedins_code", Global.inf.hospitalNO);
            jo_psn_fixed_evt_detl_dtos.Add("fixmedins_name", Global.inf.hospitalName);
            JArray ja_psn_fixed_evt_detl_dtos = new JArray();
            ja_psn_fixed_evt_detl_dtos.Add(jo_psn_fixed_evt_detl_dtos);

            
            //组织调用2507_A特药备案申请入参
            JObject joInput = new JObject();
            joInput.Add("psn_no", tb_PsnNo.Text);
            joInput.Add("begndate", dt_Begin.Value.ToString("yyyy-MM-dd"));
            joInput.Add("enddate", dt_End.Value.ToString("yyyy-MM-dd"));
            joInput.Add("tel", tb_Tel.Text);
            joInput.Add("dcla_souc", DclaSouc);
            joInput.Add("biz_appy_type", BizAppyType);
            joInput.Add("addr", tb_Address.Text);
            joInput.Add("agnter_name", tb_Name_P.Text);
            joInput.Add("agnter_cert_type", "01");
            joInput.Add("agnter_certno", tb_CertNo.Text);
            joInput.Add("agnter_tel", "");
            joInput.Add("agnter_addr", "");
            joInput.Add("agnter_rlts", "");
            joInput.Add("psn_cert_type", "01");
            joInput.Add("certno", tb_CertNo.Text);
            joInput.Add("psn_name", tb_Name.Text);
            joInput.Add("gend", "");
            joInput.Add("naty", "01");
            joInput.Add("brdy", "");
            joInput.Add("emp_no", "");
            joInput.Add("emp_nme", "");
            joInput.Add("diag_code", "");
            joInput.Add("diag_name", "");
            joInput.Add("med_insu_dir_list", ja_med_insu_dir_list);
            joInput.Add("psn_fixed_evt_detl_dtos", ja_psn_fixed_evt_detl_dtos);

            JObject joData = new JObject();
            joData.Add("data", joInput);

            string sInput = JsonHelper.setCenterInpar("2507_A", joData);
            JObject joRtn = invoker.invokeCenterService("2507_A", sInput);
            if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
            {
                MessageBox.Show("特药备案申请失败：" + errMsg);
                return;
            }
            else
            {
                string trt_dcla_detl_sn = JsonHelper.getDestValue(joRtn, "output.result.trt_dcla_detl_sn");

                if (SaveReferralRecord(joInput, joRtn, out errMsg) != 0)
                {
                    JObject joInputData = new JObject();
                    joInputData.Add("trt_dcla_detl_sn", trt_dcla_detl_sn);                  //待遇申报明细流水号
                    joInputData.Add("psn_no", tb_PsnNo.Text);        //医保个人编码
                    joInputData.Add("memo", "备案信息填写错误");                //撤销原因         

                    JObject joDatahh = new JObject();
                    joDatahh.Add("data", joInputData);

                    string sInputData = JsonHelper.setCenterInpar("2508_A", joDatahh);
                    JObject joRtnData = invoker.invokeCenterService("2508_A", sInputData);
                    if (JsonHelper.parseCenterRtnValue(joRtnData, out errMsg) != 0)
                    {
                        MessageBox.Show("特药备案申请成功，保存到数据库失败，特药备案申请撤销失败：" + errMsg + "，请手动撤销已上传的特药备案申请后重新提交备案申请！");
                        return;
                    }
                    else
                    {
                        MessageBox.Show("特药备案申请成功，保存到数据库失败，特药备案申请撤销成功，请重新提交备案申请！");
                    }

                    return;
                }

                MessageBox.Show("特药备案申请成功");

            }     
        }        

        private void cbx_DocInfo_AfterSelector(object sender, PTControl.AfterSelectorEventArgs e)
        {
            DataGridViewRow row = e.Value as DataGridViewRow;
            DataRowView dataRow = row.DataBoundItem as DataRowView;

            DrCode = dataRow["Code"].ToString().Trim();      //HIS工号
            DrName = dataRow["descripts"].ToString().Trim();      //姓名
            DrInsuCode = dataRow["insuUserCode"].ToString().Trim();  //医保医师代码
            DrCertNo = dataRow["credNo"].ToString().Trim();    //身份证号

            cbx_DocInfo.Text = DrName;
        }
    }
}
