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 PTMedicalInsurance.Helper;
using PTMedicalInsurance.Common;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.FormSetter;
using PTMedicalInsurance.Variables;
using FastReport;
using Newtonsoft.Json;
using System.Threading;
using PTMedicalInsurance.Business;
using System.Reflection;
using System.Runtime.InteropServices;
using FastReportFrom;
using System.IO;

namespace PTMedicalInsurance.Forms
{

    public partial class SettlementChecklist : Form
    {
        private int hospitalDr;
        private int interfaceDr;
        private string hospitalNO;
        private string interfaceNO;
        private string hospitalName;
        private string hospitalAreaCode;

        private bool disposed = false;

        Thread thread_test;

        private InvokeHelper invoker = new InvokeHelper();
        public SettlementChecklist()
        {
            InitializeComponent();
            hospitalDr = Global.inf.hospitalDr;
            hospitalNO = Global.inf.hospitalNO;
            hospitalName = Global.inf.hospitalName;
            hospitalAreaCode = Global.inf.areaCode;
            interfaceDr = Global.inf.interfaceDr;
        }
        public SettlementChecklist(JObject joParam)
        {
            InitializeComponent();
            hospitalDr = Global.inf.hospitalDr;
            hospitalNO = Global.inf.hospitalNO;
            hospitalName = Global.inf.hospitalName;
            hospitalAreaCode = Global.inf.areaCode;

            if (joParam == null) return;

            string setl_id = JsonHelper.getDestValue(joParam, "setl_id");
            if (setl_id == "")
            {
                MessageBox.Show("根据传入的结算编号为查询到相关信息，请手动输入查询！");
                return;
            }
            string sqlStr = "SELECT * FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            sqlStr = sqlStr + " and SettlementID='" + setl_id + "'";
            JObject joSqlStr = new JObject();
            joSqlStr.Add("sqlStr", sqlStr);
            MIIrisServices mIS = new MIIrisServices();
            JObject joRtn = mIS.QuerySettlementInfo(joSqlStr);
            DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
            dgvSettlRecord.DataSource = dt;
        }


        public void Dispose()
        {
        
            Dispose1(true);
            GC.SuppressFinalize(this);
    
        }

        protected virtual void Dispose1(bool disposing)
        {
       
            if (thread_test == null) return;
            if (disposed == false)
            {
                if (disposing == true)
                {
                    Thread.Sleep(100);
                    Global.writeLog("Main - aborting my thread.");
                    thread_test.Abort();//终止线程myThread
                    thread_test.Join();//等待线程myThread结束
                    Global.writeLog("Main - ending.");
                }
                //释放托管资源的代码
            }
            disposed = true;
        
        }

        private void rbgDirecType_ValueChanged(object sender, int index, string text)
        {

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {

        }

        private void btnQuery_Click_1(object sender, EventArgs e)
        {
            string sqlStr = " SELECT * FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + hospitalDr;
            sqlStr = sqlStr + " and OccurTime>'" + dpST.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED.Text + "'";
            if (tbName.Text != "")
            {
                sqlStr = sqlStr + " and PatientName='" + tbName.Text + "'";
            }

            if (tbPatSettlID.Text != "")
            {
                sqlStr = sqlStr + " and SettlementID='" + tbPatSettlID.Text + "'";
            }

            if (tbHisNO.Text != "")
            {
                sqlStr = sqlStr + " and Adm_Dr='" + tbHisNO.Text + "'";
            }

            if (cbxInterface.Text != "")
            {
                sqlStr = sqlStr + " and Interface_Dr=" + Global.inf.interfaceDr + "";
            }

            if (rbgAdmType.SelectedIndex == 1)
            {
                sqlStr = sqlStr + " and AdmType=2";
            }
            if (rbgAdmType.SelectedIndex == 2)
            {
                sqlStr = sqlStr + " and AdmType=1";
            }

            if (rbgBillType.SelectedIndex == 1)
            {
                sqlStr = sqlStr + " and BillType=1 and ValidFlag=1 ";
            }

            if (rbgBillType.SelectedIndex == 2)
            {
                sqlStr = sqlStr + " and BillType=-1 and ValidFlag=0 ";
            }

            JObject joSqlStr = new JObject();
            joSqlStr.Add("sqlStr", sqlStr);
            MIIrisServices mIS = new MIIrisServices();
            JObject joRtn = mIS.QuerySettlementInfo(joSqlStr);

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



        private void SettlementChecklist_Load(object sender, EventArgs e)
        {
            dpST.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dpED.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            ComboxSetter cbxSetter = new ComboxSetter();
            cbxSetter.setCbxInterfaceDataSource(cbxInterface);

            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfSettlList(dgvSettlRecord);

            rbgAdmType.SelectedIndex = 0;
            rbgBillType.SelectedIndex = 1;

            cbxInterface.SelectedValueChanged += new EventHandler(cbxInterface_SelectedValueChanged);
        }

        private void cbxInterface_SelectedValueChanged(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)cbxInterface.DataSource;
            int i = cbxInterface.SelectedIndex;

            //赋值
            hospitalNO = dt.Rows[i]["HospitalNO"].ToString();
            //MessageBox.Show(dt.Rows[i]["HospitalDr"].ToString());
            //MessageBox.Show(dt.Rows[i]["HospitalDr"].ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            hospitalDr = int.Parse(dt.Rows[i]["HospitalDr"].ToString());
            interfaceNO = dt.Rows[i]["InterfaceNO"].ToString();
            interfaceDr = int.Parse(dt.Rows[i]["ID"].ToString());
            hospitalAreaCode = dt.Rows[i]["AreaCode"].ToString();
            //Global.inf.centerURL = dt.Rows[i]["CenterURL"].ToString();
            //Global.inf.businessDllName = dt.Rows[i]["DLLName"].ToString();
            //Global.inf.patientAreaCode = dt.Rows[i]["AreaCode"].ToString();
        }
        private JObject getPatCheckList()
        {
            try
            {
                int i = dgvSettlRecord.CurrentRow.Index;
                DataTable dt = (DataTable)dgvSettlRecord.DataSource;
                JObject joSettel = new JObject();
                joSettel.Add("HospitalDr", Global.inf.hospitalDr);
                joSettel.Add("interfaceDr", Global.inf.interfaceDr);
                joSettel.Add("admID", dt.Rows[i]["AdmID"].ToString());
                joSettel.Add("SettlementID", dt.Rows[i]["SettlementID"].ToString());
                joSettel.Add("ValidFlag", dt.Rows[i]["ValidFlag"].ToString());

                JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("09010066", joSettel).ToString(), "获取结算单信息");
                return joRtn;
            }
            catch (Exception ex)
            {
                JObject joRtn = new JObject();
                joRtn.Add("errorCode", -1);
                joRtn.Add("errorMessage", ex.Message);
                return joRtn;
            }
        }

        private void uiPanel1_Click(object sender, EventArgs e)
        {

        }
        [STAThread]
        public void design()
        {
       
            try
            {
                string chineseSimpleFrl = Global.curEvt.path + @"\Chinese (Simplified).frl";
              //  FastReport.Utils.Res.LoadLocale(chineseSimpleFrl);
               // FastReport.Utils.RegisteredObjects.AddFunctionCategory("FastReport.FastReportFunction.moneyToChinese", "moneyToChinese");
                //获取要注册的方法信息
               MethodInfo methodInfo = typeof(FastReport.FastReportFunction).GetMethod("moneyToChinese");

                // 注册函数目录为 FastReport MyFunction目录下 
              //  FastReport.Utils.RegisteredObjects.AddFunction(methodInfo, "MyFunction");

                JObject joSettleCheckList = getPatCheckList();
                string errMsg;
                if (JsonHelper.parseIrisRtnValue(joSettleCheckList, out errMsg) != 0)
                {
                    MessageBox.Show("查询结算信息异常：" + errMsg);
                    return;
                }
                Report report = new Report();
                try
                {
                    
                    var json = JsonConvert.DeserializeObject<Root>(getPatCheckList().ToString());
                    report.RegisterData(json.result.data.classification, "classification");
                    report.RegisterData(json.result.data.settlement, "settlement");
                    report.RegisterData(json.result.data.reginfo, "reginfo"); 
                    report.RegisterData(json.result.data.patinsuinfo, "patinsuinfo");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                report.Load(Global.curEvt.path + "\\frx\\合肥瑶海普瑞医院.frx");
                PrintDesign pf = new PrintDesign();
                pf.designerControl1.Report = report;

                report.Design();
                pf.WindowState = FormWindowState.Maximized;
                pf.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
      
        }
        [STAThread]
        private void print()
        {
            
            /*
             string chineseSimpleFrl = Global.curEvt.path + @"\Chinese (Simplified).frl";
            // FastReport.Utils.Res.LoadLocale(chineseSimpleFrl);

             JObject joSettleCheckList = getPatCheckList();
             string errMsg;
             if (JsonHelper.parseIrisRtnValue(joSettleCheckList, out errMsg) != 0)
             {
                 MessageBox.Show("查询结算信息异常：" + errMsg);
                 return;
             }
             Report report = new Report();
             try
             {
                 var json = JsonConvert.DeserializeObject<Root>(getPatCheckList().ToString());
                 report.RegisterData(json.result.data.classification, "classification");
                 report.RegisterData(json.result.data.settlement, "settlement");
                 report.RegisterData(json.result.data.reginfo, "reginfo");
                 report.RegisterData(json.result.data.patinsuinfo, "patinsuinfo");
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
                 return;
             }
             //report.Design();
             report.Load(Global.curEvt.path + "\\frx\\合肥瑶海普瑞医院.frx");
             this.ShowInTaskbar = true;
             PrintPreview pf = new PrintPreview();
             report.Preview = pf.previewControl1;

             report.Show();
             pf.WindowState = FormWindowState.Maximized;
             pf.ShowDialog();*/

            try
            {
                int i = dgvSettlRecord.CurrentRow.Index;
                DataTable dt = (DataTable)dgvSettlRecord.DataSource;
                string AdmID = dt.Rows[i]["AdmID"].ToString();
                string SettlementID = dt.Rows[i]["SettlementID"].ToString();
                string ValidFlag = dt.Rows[i]["ValidFlag"].ToString();
                string MdtrtID = dt.Rows[i]["MdtrtID"].ToString();
                JObject joRtn = GetFastReportParams("", AdmID, MdtrtID, SettlementID, ValidFlag);
                if (JsonHelper.parseIrisRtnValue(joRtn, out string errMsg) != 0)
                {
                    MessageBox.Show("获取FastReport入参失败：" + errMsg);
                    return;
                }

                string sFastReportParam = JsonHelper.getDestValue(joRtn, "result");
                if (FastReportPrint(sFastReportParam, out errMsg) != 0)
                {
                    MessageBox.Show("调用FastReport打印失败！" + errMsg);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

        }

        [STAThread]
        private void preview()
        {
           
            //JObject joCheckList = getPatCheckList();
            Report report = new Report();
            try
            {
                var json = JsonConvert.DeserializeObject<Root>(getPatCheckList().ToString());
                report.RegisterData(json.result.data.classification, "classification");
                report.RegisterData(json.result.data.settlement, "settlement");
                report.RegisterData(json.result.data.reginfo, "reginfo");
                report.RegisterData(json.result.data.patinsuinfo, "patinsuinfo");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            //report.Design();
            report.Load(Global.curEvt.path + "\\frx\\合肥瑶海普瑞医院.frx");
            //report.Show();
            PrintPreview preview1 = new PrintPreview();
            preview1.Show();
            report.Preview = preview1.previewControl1;

            report.Prepare(); //准备
            report.ShowPrepared(); //显示
            preview1.Show();
        
        }

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

        public void btnPrint_Click(object sender, EventArgs e)
        {

            try
            { 
                //Thread thread_print = new Thread(new ThreadStart(print));
                //thread_print.SetApartmentState(ApartmentState.STA); //重点
                //thread_print.Start();
                //thread_print.Join();
                print();
            }
            catch (Exception ex)
            {
               Global.writeLog("结算单打印异常:" + ex.Message);
               MessageBox.Show("打印异常:" + ex.Message);
            }


            if (dgvSettlRecord.RowCount <= 0)
            {
                MessageBox.Show("请先查询结算数据!");
                return;
            }
            /*
            try
            {
                int i = dgvSettlRecord.CurrentRow.Index;
                DataTable dt = (DataTable)dgvSettlRecord.DataSource;
                string AdmID = dt.Rows[i]["AdmID"].ToString();
                string SettlementID = dt.Rows[i]["SettlementID"].ToString();
                string ValidFlag = dt.Rows[i]["ValidFlag"].ToString();
                string MdtrtID = dt.Rows[i]["MdtrtID"].ToString();

                JObject joRtn = GetFastReportParams("", AdmID, MdtrtID, SettlementID, ValidFlag);
                if (JsonHelper.parseIrisRtnValue(joRtn, out string errMsg) != 0)
                {
                    MessageBox.Show("获取FastReport入参失败：" + errMsg);
                    return;
                }

                string sFastReportParam = JsonHelper.getDestValue(joRtn, "result");
                if (FastReportPrint(sFastReportParam, out errMsg) != 0)
                {
                    MessageBox.Show("调用FastReport打印失败！" + errMsg);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }*/
        }

        public int FastReportPrint(string InParams, out string OutMsg)
        {
            Global.writeLog("调用FastReport入参：" + InParams);
            try
            {
                #region【调用正版FastReport打印】                
                FastReportFrom.FastReportDll FrDll = new FastReportFrom.FastReportDll();
                string sRtnFr = FrDll.FastReport(InParams);

                JObject joRetObj = JObject.Parse(sRtnFr);

                if (JsonHelper.parseIrisRtnValue(joRetObj, out string errMsg) != 0)
                {
                    OutMsg = "调用FastReport打印失败！" + errMsg;
                    return -1;
                }
                else
                {
                    OutMsg = "";
                    return 0;
                }
                #endregion
            }
            catch (Exception ex)
            {
                OutMsg = "调用FastReport打印失败！" + ex.Message;
                return -1;
            }
        }

        public JObject GetFastReportParams(string designFlag, string admID, string MdtrtID, string settlementID, string validFlag)
        {
            try
            {
                if (designFlag == "") { designFlag = "N"; }

                #region【获取HIS医保结算信息】
                JObject joSettel = new JObject();
                joSettel.Add("HospitalDr", Global.inf.hospitalDr);
                joSettel.Add("interfaceDr", Global.inf.interfaceDr);
                joSettel.Add("admID", admID);
                joSettel.Add("SettlementID", settlementID);
                joSettel.Add("ValidFlag", validFlag);
                joSettel.Add("MdtrtID", MdtrtID);

                JObject joRtnSettle = invoker.invokeInsuService(JsonHelper.setIrisInpar("09010066", joSettel).ToString(), "获取结算单信息");


                if (JsonHelper.parseIrisRtnValue(joRtnSettle, out string errMsg) != 0)
                {
                    JObject joRtnSet = new JObject();
                    joRtnSet.Add("errorCode", -1);
                    joRtnSet.Add("errorMessage", errMsg);
                    joRtnSet.Add("result", "");

                    return joRtnSet;
                }
                #endregion
                #region【获取住院号】
                JObject joTmp = new JObject();
                joTmp.Add("admID", joRtnSettle["result"]["data"]["settlement"][0]["AdmID"]);
                joTmp.Add("psn_no", joRtnSettle["result"]["data"]["settlement"][0]["PersonnelNO"]);

                //JObject joRtn = invoker.invokeHISService(JsonHelper.setIrisInpar("05110001", joTmp).ToString(), "获取诊断信息");
                JObject joRtnDiag = invoker.invokeHISService(JsonHelper.setIrisInpar("05110014", joTmp).ToString(), "获取诊断信息");
                string medrcdno = "";
                if (JsonHelper.parseIrisRtnValue(joRtnSettle, out  errMsg) == 0)
                {
                     medrcdno= joRtnDiag["mdtrtinfo"]["medrcdno"].ToString();
                }
                #endregion 
                #region【数据转换】
                if (joRtnSettle["result"]["data"]["settlement"][0]["Gender"].ToString() == "1")
                {
                    joRtnSettle["result"]["data"]["settlement"][0]["Gender"] = "男";
                }
                else
                {
                    joRtnSettle["result"]["data"]["settlement"][0]["Gender"] = "女";
                }
                

                DateTime startDate = (DateTime)joRtnSettle["result"]["data"]["reginfo"][0]["RegDate"];
                DateTime endDate = (DateTime)joRtnSettle["result"]["data"]["settlement"][0]["SettlementTime"];
                int diffInDays = (int)(endDate - startDate).TotalDays;
                if (diffInDays == 0)
                {
                    diffInDays = 1;
                }

                joRtnSettle["result"]["data"]["settlement"][0]["HospitalizationsDays"] = diffInDays;

                string str = joRtnSettle["result"]["data"]["patinsuinfo"][0]["Age"].ToString();
                if (str.Contains("."))
                {
                    joRtnSettle["result"]["data"]["patinsuinfo"][0]["Age"] = str.Split('.')[0] + "岁";
                }
                else
                {
                    joRtnSettle["result"]["data"]["patinsuinfo"][0]["Age"] = str + "岁";
                }

                #endregion 


                #region【组织FastReport调用入参】               
                JArray jachargeItemLvFee = JArray.Parse(JsonHelper.getDestValue(joRtnSettle, "result.data.chargeItemLvFee"));
                JArray jaClassification = JArray.Parse(JsonHelper.getDestValue(joRtnSettle, "result.data.classification"));
                JArray jaSettlement = JArray.Parse(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement"));
                JArray jaReginfo = JArray.Parse(JsonHelper.getDestValue(joRtnSettle, "result.data.reginfo"));
                JArray japatinsuinfo = JArray.Parse(JsonHelper.getDestValue(joRtnSettle, "result.data.patinsuinfo"));

                //转换金额大写
                string Sumamt = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].Sumamt").ToString());
                string HealthInsurancePay = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].HealthInsurancePay").ToString());
                string ActualPayDeductible = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].ActualPayDeductible").ToString());
                string PersonCashPay = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].PersonCashPay").ToString());
                string AccountPaySumamt = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].AccountPaySumamt").ToString());
                string FundPaySumamt = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].FundPaySumamt").ToString());
                string LargeExpensesSupplementPay = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].LargeExpensesSupplementPay").ToString());
                string SeriousIllnessPay = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].SeriousIllnessPay").ToString());
                string CivilserviceAllowancePay = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].CivilserviceAllowancePay").ToString());
                string MedicalAssistPay = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].MedicalAssistPay").ToString());
                string OtherPay = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].OtherPay").ToString());
                string HospitalPartAmount = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].HospitalPartAmount").ToString());
                string AccountMutualAidAmount = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].AccountMutualAidAmount").ToString());
                string InPolicyRangeAmount = FastReportFunction.MoneyToUpper(JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].InPolicyRangeAmount").ToString());
                
                //string BeginDate = JsonHelper.getDestValue(joRtnSettle, "result.data.reginfo[0].RegDate").ToString();
                //string EndDate = JsonHelper.getDestValue(joRtnSettle, "result.data.settlement[0].HISDischargeTime").ToString();
                //string InHosDays = FastReportFunction.DateDiff(Convert.ToDateTime(BeginDate), Convert.ToDateTime(EndDate));  

                JObject jaAmountChiness = new JObject();
                jaAmountChiness.Add("Sumamt", Sumamt);
                jaAmountChiness.Add("HealthInsurancePay", HealthInsurancePay);
                jaAmountChiness.Add("ActualPayDeductible", ActualPayDeductible);
                jaAmountChiness.Add("PersonCashPay", PersonCashPay);
                jaAmountChiness.Add("AccountPaySumamt", AccountPaySumamt);
                jaAmountChiness.Add("FundPaySumamt", FundPaySumamt);
                jaAmountChiness.Add("LargeExpensesSupplementPay", LargeExpensesSupplementPay);
                jaAmountChiness.Add("SeriousIllnessPay", SeriousIllnessPay);
                jaAmountChiness.Add("CivilserviceAllowancePay", CivilserviceAllowancePay);
                jaAmountChiness.Add("MedicalAssistPay", MedicalAssistPay);
                jaAmountChiness.Add("OtherPay", OtherPay);
                jaAmountChiness.Add("HospitalPartAmount", HospitalPartAmount);
                jaAmountChiness.Add("AccountMutualAidAmount", AccountMutualAidAmount);
                jaAmountChiness.Add("InPolicyRangeAmount", InPolicyRangeAmount); //合规费用
                jaAmountChiness.Add("SettlOpter", Global.user.name);
                jaAmountChiness.Add("medrcdno", medrcdno);                

                JArray jachinessParams = new JArray();
                jachinessParams.Add(jaAmountChiness);

                JObject joDataResult = new JObject();
                joDataResult.Add("SettlementInfo", jaSettlement);
                joDataResult.Add("ChargeItemLvFee", jachargeItemLvFee);
                joDataResult.Add("ClassificationInfo", jaClassification);
                joDataResult.Add("RegInfo", jaReginfo);
                joDataResult.Add("Patinsuinfo", japatinsuinfo);
                joDataResult.Add("ChinessSummat", jachinessParams);

                JObject joParams = new JObject();
                joParams.Add("fastReportCode", "SP11"); //这个要从表取值
                joParams.Add("hospID", Global.inf.hisHospitalDr.ToString());
                joParams.Add("printCode", Global.inf.interfaceDr.ToString());
                joParams.Add("templateID", "");

                JArray jaParams = new JArray();
                jaParams.Add(joParams);

                JObject joReportParams = new JObject();
                joReportParams.Add("params", jaParams);
                joReportParams.Add("code", "01040306");

                JObject joParam = new JObject();
                joParam.Add("designFlag", designFlag);
                joParam.Add("logFlag", "N");
                joParam.Add("dataParams", "");
                joParam.Add("pdfName", "");
                joParam.Add("reportparams", joReportParams);
                joParam.Add("dataResult", joDataResult);

                JObject joDataURL = new JObject();
                joDataURL.Add("dataIP", Global.hisConfig.ip);
                joDataURL.Add("urlAddress", Global.hisConfig.url);
                joDataURL.Add("authorization", Global.hisConfig.authorization);

                joParam.Add("dataURL", joDataURL);

                JArray jaParam = new JArray();
                jaParam.Add(joParam);

                JObject joInparam = new JObject();
                joInparam.Add("params", JArray.FromObject(jaParam));
                joInparam.Add("session", Global.curEvt.jaSession);
                #endregion

                JObject joRtn = new JObject();
                joRtn.Add("errorCode", 0);
                joRtn.Add("errorMessage", "");
                joRtn.Add("result", joInparam.ToString());

                return joRtn;
            }
            catch (Exception ex)
            {
                JObject joRtnEx = new JObject();
                joRtnEx.Add("errorCode", -1);
                joRtnEx.Add("errorMessage", ex.Message);
                joRtnEx.Add("result", "");
                return joRtnEx;
            }
        }

        private void btnDesign_Click(object sender, EventArgs e)
        {
            /*
            thread_test = new Thread(new ThreadStart(design));
            thread_test.SetApartmentState(ApartmentState.STA); //重点
            thread_test.Start();*/

            if (dgvSettlRecord.RowCount <= 0)
            {
                MessageBox.Show("请先查询结算数据!");
                return;
            }

            try
            {
                int i = dgvSettlRecord.CurrentRow.Index;
                DataTable dt = (DataTable)dgvSettlRecord.DataSource;

                string AdmID = dt.Rows[i]["AdmID"].ToString();
                string SettlementID = dt.Rows[i]["SettlementID"].ToString();
                string ValidFlag = dt.Rows[i]["ValidFlag"].ToString();
                string MdtrtID = dt.Rows[i]["MdtrtID"].ToString();

                JObject joRtn = GetFastReportParams("Y", AdmID, MdtrtID, SettlementID, ValidFlag);
               
                if (JsonHelper.parseIrisRtnValue(joRtn, out string errMsg) != 0)
                {
                    MessageBox.Show("获取FastReport入参失败：" + errMsg);
                    return;
                }

                string sFastReportParam = JsonHelper.getDestValue(joRtn, "result");
                if (FastReportPrint(sFastReportParam, out errMsg) != 0)
                {
                    MessageBox.Show("调用FastReport设计失败！" + errMsg);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

        }

        private void SettlementChecklist_FormClosed(object sender, FormClosedEventArgs e)
        {
      
            Dispose();
      
        }
    }

    // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    public class Classification
    {
        public string cwfSummat { get; set; }
        public string cwfInScope { get; set; }
        public string cwfPreSelfPay { get; set; }
        public string cwfOverLimit { get; set; }
        public string cwfFullOwnPay { get; set; }
        public string zcfSummat { get; set; }
        public string zcfInScope { get; set; }
        public string zcfPreSelfPay { get; set; }
        public string zcfOverLimit { get; set; }
        public string zcfFullOwnPay { get; set; }
        public string jcfSummat { get; set; }
        public string jcfInScope { get; set; }
        public string jcfPreSelfPay { get; set; }
        public string jcfOverLimit { get; set; }
        public string jcfFullOwnPay { get; set; }
        public string hyfSummat { get; set; }
        public string hyfInScope { get; set; }
        public string hyfPreSelfPay { get; set; }
        public string hyfOverLimit { get; set; }
        public string hyfFullOwnPay { get; set; }
        public string zlfSummat { get; set; }
        public string zlfInScope { get; set; }
        public string zlfPreSelfPay { get; set; }
        public string zlfOverLimit { get; set; }
        public string zlfFullOwnPay { get; set; }
        public string ssfSummat { get; set; }
        public string ssfInScope { get; set; }
        public string ssfPreSelfPay { get; set; }
        public string ssfOverLimit { get; set; }
        public string ssfFullOwnPay { get; set; }
        public string hlfSummat { get; set; }
        public string hlfInScope { get; set; }
        public string hlfPreSelfPay { get; set; }
        public string hlfOverLimit { get; set; }
        public string hlfFullOwnPay { get; set; }
        public string wsclfSummat { get; set; }
        public string wsclfInScope { get; set; }
        public string wsclfPreSelfPay { get; set; }
        public string wsclfOverLimit { get; set; }
        public string wsclfFullOwnPay { get; set; }
        public string xyfSummat { get; set; }
        public string xyfInScope { get; set; }
        public string xyfPreSelfPay { get; set; }
        public string xyfOverLimit { get; set; }
        public string xyfFullOwnPay { get; set; }
        public string zyypfSummat { get; set; }
        public string zyypfInScope { get; set; }
        public string zyypfPreSelfPay { get; set; }
        public string zyypfOverLimit { get; set; }
        public string zyypfFullOwnPay { get; set; }
        public string zcyfSummat { get; set; }
        public string zcyfInScope { get; set; }
        public string zcyfPreSelfPay { get; set; }
        public string zcyfOverLimit { get; set; }
        public string zcyfFullOwnPay { get; set; }
        public string ybzlfSummat { get; set; }
        public string ybzlfInScope { get; set; }
        public string ybzlfPreSelfPay { get; set; }
        public string ybzlfOverLimit { get; set; }
        public string ybzlfFullOwnPay { get; set; }
        public string ghfSummat { get; set; }
        public string ghfInScope { get; set; }
        public string ghfPreSelfPay { get; set; }
        public string ghfOverLimit { get; set; }
        public string ghfFullOwnPay { get; set; }
        public string qtSummat { get; set; }
        public string qtInScope { get; set; }
        public string qtPreSelfPay { get; set; }
        public string qtOverLimit { get; set; }
        public string qtFullOwnPay { get; set; }
        public string totalSummat { get; set; }
        public string totalInScope { get; set; }
        public string totalPreSelfPay { get; set; }
        public string totalOverLimit { get; set; }
        public string totalFullOwnPay { get; set; }
    }

    public class Data
    {
        public List<Classification> classification { get; set; }
        public List<Settlement> settlement { get; set; }
        public List<Reginfo> reginfo { get; set; }
        public List<Patinsuinfo> patinsuinfo { get; set; }
    }

    public class Patinsuinfo
    {
        public string PsnCertType { get; set; }
        public string PsnCertNO { get; set; }
        public string Gend { get; set; }
        public string Naty { get; set; }
        public string Brdy { get; set; }
        public string Age { get; set; }
        public string Balc { get; set; }
        public string PsnType { get; set; }
        public string Cvlservflag { get; set; }
        public string insuplcAdmdvs { get; set; }
        public string EmpName { get; set; }
        public string PsnIdettype { get; set; }
        public string PsnTypeLv { get; set; }
    }

    public class Reginfo
    {
        public string AttendDoctorNO { get; set; }
        public string ChiefPhyDocName { get; set; }
        public string AdmitDepartmentCode { get; set; }
        public string AdmitDepartmentName { get; set; }
        public string AdmBed { get; set; }
        public string MainDiagCode { get; set; }
        public string MainDiagName { get; set; }
        public string RegDate { get; set; }
        public string ConerName { get; set; }
        public string Tel { get; set; }
    }

    public class Result
    {
        public Data data { get; set; }
    }

    public class Root
    {
        public Result result { get; set; }
        public int errorCode { get; set; }
        public string errorMessage { get; set; }
    }

    public class Settlement
    {
        public string AdmID { get; set; }
        public string MdtrtID { get; set; }
        public string SettlementID { get; set; }
        public string PersonnelNO { get; set; }
        public string PatientName { get; set; }
        public string birth { get; set; }
        public string CertificateNO { get; set; }
        public string Gender { get; set; }
        public string InsuranceType { get; set; }
        public string PersonType { get; set; }
        public string CivilserviceFlag { get; set; }
        public string SettlementTime { get; set; }
        public string MedicalType { get; set; }
        public string Sumamt { get; set; }
        public string OwnPayAmount { get; set; }
        public string OverLimitAmount { get; set; }
        public string PreSelfPayAmount { get; set; }
        public string InPolicyRangeAmount { get; set; }
        public double ActualPayDeductible { get; set; }
        public string HealthInsurancePay { get; set; }
        public string HealthInsuranceRatio { get; set; }
        public double CivilserviceAllowancePay { get; set; }
        public string EnterpriseSupplementPay { get; set; }
        public string SeriousIllnessPay { get; set; }
        public string LargeExpensesSupplementPay { get; set; }
        public string MedicalAssistPay { get; set; }
        public string HospitalPartAmount { get; set; }
        public string OtherPay { get; set; }
        public string FundPaySumamt { get; set; }
        public string PersonPaySumamt { get; set; }
        public string AccountPaySumamt { get; set; }
        public string PersonCashPay { get; set; }
        public string Balance { get; set; }
        public string AccountMutualAidAmount { get; set; }
        public string OrganSettlementID { get; set; }
        public string ClearingOrgan { get; set; }
        public string ClearingWay { get; set; }
        public string ClearingType { get; set; }
        public string ValidFlag { get; set; }
        public string msgid { get; set; }
        public string HospitalizationsTimes { get; set; }
        public string HospitalizationsDays { get; set; }
        public string HISAdmTime { get; set; }
        public string HISDischargeTime { get; set; }
        public int BillType { get; set; }
        public string BillID { get; set; }
        public string admType { get; set; }
        public string RecordID { get; set; }
        public string insuplc_admdvs { get; set; }
    }






}
