using Newtonsoft.Json.Linq;
using System;
using System.IO;
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 PTMedicalInsurance.Common;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.FormSetter;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.Variables;



namespace PTMedicalInsurance.Forms
{
    public partial class MedInsuQuery : Form
    {
        DataTable dtExport;
        JObject joRtn10001 = new JObject();
        JObject joInput20002 = new JObject();
        public string patInfo = "", ReadCardOutParam = "", CertNo = "";
        public string presAdmLoc = "", presAdmDoc = "", presAdmID = "", presNo = "", hiRxno = "";
        public string DrCode = "", DrName = "", DrInsuCode = "", DrCertNo = "";

        //1.声明自适应类实例
        AutoResizeForm asc = new AutoResizeForm();
        private InvokeHelper invoker = new InvokeHelper();
        private HisIrisServices hIS = new HisIrisServices();
        private MIIrisServices mIS = new MIIrisServices();
        HisMainBusiness hBus = new HisMainBusiness();

        public MedInsuQuery()
        {
            InitializeComponent();

            asc.controllInitializeSize(this);
            asc.controlAutoSize(this);
        }

        public MedInsuQuery( int iPage)
        {
            InitializeComponent();

            asc.controllInitializeSize(this);
            asc.controlAutoSize(this);

            tbcMain.SelectedIndex = iPage;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {            
            this.Close();
        }

        private void MedInsuQuery_Load(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Maximized;

            tbcMain.SelectedIndex = 1;

            dpST.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dpED.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            dt_ST.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_ET.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            date_st.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            date_et.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");

            dtp_st.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dtp_et.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            dpt_ST.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dpt_ET.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            DT_ST1.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            DT_ET1.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            dptST.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dptET.Text = DateTime.Now.ToString("yyyy-MM-31 23:59:59");

            dtTHSJ.Text = DateTime.Now.ToString();

            // dgvSettlRecord.AutoGenerateColumns = false;
            cbbLevel.SelectedIndex = 0;
            cbbOverPrice.SelectedIndex = 0;

            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfMedInsuHosPerInfo(dgvSettlRecord);
            grdSetter.SetHeaderTextOfSettltMentFeelDetailInfo(dgvInsuFeeUpload);
            grdSetter.DatagridviewColumnWidthAdaptation(dgvInsuFeeUpload);
            grdSetter.SetHeaderTextOfMIPatCurrentInsuInfo(dgv_4001);

            grdSetter.SetHeaderTextOfSettlList(dgvSettleData);
            grdSetter.SetHeaderTextOfSettltMentFeelDetailInfo(dgvFeeInfo);
            
            grdSetter.SetHeaderTextOfHISRegister(dgv_HISRegInfo);
            grdSetter.SetHeaderTextOfHISPrescFee(dgv_PrescriptionInfo);
            grdSetter.SetHeaderTextOfBillInfo(dgv_BillInfo);
            grdSetter.SetHeaderTextOfBillDetailInfo(dgv_BillDetailInfo);

            grdSetter.SetHeaderTextOf5205DrugDetailInfo(dgv5205);

            grdSetter.DatagridviewColumnWidthAdaptation(dgv_HISRegInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_PrescriptionInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_BillInfo);
            grdSetter.DatagridviewColumnWidthAdaptation(dgv_BillDetailInfo);

            grdSetter.DatagridviewColumnWidthAdaptation(dgv5205);

            rbg_Type.SelectedIndex = 0;
            tbJGBM.Text = Global.inf.hospitalNO;
            dtTHSJ.Text= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            btnPrint.Enabled = false;
            string sCZYXM = Global.user.name;

            string SqlHeard = " Adm_Dr,MdtrtID,Name as PatientName,Age,PsnCertNO,Gend,PsnType,EmpName,AdmInDepName,insuplcAdmdvs,sZYZT AS sZTSM, "
                            + " AdmBed,RegDate,MainDiagName,AttendDoctorNO,ChiefPhyDocName,'"+ sCZYXM+ "' as OpertName,'' as InHospNo,''Address ";                           

            string SqlStrMain = " SELECT a.*,b.*,a.PatientName AS Name,a.PsnType AS PsnTypeCode,'在院' sZYZT FROM BS_MIPatCurrentInsuInfo a LEFT JOIN BS_MedInsuRegisterInfo b "
                              + " ON a.MdtrtID=b.InsuRegID AND a.Interface_Dr=b.Interface_Dr AND a.Hospital_Dr=b.Hospital_Dr "
                              + " WHERE b.Type=1 AND b.ValidFlag=1 AND b.Hospital_Dr= " + Global.inf.hospitalDr + " AND b.Interface_Dr= " + Global.inf.interfaceDr
                              + " AND b.InsuRegID NOT IN (SELECT MdtrtID FROM BS_MedInsuSettlement WHERE MdtrtID=b.InsuRegID AND BillType=1 AND ValidFlag=1 AND AdmType=2) "
                              + " AND b.RegDate<='" + dpED.Text + "' AND b.RegDate>'" + dpST.Text + "' "  //
                              + " UNION ALL "
                              + " SELECT a.*,b.*,a.PatientName AS Name,a.PsnType AS PsnTypeCode,'已结算' AS sZYZT "
                              + " FROM BS_MIPatCurrentInsuInfo a LEFT JOIN BS_MedInsuRegisterInfo b "
                              + " ON a.MdtrtID=b.InsuRegID AND a.Interface_Dr=b.Interface_Dr AND a.Hospital_Dr=b.Hospital_Dr "
                              + " LEFT JOIN BS_MedInsuSettlement c ON a.MdtrtID=b.InsuRegID AND b.InsuRegID=c.MdtrtID AND a.Interface_Dr=b.Interface_Dr AND b.Interface_Dr=c.Interface_Dr "
                              + " WHERE b.Type=1 AND b.ValidFlag=1 AND c.BillType=1 AND b.Hospital_Dr= " + Global.inf.hospitalDr + " AND b.Interface_Dr= " + Global.inf.interfaceDr                    
                              + " AND c.AdmType=2 AND c.SettlementDateTime<='" + dpED.Text + "' AND c.SettlementDateTime>'" + dpST.Text + "' ";  //

            string sqlStr = " SELECT "+ SqlHeard + " FROM ("+ SqlStrMain +") M ";

            //MessageBox.Show(sqlStr);

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            joSqlstr.Add("Type", "MedInsuHosPInfo");
            joSqlstr.Add("hospID", Global.inf.hisHospitalDr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010059");

            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询结算信息");

            //MessageBox.Show(joRtn.ToString());

            if (joRtn["result"]["data"].ToString() == "[]")
            {
                MessageBox.Show("查询结果为空！");
                return;
            }

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

            if (dt.Rows.Count != 0)
            {
                btnPrint.Enabled = true;
                dtExport = dt;

                //从HIS获取患者的床号（分床前医保登记的病人床号没有写入医保平台登记表）
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string BedNo, BedDocName, InHospNo, Address;
                    JObject joTmp = new JObject();
                    joTmp.Add("admID", dt.Rows[i]["Adm_Dr"].ToString());               
                    JObject joRtn2 = invoker.invokeHISService(JsonHelper.setIrisInpar("05110014", joTmp).ToString(), "获取患者就诊信息");
                    if (JsonHelper.parseIrisRtnValue(joRtn2, out string errMsg) == 0)
                    {
                        BedNo = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.adm_bed");
                        BedDocName = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.chfpdr_name");
                        InHospNo = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.medrcdno");
                        Address = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.Address");
                        dt.Rows[i]["AdmBed"] = BedNo;
                        dt.Rows[i]["AttendDoctorNO"] = BedDocName;
                        dt.Rows[i]["InHospNo"] = InHospNo;
                        dt.Rows[i]["Address"] = Address;
                    }  
                    else
                    {
                        if (errMsg.IndexOf("请重新登录") > 0)                        
                        {
                            MessageBox.Show("获取患者信息失败，请重新登录系统！");
                            break;
                        }
                    }
                }
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            string LSH = DateTime.Now.ToString("yyyy-MM-dd"); //DateTime.Now.ToString("MMddHHmmssffff");
            string sFliePathName = @"C:\Users\Administrator\Desktop\" + LSH + "医保在院患者登记或结算信息.xls";  
            string ReturnFileName = ExportToExcel.DataTabletoExcel(dtExport, sFliePathName);
            if (ReturnFileName != "")
            {
                MessageBox.Show("导出成功,文件保存路径：【" + ReturnFileName + "】");
                System.Diagnostics.Process.Start(ReturnFileName); //打开excel文件                
            }
            else
            {
                MessageBox.Show("导出失败!");
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string sqlStr;
            sqlStr = " SELECT a.Adm_Dr,c.Name, b.HISCode, b.MedInsuNO, b.Price,b.Sumamt,b.ChargeItemLevel,c.ChargeItemLevelName,b.SelfPayProp, ";
            sqlStr = sqlStr + " b.UpLimitAmount,b.OverLimitAmount,b.InScopeAmount,b.FullOwnPayAmount,b.PreSelfPayAmount,b.LimitUsedFlag ";
            sqlStr = sqlStr + " FROM BS_MedInsuSettlement a LEFT JOIN BS_MedInsuFeeUploadRecord b ";
            sqlStr = sqlStr + " ON a.Hospital_Dr=b.Hospital_Dr AND a.MdtrtID=b.MdtrtID AND a.PersonnelNO=b.PersonnelNO ";
            sqlStr = sqlStr + " LEFT JOIN HB_MedInsuDirectory c ON b.MedInsuNO=c.Code AND a.Interface_Dr=c.Interface_Dr AND a.Hospital_Dr=c.Hospital_Dr ";
            sqlStr = sqlStr + " WHERE b.MedInsuNO<>'' and a.ValidFlag=1 AND a.BillType=1 AND a.AdmType=2 ";
            sqlStr = sqlStr + " AND a.Interface_Dr=" + Global.inf.interfaceDr;
            sqlStr = sqlStr + " AND a.Hospital_Dr= " + Global.inf.hospitalDr;
            sqlStr = sqlStr + " AND a.OccurTime>'" + dt_ST.Text + "'";
            sqlStr = sqlStr + " AND a.OccurTime<'" + dt_ET.Text + "'";

            if (tb_InHospNo.Text != "")
            {
                sqlStr = sqlStr + " and a.BillID='" + tb_InHospNo.Text + "'";
            }
            if (tb_SettleID.Text != "")
            {
                sqlStr = sqlStr + " and a.SettlementID='" + tb_SettleID.Text + "'";
            }

            if (cbbOverPrice.Text == "是")
            {
                sqlStr = sqlStr + " AND b.OverLimitAmount>0 ";
            }
            else if (cbbOverPrice.Text == "否")
            {
                sqlStr = sqlStr + " AND b.OverLimitAmount<=0 ";
            }

            if (cbbLevel.Text == "甲类")
            {
                sqlStr = sqlStr + " AND b.ChargeItemLevel='01' ";
            }
            else if (cbbLevel.Text == "乙类")
            {
                sqlStr = sqlStr + " AND b.ChargeItemLevel='02' ";
            }
            else if (cbbLevel.Text == "丙类")
            {
                sqlStr = sqlStr + " AND b.ChargeItemLevel='03' ";
            }

            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", "09010118");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询医保结算费用信息");

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

        private void uiButton3_Click(object sender, EventArgs e)
        {
            //string sqlStr = " SELECT * FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            //sqlStr = sqlStr + " and OccurTime>'" + DT_ST1.Text + "'";
            //sqlStr = sqlStr + " and OccurTime<'" + DT_ET1.Text + "'";
            //sqlStr = sqlStr + " and Interface_Dr=" + Global.inf.interfaceDr + "";
            //sqlStr = sqlStr + " and CertificateNO= " + tb_CertNo.Text;
            //sqlStr = sqlStr + " and BillType=1 and ValidFlag=1 ";

            string sqlstr = " SELECT distinct a.InsuranceAreaCode, b.PersonalNO,b.PsnCertType,b.PsnCertNO,b.PatientName , ";
            sqlstr = sqlstr + " b.Gend,b.Naty,b.Brdy,b.Age,b.Balc,b.Insutype,b.PsnType,b.PsnInsuStas,b.PsnInsuDate, ";
            sqlstr = sqlstr + " b.PausInsuDate,b.Cvlservflag,b.insuplcAdmdvs,b.EmpName ";
            sqlstr = sqlstr + " FROM BS_MedInsuSettlement a ";
            sqlstr = sqlstr + " RIGHT JOIN BS_MIPatCurrentInsuInfo b ";
            sqlstr = sqlstr + " ON a.PersonnelNO=b.PersonalNO AND a.Interface_Dr=b.Interface_Dr ";
            sqlstr = sqlstr + " AND a.PersonType=b.PsnType AND a.InsuranceType=b.Insutype ";
            sqlstr = sqlstr + " WHERE a.ValidFlag=1 AND a.BillType=1 ";
            sqlstr = sqlstr + " and a.OccurTime>'" + DT_ST1.Text + "'";
            sqlstr = sqlstr + " and a.OccurTime<'" + DT_ET1.Text + "'";
            sqlstr = sqlstr + " and a.Interface_Dr='" + Global.inf.interfaceDr + "'";

            if (tb_CertNo.Text!="")
                sqlstr = sqlstr + " and a.CertificateNO='" + tb_CertNo.Text + "'";

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlstr);
            joSqlstr.Add("Type", "4001");
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010059");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询结算信息");

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

        private void uiButton4_Click(object sender, EventArgs e)
        {
            string errorMsg = "";
            if (dgv_4001.CurrentRow == null)
            {
                MessageBox.Show("请查询患者参保信息");
                return;
            }

            int iCenter = dgv_4001.CurrentRow.Index;
            string psn_no = dgv_4001.Rows[iCenter].Cells["PersonalNO"].Value.ToString();
            string psn_cert_type = dgv_4001.Rows[iCenter].Cells["PsnCertType"].Value.ToString();
            string certno = dgv_4001.Rows[iCenter].Cells["PsnCertNO"].Value.ToString();
            string psn_name = dgv_4001.Rows[iCenter].Cells["PatientName"].Value.ToString();
            string gend = dgv_4001.Rows[iCenter].Cells["Gend"].Value.ToString();
            string naty = dgv_4001.Rows[iCenter].Cells["Naty"].Value.ToString();
            string brdy = dgv_4001.Rows[iCenter].Cells["Brdy"].Value.ToString();
            string age = dgv_4001.Rows[iCenter].Cells["Age"].Value.ToString();
            string balc = dgv_4001.Rows[iCenter].Cells["Balc"].Value.ToString();
            string insutype = dgv_4001.Rows[iCenter].Cells["Insutype"].Value.ToString();
            string psn_type = dgv_4001.Rows[iCenter].Cells["PsnType"].Value.ToString();
            string psn_insu_stas = dgv_4001.Rows[iCenter].Cells["PsnInsuStas"].Value.ToString();
            string psn_insu_date = dgv_4001.Rows[iCenter].Cells["PsnInsuDate"].Value.ToString();
            string paus_insu_date = dgv_4001.Rows[iCenter].Cells["PausInsuDate"].Value.ToString();
            string cvlserv_flag = dgv_4001.Rows[iCenter].Cells["Cvlservflag"].Value.ToString();
            string insuplc_admdvs = dgv_4001.Rows[iCenter].Cells["insuplcAdmdvs"].Value.ToString();
            string emp_name = dgv_4001.Rows[iCenter].Cells["EmpName"].Value.ToString();

            JObject joInput = new JObject();
            JObject joData = new JObject();
            joData.Add("psn_no", psn_no);
            joData.Add("psn_cert_type", psn_cert_type);
            joData.Add("certno", certno);
            joData.Add("psn_name", psn_name);
            joData.Add("gend", gend);
            joData.Add("naty", naty); 
            joData.Add("brdy", brdy);
            joData.Add("age", age);
            joData.Add("balc", balc);
            joData.Add("insutype", insutype);
            joData.Add("psn_type", psn_type);
            joData.Add("psn_insu_stas", psn_insu_stas);
            joData.Add("psn_insu_date", psn_insu_date);
            joData.Add("paus_insu_date", paus_insu_date);
            joData.Add("cvlserv_flag", cvlserv_flag);
            joData.Add("insuplc_admdvs", insuplc_admdvs);
            joData.Add("emp_name", emp_name);

            joInput.Add("data", joData);

            JObject joRtn = invoker.invokeCenterServiceF("4001", JsonHelper.setCenterInparF("4001", joInput));
            if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
            {
                MessageBox.Show("患者信息上传失败：" + errorMsg);
                return;
            }

            MessageBox.Show("患者信息上传成功");

        }

        private void uiButton7_Click(object sender, EventArgs e)
        {
            string sqlStr = " SELECT * FROM BS_MedInsuSettlement WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            sqlStr = sqlStr + " and OccurTime>'" + dpt_ST.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpt_ET.Text + "'";
            sqlStr = sqlStr + " and Interface_Dr=" + Global.inf.interfaceDr + "";
            sqlStr = sqlStr + " and BillType=1 and ValidFlag=1 and ReversalFlag<>1";

            if ((rbg_Type.SelectedIndex == 0) || (rbg_Type.SelectedIndex == 3))
                sqlStr = sqlStr + "and AdmType=1";
            else if ((rbg_Type.SelectedIndex == 1) || (rbg_Type.SelectedIndex == 2))
                sqlStr = sqlStr + "and AdmType=2";

            if (tb_CertNo2.Text != "")
                sqlStr = sqlStr + " and CertificateNO= " + tb_CertNo2.Text;

            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", "09010059");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询结算信息");

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

        private void dgvSettleData_DoubleClick(object sender, EventArgs e)
        {
            uiButton5_Click(sender, e);
        }

        /// <summary>
        /// 上传费用明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton5_Click(object sender, EventArgs e)
        {
            string outParam = "成功", funNO = "";

            if (rbg_Type.SelectedIndex == 0)
                funNO = "4303";
            else if (rbg_Type.SelectedIndex == 1)
                funNO = "4403";
            else if (rbg_Type.SelectedIndex == 2)
                funNO = "4801";
            else if (rbg_Type.SelectedIndex == 3)
                funNO = "4802";

            if (dgvSettleData.CurrentRow == null)
            {
                MessageBox.Show("请先查询患者结算信息");
                return;
            }

            int iCenter = dgvSettleData.CurrentRow.Index;            
            Global.pat.mdtrtID = dgvSettleData.Rows[iCenter].Cells["MdtrtID"].Value.ToString();
            Global.pat.medType = dgvSettleData.Rows[iCenter].Cells["MedicalType"].Value.ToString();
            Global.pat.psn_no = dgvSettleData.Rows[iCenter].Cells["PersonnelNO"].Value.ToString();
            Global.pat.adm_Dr = int.Parse(dgvSettleData.Rows[iCenter].Cells["AdmID"].Value.ToString());
            Global.pat.billID = dgvSettleData.Rows[iCenter].Cells["BillID"].Value.ToString();
            Global.pat.recordID = dgvSettleData.Rows[iCenter].Cells["RecordID"].Value.ToString();
            Global.pat.certNO = dgvSettleData.Rows[iCenter].Cells["CertificateNO"].Value.ToString();
            Global.pat.name= dgvSettleData.Rows[iCenter].Cells["PatientName"].Value.ToString();

            Global.pat.brdy = dgvSettleData.Rows[iCenter].Cells["BirthDay"].Value.ToString();
            Global.pat.gend = dgvSettleData.Rows[iCenter].Cells["Gender"].Value.ToString();

            //获取IS费用
            if (hIS.getHisFee(Global.pat, out outParam) != 0)
            {
                MessageBox.Show("获取HIS费用信息失败：" + outParam);
                return;
            }

            //调用医保平台转换HIS费用（转换医保编码等）
            JObject joHisFee = JObject.Parse(outParam);
            if (mIS.convertHisFeeWithInsuCodeHF(joHisFee, out outParam) != 0)
            {
                MessageBox.Show("调用医保平台转换HIS费用（转换医保编码等）失败：" + outParam);
                return;
            }

            JArray jaFeeDetail = JArray.Parse(JsonHelper.getDestValue(JObject.Parse(outParam), "data"));
            //按指定条数分割后上传
            if (uploadFeeToCenter(funNO, 300, jaFeeDetail, out outParam) != 0)
            {
                MessageBox.Show("按指定条数分割后上传失败：" + outParam);
                return;
            }
            else
            {
                MessageBox.Show("上传成功！" + outParam);
                return;
            }

        }

        public int uploadFeeToCenter(string funNO, int singleCount, JArray jaFeeDetail, out string outParam)
        {
            outParam = "";
            string errMsg, type = "feedetail";
            try
            {
                if (rbg_Type.SelectedIndex == 0)
                    type = "outfeedetail";
                else if (rbg_Type.SelectedIndex == 1)
                    type = "feedetail";
                else if (rbg_Type.SelectedIndex == 2)
                    type = "feedetail";
                else if (rbg_Type.SelectedIndex == 3)
                    type = "outfeedetail";

                JArray jaTmp = new JArray();
                for (int i = 0; i < jaFeeDetail.Count; i++)
                {
                    jaFeeDetail[i]["chrg_bchno"] = Global.pat.adm_Dr.ToString();
                    jaFeeDetail[i]["med_type"] = Global.pat.medType;
                    jaFeeDetail[i]["bilg_dept_codg"] = "A10";
                    jaFeeDetail[i]["certno"] = Global.pat.certNO;
                    jaFeeDetail[i]["psn_name"] = Global.pat.name;

                    jaFeeDetail[i]["gend"] = Global.pat.gend;
                    jaFeeDetail[i]["brdy"] = Global.pat.brdy;

                    jaFeeDetail[i]["mdtrt_sn"] = Global.pat.adm_Dr;

                    if (jaFeeDetail[i]["validFlag"].ToString() == "N") continue;
                    jaTmp.Add(jaFeeDetail[i]);
                    if (((i + 1) % singleCount == 0) || ((i + 1) == jaFeeDetail.Count))
                    {
                        JObject joFeeDetail = new JObject();
                        joFeeDetail.Add(type, jaTmp);
                        JObject joRtn = invoker.invokeCenterServiceF(funNO, JsonHelper.setCenterInparF(funNO, joFeeDetail));
                        //if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
                        //{
                        //    outParam = errMsg;
                        //    return -1;
                        //}

                        jaTmp = new JArray();
                    }

                }

                return 0;
            }
            catch (Exception ex)
            {
                outParam = "uploadFee 异常：" + ex.Message;
                return -1;
            }
        }

        private void uiButton16_Click(object sender, EventArgs e)
        {
            string errorMsg;

            try
            {
                if (dgv_HISRegInfo.DataSource == null)
                    return;

                if (dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["ID"].Value.ToString() == "")
                    return;

                presNo = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["prescNo"].Value.ToString();

                JObject joTmp = new JObject();
                joTmp.Add("startDate", dtp_st.Text);
                joTmp.Add("endDate", dtp_et.Text);
                joTmp.Add("hospCode", JsonHelper.getDestValue((JObject)Global.curEvt.jaSession[0], "hospCode"));
                joTmp.Add("prescNo", presNo); //处方号

                JObject joRtn = invoker.invokeHISService(JsonHelper.setIrisInpar("05110038", joTmp).ToString(), "获取门诊处方风险提示参数");
                if (JsonHelper.parseIrisRtnValue(joRtn, out errorMsg) != 0)
                {
                    MessageBox.Show("获取门诊处方风险提示参数失败，请联系管理员！" + errorMsg);
                    return;
                }
                else
                {
                    if ((joRtn["result"].ToString() == "[]") || (joRtn["result"].ToString() == ""))
                    {
                        MessageBox.Show("调用HIS接口服务05110038获取处方号【"+ presNo + "】门诊处方风险提示参数结果为空！");
                        return;
                    }

                    //调用接口上传至中心
                    JObject joInput = new JObject();
                    joInput = JObject.Parse(joRtn["result"][0].ToString());
                    //joInput["treatmentRecord"]["patientinfo"]["psn_no"] = Global.pat.mdtrtID;
                    joInput["treatmentRecord"]["patientinfo"]["brdy"] = joInput["treatmentRecord"]["patientinfo"]["brdy"] + " 00:00:00";

                    JObject joRtn10001 = invoker.invokeCenterServiceF("10001", JsonHelper.setCenterInparF("10001", joInput));
                    if (JsonHelper.parseCenterRtnValue(joRtn10001, out errorMsg) != 0)
                    {
                        MessageBox.Show("门诊处方风险提示上传失败：" + errorMsg);
                        return;
                    }

                    MessageBox.Show("门诊处方风险提示上传成功");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("异常：" + ex.Message);
                return;
            }
        }

        /// <summary>
        /// 新华网人员类别与医保人员类别对照关系
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string GetPsnType(string param)        
        {
            if ((param == "11") || (param == "11021") || (param == "11031") ||
                (param == "1101") || (param == "1102") || (param == "1103") ||
                (param == "1111") || (param == "1113") || (param == "116006") ||
                (param == "116011") || (param == "116012") || (param == "116013") ||
                (param == "116014") || (param == "116015") || (param == "116017") ||
                (param == "136046") || (param == "136048") || (param == "136050") ||
                (param == "116018") || (param == "116019") || (param == "116020") ||
                (param == "116021") || (param == "136042") || (param == "136044") ||
                (param == "5005") || (param == "5007") || (param == "5010") ||
                (param == "5011") || (param == "5015") || (param == "5019") ||
                (param == "5022") || (param == "5028") || (param == "5029") ||
                (param == "5032") || (param == "5035") || (param == "5038") ||
                (param == "5041") || (param == "5044") || (param == "5048") ||
                (param == "5050") || (param == "1117") || (param == "1118") ||
                (param == "116041") || (param == "116042") || (param == "116043") ||
                (param == "116044") || (param == "116045") || (param == "116046") ||
                (param == "11032") || (param == "11033") || (param == "11034") ||
                (param == "116047") || (param == "116048") || (param == "116022") ||
                (param == "116031") || (param == "116032") || (param == "116033") ||
                (param == "5053") || (param == "5054") || (param == "5055") ||
                (param == "5059") || (param == "116090") || (param == "116050") ||
                (param == "116051") || (param == "995330"))
                return "1025100"; //在职
            else if ((param == "1105") || (param == "3601") || (param == "3602"))
                return "1025200"; //农民工
            else if ((param == "12") || (param == "1112") || (param == "1201") ||
                (param == "1202") || (param == "1114") || (param == "1203") ||
                (param == "12031") || (param == "136047") || (param == "1205") ||
                (param == "995311") || (param == "136049") || (param == "126001") ||
                (param == "136051") || (param == "126002") || (param == "136052") ||
                (param == "126003") || (param == "126004") || (param == "126009") ||
                (param == "995319") || (param == "126010") || (param == "995307") ||
                (param == "126013") || (param == "126015") || (param == "126016") ||
                (param == "126017") || (param == "126018") || (param == "126019") ||
                (param == "126022") || (param == "136055") || (param == "126023") ||
                (param == "126024") || (param == "126025") || (param == "126026") ||
                (param == "126027") || (param == "136035") || (param == "136039") ||
                (param == "136040") || (param == "136041") || (param == "136043") ||
                (param == "136045") || (param == "126031") || (param == "126032") ||
                (param == "126033") || (param == "5006") || (param == "5008") ||
                (param == "5012") || (param == "5013") || (param == "5016") ||
                (param == "5017") || (param == "5020") || (param == "5023") ||
                (param == "5030") || (param == "5033") || (param == "5036") ||
                (param == "5039") || (param == "5042") || (param == "5045") ||
                (param == "5049") || (param == "5051") || (param == "120701") ||
                (param == "120703") || (param == "120707") || (param == "120708") ||
                (param == "120711") || (param == "120712") || (param == "120715") ||
                (param == "120716") || (param == "120719") || (param == "120720") ||
                (param == "120723") || (param == "120724") || (param == "120727") ||
                (param == "120728") || (param == "120731") || (param == "120733") ||
                (param == "120735") || (param == "120737") || (param == "126041") ||
                (param == "126042") || (param == "126043") || (param == "126044") ||
                (param == "126045") || (param == "126046") || (param == "12032") ||
                (param == "12033") || (param == "12034") || (param == "12035") ||
                (param == "126047") || (param == "126048") || (param == "116088") ||
                (param == "126064") || (param == "126065") || (param == "126117") ||
                (param == "126216") || (param == "126037") || (param == "126067") ||
                (param == "126066") || (param == "126034") || (param == "5056") ||
                (param == "5057") || (param == "5058") || (param == "126316") ||
                (param == "126317") || (param == "5060") || (param == "126090") ||
                (param == "995331"))
                return "1025300"; //退休人员
            else
            if ((param == "13") || (param == "1300") || (param == "1300") ||
                (param == "995309") || (param == "136053") || (param == "136001") ||
                (param == "136002") || (param == "136004") || (param == "136005") ||
                (param == "136006") || (param == "136007") || (param == "136008") ||
                (param == "136009") || (param == "136010") || (param == "136011") ||
                (param == "136012") || (param == "136014") || (param == "136015") ||

                (param == "136016") || (param == "136017") || (param == "136018") ||
                (param == "136019") || (param == "136020") || (param == "136021") ||
                (param == "136022") || (param == "136023") || (param == "136024") ||
                (param == "136090") || (param == "13031") || (param == "136026") ||
                (param == "136029") || (param == "136030") || (param == "136031") ||
                (param == "5001") || (param == "5002") || (param == "5003") ||
                (param == "5004") || (param == "5009") || (param == "5018") ||
                (param == "5021") || (param == "5024") || (param == "5031") ||
                (param == "5034") || (param == "5037") || (param == "5040") ||
                (param == "5043") || (param == "5046") || (param == "5047") ||
                (param == "5052") || (param == "137001") || (param == "137002") ||
                (param == "137003") || (param == "136054") || (param == "130102") ||
                (param == "5088"))
                return "1025400"; //离休
            else
            if ((param == "14") || (param == "1405") || (param == "156006") || (param == "156007"))
                return "1025500"; //居民（未成年）
            else
            if ((param == "1401") || (param == "140101"))
                return "1025600"; //新生儿
            else
            if ((param == "1402"))
                return "1025700"; //学龄前儿童
            else
            if (param == "1403")
                return "1025800"; //中小学生
            else
            if ((param == "1404") || (param == "140890") || (param == "140891") ||
                (param == "156008") || (param == "140401") || (param == "140402") ||
                (param == "140403"))
                return "1025900"; //大学生
            else
            if ((param == "995301") || (param == "1405"))
                return "1025110"; //未成年（未入学）
            else
            if (param == "15")
                return "1025111"; //居民（成年）
            else
            if (param == "1501")
                return "1025112"; //普通居民（成年）
            else
            if ((param == "16") || (param == "160104") || (param == "140805") ||
                (param == "160100") || (param == "160101") || (param == "160102") ||
                (param == "160103"))            
                return "1025113"; //居民（老年）          
            else
                return "1025111"; //居民（成年）
        }

        /// <summary>
        /// 根据HIS就诊ID查询患者参保信息
        /// </summary>
        /// <param name="admID"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public int GetInsuPersonInfo(string admID, out JObject joRtn, out string errorMsg)
        {
            joRtn = null;
            string sqlstr = " SELECT TOP 1 * FROM BS_MIPatCurrentInsuInfo WHERE AdmID='" + admID + "'";
            sqlstr = sqlstr + " and Interface_Dr='" + Global.inf.interfaceDr + "' ORDER BY ID DESC";
            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlstr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joQuery = new JObject();
            joQuery.Add("params", jaParam);
            joQuery.Add("code", "09010082");
            JObject joQueryRtn = invoker.invokeInsuService(joQuery.ToString(), "查询人员参保信息");
            if (JsonHelper.parseIrisRtnValue(joQueryRtn, out errorMsg) != 0)
            {
                MessageBox.Show("查询人员参保信息失败，请联系管理员！" + errorMsg);
                return -1;
            }

            joRtn = joQueryRtn;
            return 0;
        }

        public string GetInsuFeeInfo(string admID, string InsuCode)        
        {
            string sqlStr;
            sqlStr = " SELECT admID as Adm_Dr,'' as Name,''as HISCode,MedInsuNO,Price,Sumamt, ";
            sqlStr = sqlStr + " ChargeItemLevel,SelfPayProp,UpLimitAmount,OverLimitAmount,InScopeAmount,";
            sqlStr = sqlStr + " FullOwnPayAmount,PreSelfPayAmount,LimitUsedFlag From BS_MedInsuFeeUploadRecord ";
            sqlStr = sqlStr + " WHERE Hospital_Dr= " + Global.inf.hospitalDr;
            sqlStr = sqlStr + " AND admID='" + admID + "'";
            sqlStr = sqlStr + " AND MedInsuNO='" + InsuCode + "'";

            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", "09010118");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询医保结算费用信息");

            decimal SelfPayProp = decimal.Parse(JsonHelper.getDestValue(joRtn, "result.data[0].SelfPayProp"));

            //1007100-医保个人，1007200-医保统筹，1007300-现金
            if (SelfPayProp == 0)            
                return "1007200"; 
            else 
                return "1007300";
        }

        private void uiButton13_Click(object sender, EventArgs e)
        {
            string errorMsg;
            string participateType = "1024200", personnelType;

            if ((dgv_BillInfo.DataSource == null) || (dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["billCode"].Value.ToString() == ""))
            {
                MessageBox.Show("请先查询单据信息!");
                return;
            }

            if ((dgv_BillDetailInfo.DataSource == null) || (dgv_BillDetailInfo.Rows[dgv_BillDetailInfo.CurrentRow.Index].Cells["billID"].Value.ToString() == ""))
            {
                MessageBox.Show("请先查询明细信息!");
                return;
            }

            try
            {
                string entId = dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["entId"].Value.ToString();
                string billCode = dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["billCode"].Value.ToString();
                string billTime = dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["billTime"].Value.ToString();
                string InsuredType = dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["participateType"].Value.ToString(); //险种类型
                string admID = dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["admID"].Value.ToString(); 

                if (InsuredType.Substring(0, 2) == "31")
                {
                    participateType = "1024100"; //职工
                }
                else if (InsuredType.Substring(0, 2) == "39")
                {
                    participateType = "1024200"; //居民
                }

                //人员类别   
                if (GetInsuPersonInfo(admID, out JObject joQueryRtn, out errorMsg) != 0)
                {
                    MessageBox.Show("查询参保人员信息失败！" + errorMsg);
                    return;
                }

                personnelType = GetPsnType(JsonHelper.getDestValue(joQueryRtn, "result.rows[0].psnType").ToString());

                JObject joData = JObject.Parse(JsonHelper.getDestValue(joInput20002, "result[0]").ToString());
                joData["participateType"] = participateType;
                joData["personnelType"] = personnelType;

                JArray jaFeeDetail = JArray.Parse(JsonHelper.getDestValue(joInput20002, "result[0].detail"));                
    
                //for (int i = 0; i < jaFeeDetail.Count; i++)
                //{
                //    string InsuCode = jaFeeDetail[i]["medicalDrugId"].ToString();                    
                //    if (InsuCode != "未对照")
                //    {
                //        string toPay = GetInsuFeeInfo(admID, InsuCode);
                //    }                    
                //}

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

                JObject joRtn = invoker.invokeCenterServiceF("20002", JsonHelper.setCenterInparF("20002", joInput));
                if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
                {
                    MessageBox.Show("事后单据鉴核信息提报失败，中心返回：" + errorMsg);
                    return;
                }

                MessageBox.Show("事后单据鉴核信息提报成功！" + errorMsg);
            }
            catch (Exception ex)
            {
                MessageBox.Show("事后单据鉴核信息提报异常：" + ex.Message);
                return;
            }
        }

        private void dgv_BillInfo_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void uiButton19_Click(object sender, EventArgs e)
        {
            string errorMsg = "";
            if (dgv_4001.CurrentRow == null)
            {
                MessageBox.Show("请查询患者参保信息");
                return;
            }
       
            for (int i = 0; i < dgv_4001.Rows.Count; i++)
            {
                //int iCenter = dgv_4001.CurrentRow.Index;
                string psn_no = dgv_4001.Rows[i].Cells["PersonalNO"].Value.ToString();
                string psn_cert_type = dgv_4001.Rows[i].Cells["PsnCertType"].Value.ToString();
                string certno = dgv_4001.Rows[i].Cells["PsnCertNO"].Value.ToString();
                string psn_name = dgv_4001.Rows[i].Cells["PatientName"].Value.ToString();
                string gend = dgv_4001.Rows[i].Cells["Gend"].Value.ToString();
                string naty = dgv_4001.Rows[i].Cells["Naty"].Value.ToString();
                string brdy = dgv_4001.Rows[i].Cells["Brdy"].Value.ToString();
                string age = dgv_4001.Rows[i].Cells["Age"].Value.ToString();
                string balc = dgv_4001.Rows[i].Cells["Balc"].Value.ToString();
                string insutype = dgv_4001.Rows[i].Cells["Insutype"].Value.ToString();
                string psn_type = dgv_4001.Rows[i].Cells["PsnType"].Value.ToString();
                string psn_insu_stas = dgv_4001.Rows[i].Cells["PsnInsuStas"].Value.ToString();
                string psn_insu_date = dgv_4001.Rows[i].Cells["PsnInsuDate"].Value.ToString();
                string paus_insu_date = dgv_4001.Rows[i].Cells["PausInsuDate"].Value.ToString();
                string cvlserv_flag = dgv_4001.Rows[i].Cells["Cvlservflag"].Value.ToString();
                string insuplc_admdvs = dgv_4001.Rows[i].Cells["insuplcAdmdvs"].Value.ToString();
                string emp_name = dgv_4001.Rows[i].Cells["EmpName"].Value.ToString();

                JObject joInput = new JObject();
                JObject joData = new JObject();
                joData.Add("psn_no", psn_no);
                joData.Add("psn_cert_type", psn_cert_type);
                joData.Add("certno", certno);
                joData.Add("psn_name", psn_name);
                joData.Add("gend", gend);
                joData.Add("naty", naty);
                joData.Add("brdy", brdy);
                joData.Add("age", age);
                joData.Add("balc", balc);
                joData.Add("insutype", insutype);
                joData.Add("psn_type", psn_type);
                joData.Add("psn_insu_stas", psn_insu_stas);
                joData.Add("psn_insu_date", psn_insu_date);
                joData.Add("paus_insu_date", paus_insu_date);
                joData.Add("cvlserv_flag", cvlserv_flag);
                joData.Add("insuplc_admdvs", insuplc_admdvs);
                joData.Add("emp_name", emp_name);

                joInput.Add("data", joData);

                JObject joRtn = invoker.invokeCenterServiceF("4001", JsonHelper.setCenterInparF("4001", joInput));
                if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
                {
                    MessageBox.Show("患者信息上传失败：" + errorMsg);
                    return;
                }


            }

            MessageBox.Show("患者信息上传成功");
        }

        private void dgvSettleData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSettleData.CurrentRow == null)
            {
                MessageBox.Show("请先查询医保结算信息");
                return;
            }

            int iCenter = dgvSettleData.CurrentRow.Index;
            string PersonnelNO = dgvSettleData.Rows[iCenter].Cells["PersonnelNO"].Value.ToString();  //MdtrtID
            string SettlementID = dgvSettleData.Rows[iCenter].Cells["SettlementID"].Value.ToString();
            string MdtrtID = dgvSettleData.Rows[iCenter].Cells["MdtrtID"].Value.ToString();

            string sqlStr;
            sqlStr = " SELECT a.Adm_Dr,c.Name, b.HISCode, b.MedInsuNO, b.Price,b.Sumamt,b.ChargeItemLevel,c.ChargeItemLevelName,b.SelfPayProp, ";
            sqlStr = sqlStr + " b.UpLimitAmount,b.OverLimitAmount,b.InScopeAmount,b.FullOwnPayAmount,b.PreSelfPayAmount,b.LimitUsedFlag ";
            sqlStr = sqlStr + " FROM BS_MedInsuSettlement a LEFT JOIN BS_MedInsuFeeUploadRecord b ";
            sqlStr = sqlStr + " ON a.Hospital_Dr=b.Hospital_Dr AND a.MdtrtID=b.MdtrtID AND a.PersonnelNO=b.PersonnelNO ";
            sqlStr = sqlStr + " LEFT JOIN HB_MedInsuDirectory c ON b.MedInsuNO=c.Code AND a.Interface_Dr=c.Interface_Dr AND a.Hospital_Dr=c.Hospital_Dr ";
            sqlStr = sqlStr + " WHERE b.MedInsuNO<>'' and a.ValidFlag=1 AND a.BillType=1  "; //AND a.AdmType=2
            sqlStr = sqlStr + " AND a.Interface_Dr=" + Global.inf.interfaceDr;
            sqlStr = sqlStr + " AND a.Hospital_Dr= " + Global.inf.hospitalDr;
            sqlStr = sqlStr + " AND a.OccurTime>'" + dpt_ST.Text + "'";
            sqlStr = sqlStr + " AND a.OccurTime<'" + dpt_ET.Text + "'";
            sqlStr = sqlStr + " AND a.PersonnelNO='" + PersonnelNO + "'";
            sqlStr = sqlStr + " AND a.SettlementID='" + SettlementID + "'";
            sqlStr = sqlStr + " AND a.MdtrtID='" + MdtrtID + "'";

            if (tb_CertNo2.Text != "")
                sqlStr = sqlStr + " And a.CertificateNO='" + tb_CertNo2.Text + "' ";

            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", "09010118");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询医保结算费用信息");

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

        private void uiButton20_Click(object sender, EventArgs e)
        {
            string outParam = "成功", funNO = "";

            if (rbg_Type.SelectedIndex == 0)
                funNO = "4303";
            else if (rbg_Type.SelectedIndex == 1)
                funNO = "4403";
            else if (rbg_Type.SelectedIndex == 2)
                funNO = "4801";
            else if (rbg_Type.SelectedIndex == 3)
                funNO = "4802";

            if (dgvSettleData.CurrentRow == null)
            {
                MessageBox.Show("请先查询患者结算信息");
                return;
            }

            for (int i = 0; i < dgvSettleData.Rows.Count; i++)
            {
                int iCenter = dgvSettleData.CurrentRow.Index;
                Global.pat.mdtrtID = dgvSettleData.Rows[i].Cells["MdtrtID"].Value.ToString();
                Global.pat.medType = dgvSettleData.Rows[i].Cells["MedicalType"].Value.ToString();
                Global.pat.psn_no = dgvSettleData.Rows[i].Cells["PersonnelNO"].Value.ToString();
                Global.pat.adm_Dr = int.Parse(dgvSettleData.Rows[i].Cells["AdmID"].Value.ToString());
                Global.pat.billID = dgvSettleData.Rows[i].Cells["BillID"].Value.ToString();
                Global.pat.recordID = dgvSettleData.Rows[i].Cells["RecordID"].Value.ToString();

                Global.pat.certNO = dgvSettleData.Rows[i].Cells["CertificateNO"].Value.ToString();
                Global.pat.name = dgvSettleData.Rows[i].Cells["PatientName"].Value.ToString();

                Global.pat.brdy = dgvSettleData.Rows[i].Cells["BirthDay"].Value.ToString();
                Global.pat.gend = dgvSettleData.Rows[i].Cells["Gender"].Value.ToString();

                //获取IS费用
                if (hIS.getHisFee(Global.pat, out outParam) != 0)
                {
                    MessageBox.Show("获取HIS费用信息失败：" + outParam);
                    return;
                }

                //调用医保平台转换HIS费用（转换医保编码等）
                JObject joHisFee = JObject.Parse(outParam);
                if (mIS.convertHisFeeWithInsuCodeHF(joHisFee, out outParam) != 0)
                {
                    MessageBox.Show("调用医保平台转换HIS费用（转换医保编码等）失败：" + outParam);
                    return;
                }

                JArray jaFeeDetail = JArray.Parse(JsonHelper.getDestValue(JObject.Parse(outParam), "data"));
                //按指定条数分割后上传
                if (uploadFeeToCenter(funNO, 300, jaFeeDetail, out outParam) != 0)
                {
                    //MessageBox.Show("按指定条数分割后上传失败：" + outParam);
                    //return;
                }
                else
                    continue;
            }

            MessageBox.Show("上传成功！" + outParam);

        }

        private void rbg_Type_ValueChanged(object sender, int index, string text)
        {
            dgvSettleData.DataSource = null;
            dgvFeeInfo.DataSource = null;
        }

        private void uiButton21_Click(object sender, EventArgs e)
        {
            string errorMsg;

            if (dgv_HISRegInfo.DataSource == null)
                return;

            if (dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["ID"].Value.ToString() == "")
                return;

            for (int i = 0; i < dgv_HISRegInfo.Rows.Count; i++)
            {
                presNo = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["prescNo"].Value.ToString();

                JObject joTmp = new JObject();
                joTmp.Add("startDate", dtp_st.Text);
                joTmp.Add("endDate", dtp_et.Text);
                joTmp.Add("hospCode", JsonHelper.getDestValue((JObject)Global.curEvt.jaSession[0], "hospCode"));
                joTmp.Add("prescNo", presNo); //处方号

                JObject joRtn = invoker.invokeHISService(JsonHelper.setIrisInpar("05110038", joTmp).ToString(), "获取门诊处方风险提示参数");
                if (JsonHelper.parseIrisRtnValue(joRtn, out errorMsg) != 0)
                {
                    MessageBox.Show("获取门诊处方风险提示参数失败，请联系管理员！" + errorMsg);
                    return;
                }
                else
                {
                    if ((joRtn["result"].ToString() == "[]") || (joRtn["result"].ToString() == ""))
                    {
                        MessageBox.Show("调用HIS接口服务05110038获取处方号【" + presNo + "】门诊处方风险提示参数结果为空！！");
                        return;
                    }

                    //调用接口上传至中心
                    JObject joInput = new JObject();
                    joInput = JObject.Parse(joRtn["result"][0].ToString());
                    //joInput["treatmentRecord"]["patientinfo"]["psn_no"] = Global.pat.mdtrtID;
                    joInput["treatmentRecord"]["patientinfo"]["brdy"] = joInput["treatmentRecord"]["patientinfo"]["brdy"] + " 00:00:00";

                    JObject joRtn10001 = invoker.invokeCenterServiceF("10001", JsonHelper.setCenterInparF("10001", joInput));
                    if (JsonHelper.parseCenterRtnValue(joRtn10001, out errorMsg) != 0)
                    {
                        MessageBox.Show("门诊处方风险提示上传失败：" + errorMsg);
                        return;
                    }             
                }
            }

            MessageBox.Show("门诊处方风险提示上传成功");
        }

        private void dgv_HISRegInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv_HISRegInfo.DataSource == null)
                return;

            if (dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["ID"].Value.ToString() == "")
                return;

            string outParam = "";
            DataTable dt = null;
            presAdmDoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["doc"].Value.ToString();
            presAdmLoc = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["loc"].Value.ToString();
            presNo = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["prescNo"].Value.ToString();
            presAdmID = dgv_HISRegInfo.Rows[dgv_HISRegInfo.CurrentRow.Index].Cells["admID"].Value.ToString();
            Global.pat.adm_Dr = int.Parse(presAdmID);

            if (presNo == "") return;

            //获取HIS处方明细信息
            if (GetHISPrescFeeInfo(presNo, ref outParam, ref dt) != 0)
            {
                MessageBox.Show(outParam);
                return;
            }

            dgv_PrescriptionInfo.DataSource = dt;
        }

        private void dgv_BillInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string outParam = "";
            DataTable dt = null;
            string errMsg;

            if (dgv_BillInfo.DataSource == null)
                return;

            if (dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["billCode"].Value.ToString() == "")
                return;

            string billID = dgv_BillInfo.Rows[dgv_BillInfo.CurrentRow.Index].Cells["billCode"].Value.ToString();

            try
            {
                JObject joTmp = new JObject();
                joTmp.Add("startDate", date_st.Text.Substring(0, 10));
                joTmp.Add("endDate", date_et.Text.Substring(0, 10));
                joTmp.Add("hospCode", JsonHelper.getDestValue((JObject)Global.curEvt.jaSession[0], "hospCode"));
                joTmp.Add("billID", billID);

                JObject joRtn = invoker.invokeHISService(JsonHelper.setIrisInpar("05110039", joTmp).ToString(), "组织事后单据鉴核信息填报参数");
                if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                {
                    MessageBox.Show("组织事后单据鉴核信息填报参数失败，请联系管理员！" + errMsg);
                    return;
                }
                else
                {
                    joInput20002 = joRtn;
                    JObject detail = new JObject();
                    string result = JsonHelper.getDestValue(joRtn, "result[0]").ToString();
                    detail = JObject.Parse(result);
                    dt = (DataTable)detail["detail"].ToObject(typeof(DataTable));
                    dgv_BillDetailInfo.DataSource = dt;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("组织事后单据鉴核信息填报参数异常：" + ex.Message);
                return;
            }
        }

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

                //展示患者信息界面
                if (hBus.showPatInfo(patInfo, out outParam) != 0)
                {
                    MessageBox.Show("参保信息展示异常！" + outParam);
                    return;
                }
                else
                {
                    if (hBus.setGlobalPatAfaterShowPatInfo(outParam, out errMsg) != 0)
                    {
                        MessageBox.Show("setGlobalPatAfaterShowPatInfo全局变量赋值异常！" + errMsg);
                        return;
                    }                    
                }
            }
        }

        private void btn5205_Click(object sender, EventArgs e)
        {
            string outParam = "", errMsg = "";

            if (string.IsNullOrEmpty(Global.pat.psn_no))
            {
                MessageBox.Show("未获取到该患者的医保个人编号，请重新读卡！");
                return;
            }

            JObject joInput = new JObject();
            JObject joData = new JObject();
            joData.Add("psn_no", Global.pat.psn_no);
            joData.Add("begntime", dptST.Text);
            joData.Add("endtime", dptET.Text);
            joInput.Add("data", joData);

            JObject joRtn = invoker.invokeCenterService("5205", JsonHelper.setCenterInparF("5205", joInput));
            if (JsonHelper.parseCenterRtnValue(joRtn, out errMsg) != 0)
            {
                MessageBox.Show("人员慢特病用药记录查询失败：" + errMsg);
                return;
            }
            else
            {
                dgv5205.DataSource = (DataTable)joRtn["output"]["feedetail"].ToObject(typeof(DataTable));
            }
        }

        public int queryHISDirectory(out string errMsg)        
        {
            errMsg = "";
            string pageSize = "500";
            string flag = "Maped";
            JObject joHISRtn = new JObject();
            JObject joRtn = new JObject();
            JArray jaPagination = new JArray();
            JArray jaParams = new JArray();
            dynamic joParam = new JObject();
            joParam.alias = "";
            joParam.HospitalDr = Global.inf.hospitalDr;
            joParam.InterfaceDr = Global.inf.interfaceDr;
            joParam.hisType = "drugs";
            jaParams.Add(joParam);
            dynamic joPagination = new JObject();
            joPagination.pageSize = pageSize;
            joPagination.currentPage = "1";
            joPagination.sortColumn = "HisCode";
            joPagination.sortOrder = "asc";
            jaPagination.Add(joPagination);

            JObject joMIRtn = mIS.GetMappedHISDir(jaPagination, jaParams);

            if (JsonHelper.parseIrisRtnValue(joMIRtn, out errMsg) != 0)
            {
                return -1;
            }

            //传给HIS，进行匹配
            joParam = new JObject();
            joParam.TotalCount = joMIRtn["result"]["TotalCount"];
            joParam.type = "drugs";
            joParam.flag = flag;
            joParam.hospID = Global.inf.hisHospitalDr;
            joParam.interfaceDr = Global.inf.interfaceDr;
            joParam.alias = "";
            joParam.include = "Hosp";
            joParam.groupID = "324";
            joParam.specInput = "";//增加规格过滤
            joParam.compareArr = joMIRtn["result"]["Data"];
            jaParams = new JArray();
            jaParams.Add(joParam);
            if (hIS.getHISDir(jaPagination, jaParams, out joRtn, out errMsg) != 0)
            {
                return -1;
            }

            DataTable dt = (DataTable)joRtn["result"]["Data"].ToObject(typeof(DataTable));
            dtExport = dt;
            int totalCount = int.Parse(joRtn["result"]["TotalCount"].ToString());
            //pgHISDirect.TotalCount = totalCount;

            //pgHISDirect.PageSize = pageSize;
            dgvMedInsuMapRelation.DataSource = null;
            dgvMedInsuMapRelation.DataSource = dt;
            dgvMedInsuMapRelation.Columns[0].ReadOnly = true;

            GridViewSetter gridSetter = new GridViewSetter();
            gridSetter.SetHeaderTextOfMapping_HisDirectory(dgvMedInsuMapRelation);
            gridSetter.DatagridviewColumnWidthAdaptation(dgvMedInsuMapRelation);

            return 0;
        }

        private void uiButton9_Click(object sender, EventArgs e)
        {            
            if (queryHISDirectory(out string errMsg) != 0)            
            {
                MessageBox.Show(errMsg);
                return;
            }
        }

        private void uiButton10_Click(object sender, EventArgs e)
        {
            string errorMsg;
            if (dgvMedInsuMapRelation.CurrentRow == null)
            {
                MessageBox.Show("请先查询医保药品对照信息");
                return;
            }

            int iCenter = dgvMedInsuMapRelation.CurrentRow.Index;
            string insuCode = dgvMedInsuMapRelation.Rows[iCenter].Cells["insuCode"].Value.ToString();  //中心编码
            string insuName = dgvMedInsuMapRelation.Rows[iCenter].Cells["insuName"].Value.ToString();  //中心编码
            string itemCode = dgvMedInsuMapRelation.Rows[iCenter].Cells["itemCode"].Value.ToString();  //医院编码
            string itemDesc = dgvMedInsuMapRelation.Rows[iCenter].Cells["itemDesc"].Value.ToString();  //医院名称

            SaleBillInfo sbi = new SaleBillInfo(insuCode, insuName);
            try
            {
                if (sbi.ShowDialog() == DialogResult.OK)
                {            
                    JObject joInput = new JObject();
                    JObject joData = new JObject();
                    joData.Add("entId", sbi.entId);
                    joData.Add("code", sbi.code);
                    joData.Add("medicalDrugId", sbi.medicalDrugId);
                    joData.Add("queryTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    joData.Add("salePkg", sbi.salePkg);
                    joData.Add("unpackCount", sbi.unpackCount);
                    joData.Add("drugSalePrice", sbi.drugSalePrice);
                    joData.Add("batchNo", sbi.batchNo);

                    joInput.Add("data", joData);

                    JObject joRtn = invoker.invokeCenterServiceF("20001", JsonHelper.setCenterInparFT("20001", joInput));
                    if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
                    {
                        MessageBox.Show("医保药品鉴核数据采集事前鉴核服务上传失败：" + errorMsg);
                        return;
                    }
                    else
                    {
                        DataTable dtData = (DataTable)joRtn["output"]["data"].ToObject(typeof(DataTable));
                        DataTable dtVerifyResult = (DataTable)joRtn["output"]["verifyResult"].ToObject(typeof(DataTable));
                        DataTable dtTraceCodeVo = (DataTable)joRtn["output"]["traceCodeVo"].ToObject(typeof(DataTable));
                        DataTable dtMedDrugInfo = (DataTable)joRtn["output"]["medDrugInfo"].ToObject(typeof(DataTable));

                        dgvData.DataSource = dtData;
                        dgvVerifyResult.DataSource = dtVerifyResult;
                        dgvTraceCodeVo.DataSource = dtTraceCodeVo;
                        dgvMedDrugInfo.DataSource = dtMedDrugInfo;

                        MessageBox.Show("医保药品鉴核数据采集事前鉴核服务上传成功");
                    }                    
                }
                else
                {
                    MessageBox.Show("操作员已取消！");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常：" + ex.Message);
                return;
            }
        }

        private void uiButton11_Click(object sender, EventArgs e)
        {
            string errorMsg;
            JObject joInput = new JObject();
            JObject joData = new JObject();
            joData.Add("ent_id", tbJGBM.Text);
            joData.Add("bill_code", tbDJBH.Text);            
            joData.Add("bill_time", dtTHSJ.Text);

            joInput.Add("data", joData);

            JObject joRtn = invoker.invokeCenterServiceF("20003", JsonHelper.setCenterInparF("20003", joInput));
            if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
            {
                MessageBox.Show("医保销售单据退货上传失败：" + errorMsg);
                return;
            }
            else
            {
                MessageBox.Show("医保销售单据退货上传成功！" + errorMsg);
            }
        }

        private void uiButton15_Click(object sender, EventArgs e)
        {
            string errMsg;
            dgv_BillInfo.DataSource = null;
            dgv_BillDetailInfo.DataSource = null;

            try
            {
                JObject joTmp = new JObject();
                joTmp.Add("startDate",date_st.Text.Substring(0,10));
                joTmp.Add("endDate", date_et.Text.Substring(0, 10));
                joTmp.Add("hospCode", JsonHelper.getDestValue((JObject)Global.curEvt.jaSession[0], "hospCode"));
                joTmp.Add("billID", "");

                JObject joRtn = invoker.invokeHISService(JsonHelper.setIrisInpar("05110039", joTmp).ToString(), "组织事后单据鉴核信息填报参数");
                if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                {
                    MessageBox.Show("组织事后单据鉴核信息填报参数失败，请联系管理员！" + errMsg);
                    return;
                }
                else
                {
                    DataTable dt = (DataTable)joRtn["result"].ToObject(typeof(DataTable));
                    dgv_BillInfo.DataSource = dt;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("组织事后单据鉴核信息填报参数异常：" + ex.Message);
                return;
            }
        }

        /// <summary>
        /// 获取HIS就诊信息
        /// </summary>
        /// <param name="dtST"></param>
        /// <param name="dtED"></param>
        /// <param name="PatInfo"></param>
        /// <param name="errMsg"></param>
        /// <param name="DT"></param>
        /// <returns></returns>
        private int GetHISRegInfo(string dtST, string dtED, string PatInfo, ref string errMsg, ref DataTable DT)
        {
            dynamic joTmp = new JObject();
            joTmp.Add("stDate", dtST);
            joTmp.Add("endDate", dtED);
            joTmp.Add("patInfo", PatInfo);

            JObject joRtnHISRegInfo = hIS.GetHISRegInfo(joTmp);

            if (JsonHelper.parseIrisRtnValue(joRtnHISRegInfo, out errMsg) != 0)
            {
                errMsg = "获取HIS患者就诊信息失败，请联系管理员！" + errMsg;
                return -1;
            }
            else
            {
                if ((joRtnHISRegInfo["result"]["rows"].ToString() == "[]"))
                {
                    errMsg = "查询HIS就诊信息结果为空！";
                    return -1;
                }
                else
                {
                    DT = (DataTable)joRtnHISRegInfo["result"]["rows"].ToObject(typeof(DataTable));
                    return 0;
                }
            }
        }

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

            //if (tb_SFZH.Text == "")
            //{
            //    MessageBox.Show("请先输入患者身份证号进行查找患者未结算处方信息！");
            //    return;
            //}
            //else
            //{
            //    dgv_HISRegInfo.DataSource = null;
            //    dgv_PrescriptionInfo.DataSource = null;

            //    CertNo = tb_SFZH.Text;
            //    Global.pat.certNO = tb_SFZH.Text;
            //}

            dgv_HISRegInfo.DataSource = null;
            dgv_PrescriptionInfo.DataSource = null;

            CertNo = tb_SFZH.Text;
            Global.pat.certNO = tb_SFZH.Text;

            #region【查询HIS就诊信息-用身份证号查询患者当日的就诊记录】
            string outParam = "";
            DataTable dt1 = null;
            if (GetHISRegInfo(dtp_st.Text, dtp_et.Text, Global.pat.certNO, ref outParam, ref dt1) != 0)
            {
                MessageBox.Show(outParam);
                return;
            }

            dgv_HISRegInfo.DataSource = dt1;
            #endregion

            #region【根据处方号查询处方明细信息】
            presAdmDoc = dgv_HISRegInfo.Rows[0].Cells["doc"].Value.ToString();
            presAdmLoc = dgv_HISRegInfo.Rows[0].Cells["loc"].Value.ToString();
            presNo = dgv_HISRegInfo.Rows[0].Cells["prescNo"].Value.ToString();
            presAdmID = dgv_HISRegInfo.Rows[0].Cells["admID"].Value.ToString();
            Global.pat.adm_Dr = int.Parse(presAdmID);

            if (presNo == "") return;
            DataTable dt2 = null;
            //获取HIS处方明细信息
            if (GetHISPrescFeeInfo(presNo, ref outParam, ref dt2) != 0)
            {
                MessageBox.Show(outParam);
                return;
            }

            dgv_PrescriptionInfo.DataSource = dt2;
            #endregion
        }

        /// <summary>
        /// 获取HIS费用明细信息
        /// </summary>
        /// <param name="PrescNo"></param>
        /// <param name="errMsg"></param>
        /// <param name="DT"></param>
        /// <returns></returns>
        private int GetHISPrescFeeInfo(string PrescNo, ref string errMsg, ref DataTable DT)
        {
            dynamic joTmp = new JObject();
            joTmp.Add("prescNo", PrescNo);

            JObject joRtnHISPrescFeeInfo = hIS.GetHISPrescFeeInfo(joTmp);

            if (JsonHelper.parseIrisRtnValue(joRtnHISPrescFeeInfo, out errMsg) != 0)
            {
                errMsg = "获取HIS患者处方信息失败，请联系管理员！" + errMsg;
                return -1;
            }
            else
            {
                if ((joRtnHISPrescFeeInfo["result"]["rows"].ToString() == "[]"))
                {
                    errMsg = "查询HIS处方信息结果为空！";
                    return -1;
                }
                else
                {
                    DT = (DataTable)joRtnHISPrescFeeInfo["result"]["rows"].ToObject(typeof(DataTable));
                    return 0;
                }
            }
        }

        private void dgv_HISRegInfo_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            uiButton16_Click(sender, e);
        }
    }
}