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

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

            cbb_CertType.SelectedIndex = 0;

            DrCode = "140005";

            //获取医院用户信息
            JObject joUserInfo = hIS.GetHosUserInfo("");
            DataTable dt = (DataTable)joUserInfo["result"]["rows"].ToObject(typeof(DataTable));
            SetDBLKCombox(ref cbx_DocInfo, 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_PsnNo.Text == "")
            {
                errMsg = ("医保人员编号不能为空！");
                return iRes;
            }
            if (cbx_DocInfo.Text == "")
            {
                errMsg = ("申请医师不能为空！");
                return iRes;
            }         

            return 0;
        }

        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 void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvReferralRecordDrugs.DataSource == null)
            {
                MessageBox.Show("请先查询特药登记信息！");
                return;
            }

            string OutPut, errMsg;
            int i = dgvReferralRecordDrugs.CurrentRow.Index;
            DataTable dt = (DataTable)dgvReferralRecordDrugs.DataSource;
            string RecordID = dt.Rows[i]["trt_dcla_detl_sn"].ToString();
            string PersonalNO = dt.Rows[i]["psn_no"].ToString(); 

            JObject joData = new JObject();
            joData.Add("trt_dcla_detl_sn", RecordID);                  //待遇申报明细流水号
            joData.Add("psn_no", PersonalNO);        //医保个人编码
            joData.Add("exp_content", "");                //扩展字段         

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

            string sInput = JsonHelper.setCenterInpar("3672", joDataInput);
            JObject joRtn = invoker.invokeCenterService("3672", sInput);
            if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
            {
                MessageBox.Show("删除特药登记信息失败：" + errMsg);
                return;
            }
            else
            {
                JObject joDataQ = new JObject();
                joDataQ.Add("psn_no", Global.pat.psn_no);        //医保个人编码
                joDataQ.Add("fixmedins_code", Global.inf.hospitalNO); //机构编号    
                joDataQ.Add("page_num", "1");  //分页页码   
                joDataQ.Add("page_size", "50");  //分页大小   
                joDataQ.Add("exp_content", "");  //扩展字段                                                       

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

                string sInputQ = JsonHelper.setCenterInpar("3673", joDataInputQ);
                JObject joRtnQ = invoker.invokeCenterService("3673", sInputQ);
                if (JsonHelper.parseCenterRtnValue(joRtnQ, out errMsg) != 0)
                {
                    MessageBox.Show("查询特药登记信息失败：" + errMsg);
                    return;
                }
                else
                {
                    DataTable dtQ = (DataTable)joRtn["output"]["result"].ToObject(typeof(DataTable));
                    dgvReferralRecordDrugs.DataSource = dtQ;

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

            MessageBox.Show("删除特药登记信息成功！");
        }



        private void btnInsuQuery_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;
                    }     

                    JObject joData = new JObject();
                    joData.Add("psn_no", Global.pat.psn_no);        //医保个人编码
                    joData.Add("fixmedins_code", Global.inf.hospitalNO); //机构编号    
                    joData.Add("page_num", "1");  //分页页码   
                    joData.Add("page_size", "50");  //分页大小   
                    joData.Add("exp_content", "");  //扩展字段                                                       

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

                    string sInput = JsonHelper.setCenterInpar("3673", joDataInput);
                    JObject joRtn = invoker.invokeCenterService("3673", sInput);
                    if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                    {
                        MessageBox.Show("查询特药登记信息失败：" + errMsg);
                        return;
                    }
                    else
                    {
                        DataTable dt = (DataTable)joRtn["output"]["result"].ToObject(typeof(DataTable));
                        dgvReferralRecordDrugs.DataSource = dt;

                        if (dt.Rows.Count <= 0)
                        {
                            MessageBox.Show("医保中心查询结果返回为空！");
                            dgvReferralRecordDrugs.DataSource = null;
                        }                          
                    } 
                }
            }
        }

        private void btnReadCard_Click_1(object sender, EventArgs e)
        {

        }

        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;
            }       
            
            //组织调用2507_A特药备案申请入参
            JObject joInput = new JObject();
            joInput.Add("psn_no", tb_PsnNo.Text);
            joInput.Add("psn_cert_type", "01");
            joInput.Add("certno", tb_CertNo.Text);
            joInput.Add("insutype", Global.pat.insuType);
            joInput.Add("emp_no", "");
            joInput.Add("emp_nme", "");
            joInput.Add("dr_code", DrInsuCode); //医师代码
            joInput.Add("dr_name", DrName); //医师姓名
            joInput.Add("begndate", dt_Begin.Value.ToString("yyyy-MM-dd"));
            joInput.Add("enddate", dt_End.Value.ToString("yyyy-MM-dd"));
            joInput.Add("diag_code", "");
            joInput.Add("diag_name", "");
            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("exp_content", "");

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

            string sInput = JsonHelper.setCenterInpar("3671", joData);
            JObject joRtn = invoker.invokeCenterService("3671", 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("exp_content", "特药登记信息填写错误");                //扩展字段      

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

                    string sInputData = JsonHelper.setCenterInpar("3672", joDatahh);
                    JObject joRtnData = invoker.invokeCenterService("3672", 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;
        }
    }
}
