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

namespace PTMedicalInsurance.Forms
{
    public partial class Clearing : Form
    {
        private string txtPath;
        private string txtName;
        private string finalAchPath;
        private UIDataGridViewFooter dgvHisSettlRecFooter = new Sunny.UI.UIDataGridViewFooter();
        JObject jo9102Rtn = new JObject();

        public Clearing()
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterParent;

        }

        private void Clearing_Load(object sender, EventArgs e)
        {
            ComboxSetter cbxSetter = new ComboxSetter();
            cbxSetter.setCbxInterfaceDataSource(cbxInterface);
            cbxSetter.setCbxInterfaceDataSource(cbInterface_2);
            cbxSetter.setCbxInterfaceDataSource(cbInterface_3);
            cbxSetter.setCbxDictionaryDataSource(Global.inf.interfaceDr_TY.ToString(), "insutype", cbxInsuType);
            cbxSetter.setCbxDictionaryDataSource(Global.inf.interfaceDr_TY.ToString(), "clr_type", cbxClrType);

            cbxSetter.setCbxDictionaryDataSource(Global.inf.interfaceDr_TY.ToString(), "clr_type", cbClrType_2);
            cbxSetter.setCbxDictionaryDataSource(Global.inf.interfaceDr_TY.ToString(), "clr_way", cbClrWay_2);
            cbxSetter.setCbxDictionaryDataSource("1", "clr_type", cbxClrType_O);

            cbxInterface.SelectedValueChanged += new EventHandler(cbxInterface_SelectedValueChanged);
            cbInterface_2.SelectedValueChanged += new EventHandler(cbInterface_2_SelectedValueChanged);
            cbInterface_3.SelectedValueChanged += new EventHandler(cbInterface_3_SelectedValueChanged);
            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfCheck(dgvSettlSummary);            
            grdSetter.SetHeaderTextOfClearing(dgvClearingSum);
            grdSetter.SetHeaderTextOfClearingData(dgvClearingData);
            grdSetter.SetHeaderTextOfOthPlcCheck(dgvOthCheck);

            cbgGroupSet.SelectAll();
            cbgGroupSet.SetItemCheckState(4, false);

            cbxValid.SelectedIndex = 0;
            cbValid_2.SelectedIndex = 1;
            cbValid_3.SelectedIndex = 0;
            rbgTimeWay.SelectedIndex = 0;
            cbOtherPlaceFlag.SelectedIndex = 2;

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

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

            dpED_3.Value = DateTime.Now;
            WindowState = FormWindowState.Maximized;

            tbTmp.Text= Global.currentDirectory + "\\Download";
        }

        private void cbxInterface_SelectedValueChanged(object sender, EventArgs e)
        {
            DataTable dtInteface = (DataTable)cbxInterface.DataSource;
            int i = cbxInterface.SelectedIndex;
            if (i != 2)
            {
                Global.pat.insuplc_admdvs = "";
            }
            else
            {
                Global.pat.insuplc_admdvs = "530199";
            }
            Global.inf.hospitalNO = dtInteface.Rows[i]["HospitalNO"].ToString();
            Global.inf.hospitalName = dtInteface.Rows[i]["HospitalName"].ToString();
            Global.inf.centerURL = dtInteface.Rows[i]["CenterURL"].ToString();
            Global.inf.areaCode = dtInteface.Rows[i]["AreaCode"].ToString();
            Global.user.name = "0";
            Global.user.ID = "0";
            Global.inf.operatoType = "3";
            Global.inf.version = "v1.0";
            Global.inf.recivedSystem = "SY";
            Global.inf.interfaceDr = int.Parse(dtInteface.Rows[i]["ID"].ToString());

            ComboxSetter cbxSetter = new ComboxSetter();
            cbxSetter.setCbxDictionaryDataSource(dtInteface.Rows[i]["ID"].ToString(), "insutype", cbxInsuType);
            cbxSetter.setCbxDictionaryDataSource(dtInteface.Rows[i]["ID"].ToString(), "clr_type", cbxClrType);
        }

        private void cbInterface_2_SelectedValueChanged(object sender, EventArgs e)
        {
            DataTable dtInteface = (DataTable)cbInterface_2.DataSource;
            int i = cbInterface_2.SelectedIndex;
            if (i != 2)
            {
                Global.inf.areaCode = "";
            }
            else
            {
                Global.pat.insuplc_admdvs = "530100";
            }
            Global.inf.hospitalNO = dtInteface.Rows[i]["HospitalNO"].ToString();
            Global.inf.hospitalName = dtInteface.Rows[i]["HospitalName"].ToString();
            Global.inf.centerURL = dtInteface.Rows[i]["CenterURL"].ToString();
            Global.inf.areaCode = dtInteface.Rows[i]["AreaCode"].ToString();
            Global.user.name = "0";
            Global.user.ID = "0";
            Global.inf.operatoType = "3";
            Global.inf.version = "v1.0";
            Global.inf.recivedSystem = "SY";
            Global.inf.interfaceDr = int.Parse(dtInteface.Rows[i]["ID"].ToString());

            ComboxSetter cbxSetter = new ComboxSetter();
            cbxSetter.setCbxDictionaryDataSource(Global.inf.interfaceDr.ToString(), "clr_type", cbClrType_2);
            cbxSetter.setCbxDictionaryDataSource(Global.inf.interfaceDr.ToString(), "clr_way", cbClrWay_2);
        }

        private void cbInterface_3_SelectedValueChanged(object sender, EventArgs e)
        {
            DataTable dtInteface = (DataTable)cbInterface_2.DataSource;
            int i = cbInterface_2.SelectedIndex;
            if (i != 2)
            {
                Global.inf.areaCode = "";
            }
            else
            {
                Global.pat.insuplc_admdvs = "530100";
            }
            Global.inf.hospitalNO = dtInteface.Rows[i]["HospitalNO"].ToString();
            Global.inf.hospitalName = dtInteface.Rows[i]["HospitalName"].ToString();
            Global.inf.centerURL = dtInteface.Rows[i]["CenterURL"].ToString();
            Global.inf.areaCode = dtInteface.Rows[i]["AreaCode"].ToString();
            Global.user.name = "0";
            Global.user.ID = "0";
            Global.inf.operatoType = "3";
            Global.inf.version = "v1.0";
            Global.inf.recivedSystem = "SY";
        }

        private void cmsCheck_Opening(object sender, CancelEventArgs e)
        {

        }

        /// <summary>
        /// 单条对总账事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmCheck_Single_Click(object sender, EventArgs e)
        {
            string error = "";
            if (Check_Single(out error) != 0)
            {
                MessageBox.Show("对总账失败：" + error);
            }
            else
            {
                MessageBox.Show("对总账成功");
            }

        }

        /// <summary>
        /// 单条对总账【本地】
        /// </summary>
        /// <param name="error"></param>
        /// <returns></returns>
        private int Check_Single(out string error)
        {
            error = "";string setlOptins = "";
            DataTable dt = (DataTable)dgvSettlSummary.DataSource;
            int i = dgvSettlSummary.CurrentRow.Index;

            dynamic joCheck = new JObject();
            joCheck.insutype = dt.Rows[i]["insutype"].ToString();                       //险种类型
            joCheck.clr_type = dt.Rows[i]["clr_type"].ToString();                       //清算类别            

            if (tbSettlOption.Text != "")
            {
                joCheck.setl_optins = tbSettlOption.Text; //dt.Rows[i]["setl_optins"].ToString();  //结算经办机构
                setlOptins = tbSettlOption.Text;
            }
            else
            {
                joCheck.setl_optins = dt.Rows[i]["setl_optins"].ToString();             //结算经办机构
                setlOptins = dt.Rows[i]["setl_optins"].ToString();
            }
            
            joCheck.medfee_sumamt = dt.Rows[i]["medfee_sumamt"].ToString();             //医疗费总额
            joCheck.fund_pay_sumamt = dt.Rows[i]["fund_pay_sumamt"].ToString();         //基金支付总额
            joCheck.acct_pay = dt.Rows[i]["acct_pay"].ToString();                       //个人账户支付金额
            joCheck.fixmedins_setl_cnt = dt.Rows[i]["fixmedins_setl_cnt"].ToString();   //定点医药机构结算笔数
            joCheck.stmt_begndate = dpST.Value.ToString("yyyy-MM-dd HH:mm:ss");         //对账开始日期
            joCheck.stmt_enddate = dpED.Value.ToString("yyyy-MM-dd HH:mm:ss");          //对账结束日期

            JObject joData = new JObject();
            joData.Add("data", joCheck);
            //上传给中心
            //先签到
            CenterBusiness cBus = new CenterBusiness();
            JObject jo9001Rtn = new JObject();
            cBus.signIn(out jo9001Rtn);

            Global.pat.insuplc_admdvs = setlOptins;

            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeCenterService("3201", JsonHelper.setCenterInpar("3201", joData.ToString())); 
            if (JsonHelper.parseCenterReturnJson(joRtn, out error) != 0)
            {
                return -1;
            }
            else
            {
                if (JsonHelper.getDestValue(joRtn, "output.stmtinfo.stmt_rslt") != "0")
                {
                    error = JsonHelper.getDestValue(joRtn, "output.stmtinfo.stmt_rslt_dscr");
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
        }

        private int OthPlcCheck_Single(out string error)
        {
            error = "";
            DataTable dt = (DataTable)dgvOthCheck.DataSource;
            int i = dgvOthCheck.CurrentRow.Index;

            Global.inf.areaCode = dt.Rows[i]["insuplc_admdvs"].ToString();

            int billType = int.Parse(dt.Rows[i]["BillType"].ToString());
            dynamic joCheck = new JObject();
            joCheck.psn_no = dt.Rows[i]["PersonnelNO"].ToString();
            joCheck.medfee_sumamt = billType * Convert.ToDecimal(dt.Rows[i]["Sumamt"].ToString());
            joCheck.optins_pay_sumamt = billType * (Convert.ToDecimal(dt.Rows[i]["FundPaySumamt"].ToString()) + Convert.ToDecimal(dt.Rows[i]["AccountPaySumamt"].ToString()));
            joCheck.mdtrt_setl_time = Convert.ToDateTime(dt.Rows[i]["SettlementTime"].ToString()).ToString("yyyyMMddHHmmss");
            joCheck.trns_type = dt.Rows[i]["BillType"].ToString();
            joCheck.mdtrt_id = dt.Rows[i]["MdtrtID"].ToString();
            joCheck.setl_id = dt.Rows[i]["SettlementID"].ToString();


            JArray jaCheck = new JArray();
            jaCheck.Add(joCheck);
            JObject joData = new JObject();
            joData.Add("data", jaCheck);
            //上传给中心
            //先签到
            CenterBusiness cBus = new CenterBusiness();
            JObject jo9001Rtn = new JObject();
            cBus.signIn(out jo9001Rtn);

            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeCenterService("S3501", joData.ToString());
            if (JsonHelper.parseCenterReturnJson(joRtn, out error) != 0)
            {
                return -1;
            }
            else
            {
                if (JsonHelper.getDestValue(joRtn, "output.result[0].succ_flag") != "0")
                {
                    error = JsonHelper.getDestValue(joRtn, "output.result[0].prmmsg");
                    return -1;
                }
                else
                    return 0;
            }
        }

        private int Clearing_Single(out string error)
        {
            error = "";
            DataTable dt = (DataTable)dgvClearingSum.DataSource;
            int i = dgvClearingSum.CurrentRow.Index;
            dynamic joClearing = new JObject();

            //双定点必须分开申请，通过报文头中insuplc_admdvs参保地行政区划区分。比如郑州省直双定点，向郑州申请时insuplc_admdvs传410100，向省直申请时insuplc_admdvs传419900。
            //异地申请：清算类别传9909,报文头中参保地行政区划省内传410000，跨省不需要清算申请

            Global.pat.insuplc_admdvs = dt.Rows[i]["clr_optins"].ToString();

            if (dt.Rows[i]["clr_optins"].ToString() == "410000")
                joClearing.clr_type = "9909";
            else
                joClearing.clr_type = dt.Rows[i]["clr_type"].ToString();

            joClearing.clr_way = dt.Rows[i]["clr_way"].ToString();
            joClearing.setlym = dpST_2.Value.ToString("yyyyMM");
            joClearing.psntime = dt.Rows[i]["psntime"].ToString();            
            joClearing.medfee_sumamt = dt.Rows[i]["medfee_sumamt"].ToString();
            joClearing.med_sumfee = dt.Rows[i]["med_sumfee"].ToString();
            joClearing.fund_appy_sum = dt.Rows[i]["fund_appy_sum"].ToString();
            joClearing.cash_payamt = dt.Rows[i]["cash_payamt"].ToString();
            joClearing.acct_pay = dt.Rows[i]["acct_pay"].ToString();                       
            joClearing.begndate = dpST_2.Value.ToString("yyyy-MM-dd");
            joClearing.enddate = dpED_2.Value.ToString("yyyy-MM-dd");

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

            //先签到
            //CenterBusiness cBus = new CenterBusiness();
            //JObject jo9001Rtn = new JObject();
            //cBus.signIn(out jo9001Rtn);

            InvokeHelper invoker = new InvokeHelper();
            string input = JsonHelper.setCenterInpar("3203", joData.ToString());
            JObject joRtn = invoker.invokeCenterService("3203", input);
            if (JsonHelper.parseCenterReturnJson(joRtn, out error) != 0)
            {
                return -1;
            }
            else
            {
                //保存到医保平台
                JObject joTmp = new JObject();
                joTmp.Add("HospitalDr", Global.inf.hospitalDr);
                joTmp.Add("InterfaceDr", Global.inf.interfaceDr);
                joTmp.Add("ApplyID", JsonHelper.getDestValue(joRtn, "output.result.clr_appy_evt_id"));
                joTmp.Add("OccurTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                joTmp.Add("ClrWay", dt.Rows[i]["clr_way"].ToString());
                joTmp.Add("ClrType", dt.Rows[i]["clr_type"].ToString());
                joTmp.Add("ClearYearMonth", dpST_2.Value.ToString("yyyyMM"));
                joTmp.Add("PersonTime", dt.Rows[i]["psntime"].ToString());
                joTmp.Add("Sumamt", dt.Rows[i]["med_sumfee"].ToString());
                joTmp.Add("MedAcceptSumamt", dt.Rows[i]["med_sumfee"].ToString());
                joTmp.Add("FundPay", dt.Rows[i]["fund_appy_sum"].ToString());
                joTmp.Add("CashPay", dt.Rows[i]["cash_payamt"].ToString());
                joTmp.Add("AccountPay", dt.Rows[i]["acct_pay"].ToString());
                joTmp.Add("Begndate", dpST_2.Value.ToString("yyyy-MM-dd 00:00:00"));
                joTmp.Add("Enddate", dpED_2.Value.ToString("yyyy-MM-dd 23:59:59"));
                joTmp.Add("OthPlcFlag", 0);
                joTmp.Add("ValidFlag", 1);
                joTmp.Add("Operator", "0");

                JArray jaParam = new JArray();
                jaParam.Add(joTmp);
                JObject joUpdate = new JObject();
                joUpdate.Add("params", jaParam);
                joUpdate.Add("updateUserID", "0");
                joUpdate.Add("HospitalDr", Global.inf.hospitalDr);
                joUpdate.Add("InterfaceDr", Global.inf.interfaceDr);
                joUpdate.Add("code", "09010067");
                invoker = new InvokeHelper();
                joRtn = invoker.invokeInsuService(joUpdate.ToString(), "插入清算记录");

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

        private int OthPlcClearing_Single(out string error)
        {
            if (tbInsuPlc.Text != "")
                Global.inf.areaCode = tbInsuPlc.Text;
            error = "";
            DataTable dt = (DataTable)dgvClearingSum.DataSource;
            int i = dgvClearingSum.CurrentRow.Index;

            dynamic joClearing = new JObject();
            joClearing.clr_type = dt.Rows[i]["clr_type"].ToString();
            joClearing.mon_setl_cnt = dt.Rows[i]["psntime"].ToString();
            joClearing.optins_pay_sumamt = Convert.ToDecimal(dt.Rows[i]["fund_appy_sum"].ToString()) + Convert.ToDecimal(dt.Rows[i]["acct_pay"].ToString());
            joClearing.medfee_sumamt = dt.Rows[i]["medfee_sumamt"].ToString();

            joClearing.begndate = dpST_2.Value.ToString("yyyy-MM-dd");
            joClearing.enddate = dpED_2.Value.ToString("yyyy-MM-dd");

            JObject joData = new JObject();
            joData.Add("data", joClearing);
            //上传给中心
            //先签到
            CenterBusiness cBus = new CenterBusiness();
            JObject jo9001Rtn = new JObject();
            cBus.signIn(out jo9001Rtn);

            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeCenterService("S3203", joData.ToString());
            if (JsonHelper.parseCenterReturnJson(joRtn, out error) != 0)
            {
                return -1;
            }
            else
            {
                //保存到医保平台
                JObject joTmp = new JObject();
                joTmp.Add("HospitalDr", Global.inf.hospitalDr);
                joTmp.Add("InterfaceDr", Global.inf.interfaceDr);
                joTmp.Add("ApplyID", JsonHelper.getDestValue(joRtn, "output.result.mon_setl_eid"));
                joTmp.Add("OccurTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                joTmp.Add("ClrWay", dt.Rows[i]["clr_way"].ToString());
                joTmp.Add("ClrType", dt.Rows[i]["clr_type"].ToString());
                joTmp.Add("ClearYearMonth", JsonHelper.getDestValue(joRtn, "output.result.data_ym"));
                joTmp.Add("PersonTime", dt.Rows[i]["psntime"].ToString());
                joTmp.Add("Sumamt", dt.Rows[i]["med_sumfee"].ToString());
                joTmp.Add("MedAcceptSumamt", dt.Rows[i]["med_sumfee"].ToString());
                joTmp.Add("FundPay", dt.Rows[i]["fund_appy_sum"].ToString());
                joTmp.Add("CashPay", dt.Rows[i]["cash_payamt"].ToString());
                joTmp.Add("AccountPay", dt.Rows[i]["acct_pay"].ToString());
                joTmp.Add("Begndate", dpST_2.Value.ToString("yyyy-MM-dd 00:00:00"));
                joTmp.Add("Enddate", dpED_2.Value.ToString("yyyy-MM-dd 23:59:59"));
                joTmp.Add("OthPlcFlag", 1);
                joTmp.Add("ValidFlag", 1);
                joTmp.Add("Operator", "0");

                JArray jaParam = new JArray();
                jaParam.Add(joTmp);
                JObject joUpdate = new JObject();
                joUpdate.Add("params", jaParam);
                joUpdate.Add("updateUserID", "0");
                joUpdate.Add("HospitalDr", Global.inf.hospitalDr);
                joUpdate.Add("InterfaceDr", Global.inf.interfaceDr);
                joUpdate.Add("code", "09010067");
                invoker = new InvokeHelper();
                joRtn = invoker.invokeInsuService(joUpdate.ToString(), "插入清算记录");

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

        private int CancleClearing_Single(out string error)
        {

            error = "";
            DataTable dt = (DataTable)dgvClearingData.DataSource;
            int i = dgvClearingData.CurrentRow.Index;

            dynamic joCancleClearing = new JObject();
            joCancleClearing.clr_appy_evt_id = dt.Rows[i]["ApplyID"].ToString();

            JObject joData = new JObject();
            joData.Add("data", joCancleClearing);
            //上传给中心
            //先签到
            CenterBusiness cBus = new CenterBusiness();
            JObject jo9001Rtn = new JObject();
            cBus.signIn(out jo9001Rtn);

            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeCenterService("3204", joData.ToString());
            if (JsonHelper.parseCenterReturnJson(joRtn, out error) != 0)
            {
                return -1;
            }
            else
            {
                //保存到医保平台
                JObject joTmp = new JObject();
                joTmp.Add("HospitalDr", Global.inf.hospitalDr);
                joTmp.Add("InterfaceDr", Global.inf.interfaceDr);
                joTmp.Add("ApplyID", dt.Rows[i]["ApplyID"].ToString());
                //joTmp.Add("CancleOccurTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //joTmp.Add("ClrWay", dt.Rows[i]["clr_way"].ToString());
                joTmp.Add("ClrType", dt.Rows[i]["ClrType"].ToString());
                //joTmp.Add("ClearYearMonth", dpST_2.Value.ToString("yyyyMM"));
                //joTmp.Add("PersonTime", dt.Rows[i]["psntime"].ToString());
                //joTmp.Add("Sumamt", dt.Rows[i]["med_sumfee"].ToString());
                //joTmp.Add("MedAcceptSumamt", dt.Rows[i]["med_sumfee"].ToString());
                //joTmp.Add("FundPay", dt.Rows[i]["fund_appy_sum"].ToString());
                //joTmp.Add("CashPay", dt.Rows[i]["cash_payamt"].ToString());
                //joTmp.Add("AccountPay", dt.Rows[i]["acct_pay"].ToString());
                //joTmp.Add("Begndate", dpST_2.Value.ToString("yyyy-MM-dd 00:00:00"));
                //joTmp.Add("Enddate", dpED_2.Value.ToString("yyyy-MM-dd 23:59:59"));
                joTmp.Add("ValidFlag", -1);
                joTmp.Add("updateUserID", "0");
                //joTmp.Add("Operator", "0");

                JArray jaParam = new JArray();
                jaParam.Add(joTmp);
                JObject joUpdate = new JObject();
                joUpdate.Add("params", jaParam);
                joUpdate.Add("updateUserID", "0");
                joUpdate.Add("HospitalDr", Global.inf.hospitalDr);
                joUpdate.Add("InterfaceDr", Global.inf.interfaceDr);
                joUpdate.Add("code", "09010067");
                invoker = new InvokeHelper();
                joRtn = invoker.invokeInsuService(joUpdate.ToString(), "更新清算记录");

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

        private int CancleOthPlcClearing_Single(out string error)
        {

            error = "";
            DataTable dt = (DataTable)dgvClearingData.DataSource;
            int i = dgvClearingData.CurrentRow.Index;

            dynamic joCancleClearing = new JObject();
            joCancleClearing.clr_appy_evt_id = dt.Rows[i]["ApplyID"].ToString();
            joCancleClearing.data_ym = dt.Rows[i]["ClearYearMonth"].ToString();

            JObject joData = new JObject();
            joData.Add("data", joCancleClearing);
            //上传给中心
            //先签到
            CenterBusiness cBus = new CenterBusiness();
            JObject jo9001Rtn = new JObject();
            cBus.signIn(out jo9001Rtn);

            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeCenterService("S3204", joData.ToString());
            if (JsonHelper.parseCenterReturnJson(joRtn, out error) != 0)
            {
                return -1;
            }
            else
            {
                //保存到医保平台
                JObject joTmp = new JObject();
                joTmp.Add("HospitalDr", Global.inf.hospitalDr);
                joTmp.Add("InterfaceDr", Global.inf.interfaceDr);
                joTmp.Add("ApplyID", dt.Rows[i]["ApplyID"].ToString());
                //joTmp.Add("CancleOccurTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //joTmp.Add("ClrWay", dt.Rows[i]["clr_way"].ToString());
                joTmp.Add("ClrType", dt.Rows[i]["ClrType"].ToString());
                //joTmp.Add("ClearYearMonth", dpST_2.Value.ToString("yyyyMM"));
                //joTmp.Add("PersonTime", dt.Rows[i]["psntime"].ToString());
                //joTmp.Add("Sumamt", dt.Rows[i]["med_sumfee"].ToString());
                //joTmp.Add("MedAcceptSumamt", dt.Rows[i]["med_sumfee"].ToString());
                //joTmp.Add("FundPay", dt.Rows[i]["fund_appy_sum"].ToString());
                //joTmp.Add("CashPay", dt.Rows[i]["cash_payamt"].ToString());
                //joTmp.Add("AccountPay", dt.Rows[i]["acct_pay"].ToString());
                //joTmp.Add("Begndate", dpST_2.Value.ToString("yyyy-MM-dd 00:00:00"));
                //joTmp.Add("Enddate", dpED_2.Value.ToString("yyyy-MM-dd 23:59:59"));
                joTmp.Add("ValidFlag", -1);
                joTmp.Add("updateUserID", "0");
                //joTmp.Add("Operator", "0");

                JArray jaParam = new JArray();
                jaParam.Add(joTmp);
                JObject joUpdate = new JObject();
                joUpdate.Add("params", jaParam);
                joUpdate.Add("updateUserID", "0");
                joUpdate.Add("HospitalDr", Global.inf.hospitalDr);
                joUpdate.Add("InterfaceDr", Global.inf.interfaceDr);
                joUpdate.Add("code", "09010067");
                invoker = new InvokeHelper();
                joRtn = invoker.invokeInsuService(joUpdate.ToString(), "更新清算记录");

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


        }

        private int queryHisSettlementInfo(out string error)
        {
            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfHisSettlRec(dgvHisSettlRec);
            error = "";
            try
            {
                DataTable dtInteface = (DataTable)cbxInterface.DataSource;
                int i = cbxInterface.SelectedIndex;

                string sqlStr = "SELECT SUM(BillType*Sumamt) AS medfee_sumamt,count(*) AS fixmedins_setl_cnt, ";
                sqlStr = sqlStr + " SUM(BillType*AccountPaySumamt) AS acct_pay,SUM(BillType*HealthInsurancePay) AS fund_pay_sumamt ";
                //sqlStr = sqlStr + " Interface_dr,clearingWay AS clr_way,clearingType AS clr_type ";
                string conditionStr = " ";
                DataTable dtSettlSummary = (DataTable)dgvSettlSummary.DataSource;
                int iCurRow = dgvSettlSummary.CurrentRow.Index;

                //DataTable dtInteface = (DataTable)cbxInterface.DataSource;
                if (cbgGroupSet.GetItemCheckState(0))
                {
                    conditionStr = conditionStr + " and Interface_Dr ='" + dtSettlSummary.Rows[iCurRow]["Interface_dr"].ToString() + "'";
                }
                if (cbgGroupSet.GetItemCheckState(1))
                {
                    conditionStr = conditionStr + " and InsuranceType ='" + dtSettlSummary.Rows[iCurRow]["insutype"].ToString() + "'";
                }
                if (cbgGroupSet.GetItemCheckState(2))
                {
                    conditionStr = conditionStr + " and ClearingType ='" + dtSettlSummary.Rows[iCurRow]["clr_type"].ToString() + "'";
                }
                if (cbgGroupSet.GetItemCheckState(3))
                {
                    conditionStr = conditionStr + " and ClearingOrgan ='" + dtSettlSummary.Rows[iCurRow]["setl_optins"].ToString() + "'";
                }
                if (cbgGroupSet.GetItemCheckState(4))
                {
                    sqlStr = sqlStr + ",BillType";
                    conditionStr = conditionStr + " and BillType ='" + dtSettlSummary.Rows[iCurRow]["BillType"].ToString() + "'";
                }

                sqlStr = "select *  FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + dtInteface.Rows[i]["HospitalDr"].ToString();
                sqlStr = sqlStr + " and OccurTime>'" + dpST.Text + "'";
                sqlStr = sqlStr + " and OccurTime<'" + dpED.Text + "'";

                //ValidFlag=1 and BillType=1 表示正常结算记录   ValidFlag=0 and BillType=-1 表示退费记录  ValidFlag=0表示无效记录 
                if (cbxValid.SelectedIndex != 0)
                {
                    if (cbxValid.SelectedIndex == 1)
                        sqlStr = sqlStr + " and ValidFlag =1 and BillType=1";
                    else
                        sqlStr = sqlStr + " and ValidFlag =0 and BillType=-1";
                }

                //省医保和市医保对账一样，异地对账需要用到另外的对账交易
                if (Global.inf.interfaceDr == 1)
                {
                    sqlStr = sqlStr + " and (InsuranceAreaCode='539900' or InsuranceAreaCode='530100')";
                }

                //conditionStr = conditionStr.Substring(0,conditionStr.Length -1 );
                //conditionStr = conditionStr.Remove(conditionStr.Length - 1, 1);

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

                //DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
                JArray ja = JArray.Parse(JsonHelper.getDestValue(joRtn, "result.data"));
                DataTable dt = (DataTable)JsonConvert.DeserializeObject(JsonHelper.getDestValue(joRtn, "result.data"), (typeof(DataTable)));
                dgvHisSettlRec.DataSource = dt;
                //dt.Columns[7].DataType = typeof(float);//不允许
                //dgvHisSettlRecFooter.DataGridView = dgvHisSettlRec;
                //dgvHisSettlRecFooter.Dock = System.Windows.Forms.DockStyle.Bottom;
                //dgvHisSettlRecFooter.Clear();
                //dgvHisSettlRecFooter["AdmID"] = "合计";
                //dgvHisSettlRecFooter["OverLimitAmount"] = "测试";

                return 0;
            }
            catch (Exception ex)
            {
                error = "queryHisSettlementInfo:" + ex.Message;
                return -1;
            }
        }

        private void tsmCheckDetail_Single_Click(object sender, EventArgs e)
        {
            //HIS明细
            string error;
            if (queryHisSettlementInfo(out error) != 0)
            {
                MessageBox.Show(error);
            }
            //中心明细
            if (CheckDetail_Single(out error) != 0)
            {
                MessageBox.Show(error);
            }
        }

        /// <summary>
        /// 查询HIS结算明细记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmHisRecord_Click(object sender, EventArgs e)
        {
            string error;
            if (queryHisSettlementInfo(out error) != 0)
            {
                MessageBox.Show(error);
            }
        }

        public static void writeToTxt(string content, string filePath, string fileName)
        {
            //创建文件夹,文件夹名称与TXT同名
            string finalPath = filePath + "\\" + fileName;
            if (!Directory.Exists(finalPath))
            {
                DirectoryInfo dirInfo = Directory.CreateDirectory(finalPath);
            }
            //判断文件夹中是否存在txt
            string finalFileName = finalPath + "\\" + fileName + ".txt";
            if (!File.Exists(finalFileName))
            {
                FileStream fs1 = File.Create(finalFileName);
                fs1.Close();
            }

            FileStream fs = new FileStream(finalFileName, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(content);
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 读文件到byte[]
        /// </summary>
        /// <param name="fileName">硬盘文件路径</param>
        /// <returns></returns>
        public static byte[] ReadFileToByte(string fileName)
        {
            FileStream pFileStream = null;
            byte[] pReadByte = new byte[0];
            try
            {
                pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(pFileStream);
                r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件开
                pReadByte = r.ReadBytes((int)r.BaseStream.Length);
                return pReadByte;
            }
            catch
            {
                return pReadByte;
            }
            finally
            {
                if (pFileStream != null)
                    pFileStream.Close();
            }
        }

        /// <summary>
        ///单字节转有符号整数
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string byteArrayToDecString(byte[] data)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                builder.Append((sbyte)data[i] + ",");
            }
            return builder.ToString().Trim();
        }

        private int HISDetailDataExport(string filePath, string fileName)
        {
            try
            {
                DataTable dt = (DataTable)dgvHisSettlRec.DataSource;
                string content = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string flag = "";
                    if (dt.Rows[i]["ValidFlag"].ToString() == "-1")
                    {
                        flag = "1";
                    }
                    else
                    {
                        flag = "0";
                    }
                    content = "\r\n"
                            + dt.Rows[i]["SettlementID"].ToString() + "\t"
                            + dt.Rows[i]["MdtrtID"].ToString() + "\t"
                            + dt.Rows[i]["PersonnelNO"].ToString() + "\t"
                            + dt.Rows[i]["Sumamt"].ToString() + "\t"
                            + dt.Rows[i]["FundPaySumamt"].ToString() + "\t"
                            + dt.Rows[i]["AccountPaySumamt"].ToString() + "\t"
                            + flag
                            + content;
                }
                string finalContent = content.Remove(0, 2);
                writeToTxt(finalContent, filePath, fileName);
                return 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -1;
            }
        }

        private void tsmExport_Click(object sender, EventArgs e)
        {
            txtName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            txtPath = Global.currentDirectory + "\\Download";
            if (HISDetailDataExport(txtPath, txtName) != 0)
            {
                MessageBox.Show("导出TXT失败！");
            }
            else
            {
                MessageBox.Show("导出TXT成功！");
            }
            
            //System.IO.Compression.ZipFile.CreateFromDirectory(txtPath + "\\" + "2022ceshi", txtPath + "\\" + "111.zip");
        }

        private void tsmCompress_Click(object sender, EventArgs e)
        {
            string path = @"C:\ProgramData\prykNT\prBrowser\bin\service\plugins\INSUNew\DownLoad\111";
            string name = @"1121.zip";
            string finalDirPath = txtPath + "\\" + txtName;
            finalAchPath = finalDirPath + ".zip";
            System.IO.Compression.ZipFile.CreateFromDirectory(finalDirPath, finalAchPath);
            //System.IO.Compression.ZipFile.CreateFromDirectory(path, name);
            //System.IO.Compression.ZipFile.CreateFromDirectory(path, name, 0, true);

            MessageBox.Show("将TXT压缩为ZIP成功！");
        }

        private void tsmZIPToSDec_Click(object sender, EventArgs e)
        {
            byte[] bArray = ReadFileToByte(finalAchPath);
            string str = byteArrayToDecString(bArray);
            Global.writeLog(str);

            MessageBox.Show("ZIP转为有符号整数成功！");
        }

        private void tsmUploadZIP_Click(object sender, EventArgs e)
        {
            string outParam = "";
            byte[] bArray = ReadFileToByte(finalAchPath);
            string str = "[" + byteArrayToDecString(bArray) + "]";

            JObject joTmp = new JObject();
            joTmp.Add("in", JArray.Parse(str));
            joTmp.Add("filename", txtName + ".zip");

            Global.inf.fileName = txtName + ".zip";

            //joTmp.Add("filename", finalAchPath.Replace("\\",@"\"));
            joTmp.Add("fixmedins_code", Global.inf.hospitalNO);

            JObject joFsUploadIn = new JObject();
            joFsUploadIn.Add("fsUploadIn", joTmp);

            InvokeHelper invoker = new InvokeHelper();
            JObject jo9101Rtn= invoker.invokeCenterService("9101", JsonHelper.setCenterInpar("9101", joFsUploadIn.ToString()));

            if (JsonHelper.parseCenterRtnValue(jo9101Rtn, out outParam) != 0)
            {                
                outParam = JsonHelper.setExceptionJson(-1, "【9101】文件上传失败", outParam).ToString();
                
                return;
            }
            else
            {
                MessageBox.Show("【9101】文件上传成功");
            }
        }

        private void tsm3202_Click(object sender, EventArgs e)
        {
            string outParam = "";
            DataTable dt = (DataTable)dgvSettlSummary.DataSource;
            int i = dgvSettlSummary.CurrentRow.Index;


            MessageBox.Show(dt.Rows[i]["clr_type"].ToString());

            dynamic joCheck = new JObject();
            joCheck.file_qury_no = JObject.Parse(tbTmp.Text);
            joCheck.clr_type = dt.Rows[i]["clr_type"].ToString();
            joCheck.setl_optins = dt.Rows[i]["setl_optins"].ToString();
            joCheck.stmt_begndate = dpST.Value.ToString("yyyy-MM-dd HH:mm:ss");
            joCheck.stmt_enddate = dpED.Value.ToString("yyyy-MM-dd HH:mm:ss");
            joCheck.medfee_sumamt = dt.Rows[i]["medfee_sumamt"].ToString();
            joCheck.fund_pay_sumamt = dt.Rows[i]["fund_pay_sumamt"].ToString();
            joCheck.cash_payamt = dt.Rows[i]["cash_payamt"].ToString();
            joCheck.fixmedins_setl_cnt = dt.Rows[i]["fixmedins_setl_cnt"].ToString();

            JObject joData = new JObject();
            joData.Add("data", joCheck);
            InvokeHelper invoker = new InvokeHelper();
           
            JObject jo3202Rtn= invoker.invokeCenterService("3202", JsonHelper.setCenterInpar("3202", joData.ToString()));
            if (JsonHelper.parseCenterRtnValue(jo3202Rtn, out outParam) != 0)
            {
                outParam = JsonHelper.setExceptionJson(-1, "【3202】医保明细对账失败", outParam).ToString();
                MessageBox.Show(outParam);
                return;
            }
            else
            {
                MessageBox.Show("【3202】医保明细对账成功");
            }
        }

        private void tsmDownload_Click(object sender, EventArgs e)
        {
            string outParam = "";
            JObject joTmp = new JObject();
            joTmp.Add("file_qury_no", JObject.Parse(tbTmp.Text.Replace(@"\\", @"\")));
            joTmp.Add("filename", txtName + ".zip");
            joTmp.Add("fixmedins_code", Global.inf.hospitalNO);

            JObject joFsDownloadIn = new JObject();
            joFsDownloadIn.Add("fsDownloadIn", joTmp);

            InvokeHelper invoker = new InvokeHelper();
            jo9102Rtn = invoker.invokeCenterService("9102", JsonHelper.setCenterInpar("9102", joFsDownloadIn).ToString());

            if (JsonHelper.parseCenterRtnValue(jo9102Rtn, out outParam) != 0)
            {
                outParam = JsonHelper.setExceptionJson(-1, "【9102】文件下载失败", outParam).ToString();
                MessageBox.Show(outParam);
                return;
            }
            else
            {
                MessageBox.Show("【9102】文件下载成功");
            }
        }

        private void tsmUnCompress_Click(object sender, EventArgs e)
        {
            //解压缩
            string zipFilePath = jo9102Rtn["filePath"].ToString();
            string txtFileDir = System.Environment.CurrentDirectory + "\\Download";
            //string txtFilePath = txtFileDir + "\\" + filename.Substring(0, filename.Length - 4);
            string txtFilePath = txtFileDir;
            if (File.Exists(txtFilePath))
            {
                File.Delete(txtFilePath);
            }

            ZipFile.ExtractToDirectory(zipFilePath, txtFileDir);
        }

        private void tsmImport_Click(object sender, EventArgs e)
        {
            GridViewSetter grd = new GridViewSetter();
            grd.SetHeaderTextOfDgvCenterSetlRec(dgvCenterSettlRec);
            string txtFileDir = tbTmp.Text;//E:\GHSF\SCYBDownLoad\result.txt
            string[] lines = System.IO.File.ReadAllLines(txtFileDir);
            Global.writeLog(lines.ToString());

            DataTable dt = new DataTable();
            dt.Columns.Add("sn", typeof(int));
            dt.Columns.Add("psn_no", typeof(string));
            dt.Columns.Add("mdtrt_id", typeof(string));
            dt.Columns.Add("setl_id", typeof(string));
            dt.Columns.Add("msgid", typeof(string));
            dt.Columns.Add("stmt_rslt", typeof(string));
            dt.Columns.Add("refd_setl_flag", typeof(string));
            dt.Columns.Add("memo", typeof(string));
            dt.Columns.Add("medfee_sumamt", typeof(string));
            dt.Columns.Add("fund_pay_sumamt", typeof(string));
            dt.Columns.Add("acct_pay", typeof(string));

            //foreach (string line in lines)
            for (int i = 0; i < lines.Length; i++)
            {
                string[] strs = (lines[i] + "\t").Split('\t');
                DataRow dr = dt.NewRow();
                //Global.inf.writeLog(lines[i].ToString());
                //Global.inf.writeLog(strs.Length.ToString());

                dr["sn"] = i;
                dr["psn_no"] = strs[0];
                dr["mdtrt_id"] = strs[1];
                dr["setl_id"] = strs[2];
                dr["msgid"] = strs[3];
                dr["stmt_rslt"] = strs[4];
                dr["refd_setl_flag"] = strs[5];
                dr["memo"] = strs[6];
                dr["medfee_sumamt"] = strs[7];
                dr["fund_pay_sumamt"] = strs[8];
                dr["acct_pay"] = strs[9];
                //dr["Field2"] = strs[2];

                dt.Rows.Add(dr);
            }
            dgvCenterSettlRec.DataSource = dt;
        }

        private int exportAndCompress(out string zipPath)
        {
            zipPath = "";
            try
            {
                //导出TXT
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                string filePath = Global.currentDirectory + "\\Download";
                HISDetailDataExport(filePath, fileName);
                //压缩
                string finalDirPath = filePath + "\\" + fileName;//同名文件夹
                zipPath = finalDirPath + ".zip";
                System.IO.Compression.ZipFile.CreateFromDirectory(finalDirPath, zipPath);
                return 0;
            }
            catch (Exception ex)
            {
                zipPath = "exportAndCompress:" + ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 上传ZIP文件转字节流再转换为有符号10进制数组后上传
        /// </summary>
        /// <param name="zipPath"></param>
        /// <param name="file_qury_no"></param>
        /// <returns></returns>
        private int uploadFileToCenter(string zipPath, out string file_qury_no)
        {
            string outParam = "";
            try
            {
                byte[] bArray = ReadFileToByte(zipPath);
                string str = "[" + byteArrayToDecString(bArray) + "]";

                JObject joTmp = new JObject();
                joTmp.Add("in", JArray.Parse(str));
                joTmp.Add("filename", txtName + ".zip");
                joTmp.Add("fixmedins_code", Global.inf.hospitalNO);

                JObject joFsUploadIn = new JObject();
                joFsUploadIn.Add("fsUploadIn", joTmp);

                InvokeHelper invoker = new InvokeHelper(); 
                JObject jo9101Rtn = invoker.invokeCenterService("9101", JsonHelper.setCenterInpar("9101", joFsUploadIn.ToString()));

                if (JsonHelper.parseCenterReturnJson(jo9101Rtn, out outParam) != 0)
                {
                    file_qury_no = outParam;
                    return -1;
                }
                else
                {
                    file_qury_no = JsonHelper.getDestValue(jo9101Rtn, "output.file_qury_no");
                    return 0;
                }

            }
            catch (Exception ex)
            {
                file_qury_no = "uploadFileToCenter:" + ex.Message;
                return -1;
            }
        }
        private int checkDetail(string file_qury_no, out string outParam, out string fileName)
        {
            fileName = "";
            try
            {
                DataTable dt = (DataTable)dgvSettlSummary.DataSource;
                int i = dgvSettlSummary.CurrentRow.Index;

                Global.inf.areaCode = "";

                dynamic joCheck = new JObject();
                joCheck.file_qury_no = file_qury_no.Replace(@"\\", @"\");
                joCheck.clr_type = dt.Rows[i]["clr_type"].ToString();
                joCheck.setl_optins = dt.Rows[i]["setl_optins"].ToString();
                joCheck.stmt_begndate = dpST.Value.ToString("yyyy-MM-dd HH:mm:ss");
                joCheck.stmt_enddate = dpED.Value.ToString("yyyy-MM-dd HH:mm:ss");
                joCheck.medfee_sumamt = dt.Rows[i]["medfee_sumamt"].ToString();
                joCheck.fund_pay_sumamt = dt.Rows[i]["fund_pay_sumamt"].ToString();
                joCheck.cash_payamt = dt.Rows[i]["cash_payamt"].ToString();
                joCheck.fixmedins_setl_cnt = dt.Rows[i]["fixmedins_setl_cnt"].ToString();

                JObject joData = new JObject();
                joData.Add("data", joCheck);
                InvokeHelper invoker = new InvokeHelper(); 
                JObject jo3202Rtn = invoker.invokeCenterService("3202", JsonHelper.setCenterInpar("3202", joData.ToString()));
                if (JsonHelper.parseCenterReturnJson(jo3202Rtn, out outParam) != 0)
                {
                    return -1;
                }
                else
                {
                    outParam = JsonHelper.getDestValue(jo3202Rtn, "output.fileinfo.file_qury_no");
                    fileName = JsonHelper.getDestValue(jo3202Rtn, "output.fileinfo.filename");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outParam = "checkDetail:" + ex.Message;
                return -1;
            }

        }
        private int downloadZIP(string file_qury_no, string fileName, out string outParam)
        {
            outParam = "";
            try
            {
                JObject joTmp = new JObject();
                joTmp = new JObject();
                joTmp.Add("file_qury_no", file_qury_no.Replace(@"\\", @"\"));
                joTmp.Add("filename", fileName);
                joTmp.Add("fixmedins_code", Global.inf.hospitalNO);

                JObject joFsDownloadIn = new JObject();
                joFsDownloadIn.Add("fsDownloadIn", joTmp);
                InvokeHelper invoker = new InvokeHelper();
                JObject jo9102Rtn = invoker.DownloadCenterFile(JsonHelper.setCenterInpar("9102", joFsDownloadIn).ToString());
                string error = "";
                if (JsonHelper.parseIrisRtnValue(jo9102Rtn, out error) != 0)
                {
                    outParam = error;
                    return -1;
                }
                else
                {
                    outParam = JsonHelper.getDestValue(jo9102Rtn, "filePath");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outParam = "downloadZIP:" + ex.Message;
                return -1;
            }

        }
        private int importToDgvCenterSetlRec(string fileName, string zipFilePath, out string outParam)
        {
            outParam = "";
            try
            {
                string dir = fileName.Substring(1, fileName.Length - 4);
                //解压缩
                string txtFileDir = System.Environment.CurrentDirectory + "\\Download\\" + dir;
                string txtFilePath = zipFilePath.Substring(0, zipFilePath.Length - 4);
                if (File.Exists(txtFilePath))
                {
                    File.Delete(txtFilePath);
                }
                if (!Directory.Exists(txtFileDir))
                {
                    Directory.CreateDirectory(txtFileDir);
                }

                ZipFile.ExtractToDirectory(zipFilePath, txtFileDir);

                //导入文件
                GridViewSetter grd = new GridViewSetter();
                grd.SetHeaderTextOfDgvCenterSetlRec(dgvCenterSettlRec);
                //txtFileDir = txtFileDir;//E:\GHSF\SCYBDownLoad\result.txt
                string[] lines = System.IO.File.ReadAllLines(txtFileDir + "\\result.txt");

                DataTable dt = new DataTable();
                dt.Columns.Add("sn", typeof(int));
                dt.Columns.Add("psn_no", typeof(string));
                dt.Columns.Add("mdtrt_id", typeof(string));
                dt.Columns.Add("setl_id", typeof(string));
                dt.Columns.Add("msgid", typeof(string));
                dt.Columns.Add("stmt_rslt", typeof(string));
                dt.Columns.Add("refd_setl_flag", typeof(string));
                dt.Columns.Add("memo", typeof(string));
                dt.Columns.Add("medfee_sumamt", typeof(string));
                dt.Columns.Add("fund_pay_sumamt", typeof(string));
                dt.Columns.Add("acct_pay", typeof(string));

                //foreach (string line in lines)
                for (int i = 0; i < lines.Length; i++)
                {
                    string[] strs = (lines[i] + "\t").Split('\t');
                    DataRow dr = dt.NewRow();
                    //Global.inf.writeLog(lines[i].ToString());
                    //Global.inf.writeLog(strs.Length.ToString());
                    dr["sn"] = i + 1;
                    dr["psn_no"] = strs[0];
                    dr["mdtrt_id"] = strs[1];
                    dr["setl_id"] = strs[2];
                    dr["msgid"] = strs[3];
                    dr["stmt_rslt"] = strs[4];
                    dr["refd_setl_flag"] = strs[5];
                    dr["memo"] = strs[6];
                    dr["medfee_sumamt"] = strs[7];
                    dr["fund_pay_sumamt"] = strs[8];
                    dr["acct_pay"] = strs[9];
                    //dr["Field2"] = strs[2];

                    dt.Rows.Add(dr);
                }
                dgvCenterSettlRec.DataSource = dt;

                return 0;
            }
            catch (Exception ex)
            {
                outParam = "importToDgvCenterSetlRec:" + ex.Message;
                return -1;
            }
        }

        private int CheckDetail_Single(out string outParam)
        {
            outParam = "";
            //先签到
            CenterBusiness cBus = new CenterBusiness();
            JObject jo9001Rtn = new JObject();
            cBus.signIn(out jo9001Rtn);
            try
            {
                //导出并压缩
                if (exportAndCompress(out outParam) != 0)
                {
                    return -1;
                }
                string zipPath = outParam;
                Global.writeLog("exportAndCompress:" + zipPath);
                //上传给中心，
                if (uploadFileToCenter(zipPath, out outParam) != 0)
                {
                    return -1;
                }
                Global.writeLog("uploadFileToCenter:" + outParam);
                string file_query_no = outParam;
                string fileName = "";
                //3202明细对账  输出查询号和文件名
                if (checkDetail(file_query_no, out outParam, out fileName) != 0)
                {
                    return -1;
                }
                file_query_no = outParam;
                Global.writeLog("checkDetail:" + outParam + "///" + fileName);
                //下载  获取 查询号和文件名后 下载
                if (downloadZIP(file_query_no, fileName, out outParam) != 0)
                {
                    return -1;
                }

                zipPath = outParam;

                Global.writeLog("downloadZIP:" + outParam);
                //导入DGV
                if (importToDgvCenterSetlRec(fileName, zipPath, out outParam) != 0)
                {
                    return -1;
                }
                Global.writeLog("importToDgvCenterSetlRec:" + outParam);
                return 0;
            }
            catch (Exception ex)
            {
                outParam = "CheckDetail_Single:" + ex.Message;
                return -1;
            }

        }

        private void dgvRowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            dgv.RowHeadersWidth = 60;
            if (dgv.Rows.Count > 1)
                e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void dgvSettlSummary_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (dgvSettlSummary.Rows.Count > 1)
                e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void dgvHisSettlRec_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (dgvHisSettlRec.Rows.Count > 1)
                e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }
        private int compareDataGridView(string value, string colName, Sunny.UI.UIDataGridView dgv)
        {
            try
            {
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells[colName].Value.ToString() == value)
                    {
                        return 0;
                    }
                }
                return -1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("compareDataGridView" + ex.Message);
                return -1;
            }
        }
        private void tsmAICheck_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dgvHisSettlRec.RowCount; i++)
            {
                string value = dgvHisSettlRec.Rows[i].Cells["SettlementID"].Value.ToString();
                string colName = "setl_id";
                if (compareDataGridView(value, colName, dgvCenterSettlRec) != 0)
                {
                    dgvHisSettlRec.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    rtbCheckDetailLog.AppendText("HIS结算ID:" + value + "在中心明细中未找到数据！" + "\r\n");
                }
            }

            for (int i = 0; i < dgvCenterSettlRec.RowCount; i++)
            {
                string value = dgvCenterSettlRec.Rows[i].Cells["setl_id"].Value.ToString();
                string colName = "SettlementID";
                if (compareDataGridView(value, colName, dgvHisSettlRec) != 0)
                {
                    dgvCenterSettlRec.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    rtbCheckDetailLog.AppendText("中心结算ID:" + value + "在HIS明细中未找到数据！" + "\r\n");
                }
            }
        }

        private void tsmCheckDetail_Batch_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            int i = dgvHisSettlRec.CurrentRow.Index;
            DataTable dt = (DataTable)dgvHisSettlRec.DataSource;
            MessageBox.Show(dt.Rows[i]["AccountPaySumamt"].ToString());
        }

        private void btnAddOneDay_Click(object sender, EventArgs e)
        {
            dpST.Value = dpST.Value.AddDays(1);
            dpED.Value = dpED.Value.AddDays(1);
        }

        private void btnReduceOndDay_Click(object sender, EventArgs e)
        {
            dpST.Value = dpST.Value.AddDays(-1);
            dpED.Value = dpED.Value.AddDays(-1);
        }

        private void Clearing1()
        {
            //组织入参，进行中心清算
            int i = dgvSettlSummary.CurrentRow.Index;
            DataTable dt = (DataTable)dgvSettlSummary.DataSource;

            JObject joData = new JObject();
            joData.Add("", dgvSettlSummary.CurrentRow.Cells[""].Value.ToString());
            //存到医保平台
        }

        private void btnQueryClrSum_Click(object sender, EventArgs e)
        {
            DataTable dtInteface = (DataTable)cbInterface_2.DataSource;
            int i = cbInterface_2.SelectedIndex;

            string sqlStr = " SELECT SUM(Billtype*Sumamt) AS medfee_sumamt,SUM(Billtype*(0.00+FundPaySumamt+AccountPaySumamt+PersonCashPay)) AS med_sumfee, "
                          + " SUM(billtype*PersonCashPay) AS cash_payamt,count(*) AS psntime, ";            
            sqlStr = sqlStr + " SUM(billtype*AccountPaySumamt) AS acct_pay,SUM(Billtype*(0.00+FundPaySumamt+AccountPaySumamt)) AS fund_appy_sum, ";
            sqlStr = sqlStr + " ClearingType as clr_type,ClearingWay as clr_way,Interface_Dr,ClearingOrgan as clr_optins ";
            sqlStr = sqlStr + " FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + dtInteface.Rows[i]["HospitalDr"].ToString();
            sqlStr = sqlStr + " and OccurTime>'" + dpST_2.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED_2.Text + "'";

            if (cbInterface_2.Text != "")
            {
                sqlStr = sqlStr + " and Interface_dr =" + dtInteface.Rows[i]["ID"].ToString();
            }

            if (cbInsutype_2.Text != "")
            {
                sqlStr = sqlStr + " and InsuranceType ='" + cbInsutype_2.SelectedValue + "'";
            }

            if (cbClrType_2.Text != "")
            {
                sqlStr = sqlStr + " and ClearingType ='" + cbClrType_2.SelectedValue + "'";
            }

            if (tbSettlOption_2.Text != "")
            {
                sqlStr = sqlStr + " and ClearingOrgan ='" + tbSettlOption_2.Text + "'";
            }

            if (cbClrWay_2.Text != "")
            {
                sqlStr = sqlStr + " and ClearingWay ='" + cbClrWay_2.SelectedValue + "'";
            }

            if (cbValid_2.SelectedIndex != 0)
            {
                if (cbValid_2.SelectedIndex == 1)
                { sqlStr = sqlStr + " and ValidFlag =1"; }
                else
                    sqlStr = sqlStr + " and ValidFlag =-1";
            }

            sqlStr = sqlStr + " and ReversalFlag<>1 ";

            //省医保本地            
            //if ((Global.inf.interfaceDr == 10) && (cbOtherPlaceFlag.SelectedIndex == 2))
            //{
            //    sqlStr = sqlStr + " and (left(InsuranceAreaCode,4)='4101' or left(InsuranceAreaCode,4)='4199')";
            //}
            ////省医保异地
            //if ((Global.inf.interfaceDr == 10) && (cbOtherPlaceFlag.SelectedIndex == 1))
            //{
            //    sqlStr = sqlStr + " and (left(InsuranceAreaCode,4)<>'4199' and left(InsuranceAreaCode,4)<>'4101')";
            //}

            sqlStr = sqlStr + " Group By Interface_Dr,ClearingType,ClearingWay,ClearingOrgan";
            JObject joSqlstr = new JObject();

            //MessageBox.Show("哈哈："+sqlStr);

            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010068");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询汇总结算信息(清算)");

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


        private void tmsClearing_2_Click(object sender, EventArgs e)
        {
            string error = "";
            if ((Global.inf.interfaceDr == 1) && (cbOtherPlaceFlag.SelectedIndex == 1))
            {
                if (OthPlcClearing_Single(out error) != 0)
                {
                    MessageBox.Show("异地清算失败：" + error);
                }
                else
                {
                    MessageBox.Show("异地清算成功");
                }
            }
            else
            {
                if (Clearing_Single(out error) != 0)
                {
                    MessageBox.Show("清算失败：" + error);
                }
                else
                {
                    MessageBox.Show("清算成功");
                }
            }

        }

        private void btnClose_3_Click(object sender, EventArgs e)
        {

        }

        private void btnQueryClearing_Click(object sender, EventArgs e)
        {
            DataTable dtInteface = (DataTable)cbInterface_3.DataSource;
            int i = cbInterface_3.SelectedIndex;

            string sqlStr = "SELECT * from  BS_MedInsuClearingRecord where Hosp_Dr=" + dtInteface.Rows[i]["HospitalDr"].ToString(); ;
            sqlStr = sqlStr + " and interface_Dr =" + dtInteface.Rows[i]["ID"].ToString();
            if (rbgTimeWay.SelectedIndex == 0)
            {
                sqlStr = sqlStr + " and OccurTime>'" + dpST_3.Value.ToString("yyyy-MM-dd 00:00:00") + "'";
                sqlStr = sqlStr + " and OccurTime<'" + dpED_3.Value.ToString("yyyy-MM-dd 23:59:59") + "'";
            }
            else
            {
                sqlStr = sqlStr + " and Begndate>='" + dpST_3.Value.ToString("yyyy-MM-dd 00:00:00") + "'";
                sqlStr = sqlStr + " and Enddate<='" + dpED_3.Value.ToString("yyyy-MM-dd 23:59:59") + "'";
            }

            if (cbValid_3.SelectedIndex != 0)
            {
                if (cbValid_3.SelectedIndex == 1)
                { sqlStr = sqlStr + " and ValidFlag =1"; }
                else
                    sqlStr = sqlStr + " and ValidFlag =-1";
            }

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

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

        private void btnCancleClearing_Click(object sender, EventArgs e)
        {
            string error = "";
            if (1 == 1)
            {
                if (CancleClearing_Single(out error) != 0)
                {
                    MessageBox.Show("撤销清算失败：" + error);
                }
                else
                {
                    MessageBox.Show("撤销清算成功");
                }
            }
            else
            {
                if (CancleOthPlcClearing_Single(out error) != 0)
                {
                    MessageBox.Show("异地撤销清算失败：" + error);
                }
                else
                {
                    MessageBox.Show("异地撤销清算成功");
                }
            }
        }

        private void btnAddMonth_Click(object sender, EventArgs e)
        {
            dpST_2.Value = dpST_2.Value.AddMonths(1);
            dpED_2.Value = dpST_2.Value.AddDays(1 - dpST_2.Value.Day).AddMonths(1).AddMinutes(-1);
        }

        private void btnReduceMonth_Click(object sender, EventArgs e)
        {
            dpST_2.Value = dpST_2.Value.AddMonths(-1);
            dpED_2.Value = dpST_2.Value.AddDays(1 - dpST_2.Value.Day).AddMonths(1).AddMinutes(-1);
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            string sqlStr = "SELECT * ";

            sqlStr = sqlStr + " FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + Global.inf.interfaceDr;
            sqlStr = sqlStr + " and OccurTime>'" + dpST_O.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED_O.Text + "'";
            sqlStr = sqlStr + " and Interface_dr =1";
            sqlStr = sqlStr + " and (left(InsuranceAreaCode,4)<>'4199' and left(InsuranceAreaCode,4)<>'4101')";

            //if (cbxInsuType.Text != "")
            //{
            //    sqlStr = sqlStr + " and insutype ='" + cbxInsuType.SelectedValue + "'";
            //}

            if (cbxClrType_O.Text != "")
            {
                sqlStr = sqlStr + " and ClearingType ='" + cbxClrType_O.SelectedValue + "'";
            }

            //if (tbSettlOption.Text != "")
            //{
            //    sqlStr = sqlStr + " and ClearingOrgan ='" + tbSettlOption.Text + "'";
            //}

            if (cbxValid_O.SelectedIndex != 0)
            {
                if (cbxValid_O.SelectedIndex == 1)
                { sqlStr = sqlStr + " and ValidFlag =1"; }
                else
                    sqlStr = sqlStr + " and ValidFlag =-1";
            }

            sqlStr = sqlStr + " and ReversalFlag<>1 ";

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

            //DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
            DataTable dt = (DataTable)JsonConvert.DeserializeObject(joRtn["result"]["data"].ToString(), (typeof(DataTable)));
            //DataTable dtResult = new DataTable();
            ////克隆表结构
            //dtResult = dt.Clone();
            //foreach (DataColumn col in dtResult.Columns)
            //{
            //    if (col.ColumnName == "BillID")
            //    {
            //        //修改列类型
            //        col.DataType = typeof(string);
            //    }
            //    if (col.ColumnName == "RecordID")
            //    {
            //        //修改列类型
            //        col.DataType = typeof(string);
            //    }
            //}

            //foreach (DataRow row in dt.Rows)
            //{
            //    DataRow newDtRow = dtResult.NewRow();
            //    foreach (DataColumn column in dt.Columns)
            //    {
            //        if (column.ColumnName == "BillID")
            //        {
            //            MessageBox.Show("cs1:" + column.ColumnName + row[column.ColumnName].ToString());
            //            newDtRow[column.ColumnName] = Convert.ToString(row[column.ColumnName]);
            //        }
            //        else
            //        {
            //            newDtRow[column.ColumnName] = row[column.ColumnName];
            //        }
            //    }
            //    dtResult.Rows.Add(newDtRow);
            //}
            dgvOthCheck.DataSource = dt;
        }

        private void tsmOthPlcCheck_Click(object sender, EventArgs e)
        {
            string error = "";
            if (OthPlcCheck_Single(out error) != 0)
            {
                MessageBox.Show("对账失败：" + error);
            }
            else
            {
                MessageBox.Show("对账成功");
            }
        }

        private void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            dpST_O.Value = dpST_O.Value.AddDays(1);
            dpED_O.Value = dpED_O.Value.AddDays(1);
        }

        private ArrayList getIndexArray(String inputStr, String findStr)
        {
            ArrayList list = new ArrayList();
            int start = 0;

            while (start < inputStr.Length)
            {
                int index = inputStr.IndexOf(findStr, start);

                if (index >= 0)

                {
                    list.Add(index);
                    start = index + findStr.Length;
                }
                else
                {
                    break;
                }
            }

            return list;
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)dgvOthCheck.DataSource;
            string error = "";
            int failRows = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //dgvOthCheck.Rows[i].Selected = true;

                dgvOthCheck.CurrentCell = dgvOthCheck.Rows[i].Cells[0];
                if (OthPlcCheck_Single(out error) != 0)
                {
                    string str = "【当前人员】：";
                    //Graphics g = this.CreateGraphics();
                    //Font font = new Font("宋体", 14, FontStyle.Bold);
                    //SolidBrush brush = new SolidBrush(Color.Red);
                    //g.DrawString(str, font, brush, 20, 50);
                    string patInfo = str + dt.Rows[i]["PatientName"].ToString()
                                   + "，结算编号：" + dt.Rows[i]["SettlementID"].ToString()
                                   + "，清算类别：" + dt.Rows[i]["ClearingType"].ToString()
                                   + "，就诊类别(1门诊2住院)：" + dt.Rows[i]["admType"].ToString();

                    rtbOthCheckResultRecord.AppendText(patInfo + ";对账失败：" + error + "\r\n");
                    failRows++;
                }
                else
                {
                    //rtbOthCheckResultRecord.AppendText("当前人员：" + dt.Rows[i]["PatientName"].ToString() + ";对账成功！"  + "\r\n");
                }
            }
            if (failRows == 0)
            {
                rtbOthCheckResultRecord.AppendText("当前所有人员对账成功！" + "\r\n");
            }
            else
            {
                string str = "【当前人员】";
                ArrayList list = getIndexArray(rtbOthCheckResultRecord.Text, str);

                for (int i = 0; i < list.Count; i++)

                {
                    int index = (int)list[i];

                    rtbOthCheckResultRecord.Select(index, str.Length);
                    rtbOthCheckResultRecord.SelectionColor = Color.Red;

                    Font oldFont = rtbOthCheckResultRecord.SelectionFont;
                    Font font = new Font(oldFont, oldFont.Style | FontStyle.Bold);
                    rtbOthCheckResultRecord.SelectionFont = font;
                }
            }
        }

        private void tsmHandCheck_Click(object sender, EventArgs e)
        {
            JObject joData = JObject.Parse(rtbCheckDetailLog.Text);
            InvokeHelper invoker = new InvokeHelper(); 
            JObject joRtn = invoker.invokeCenterService("3201", JsonHelper.setCenterInpar("3202", joData.ToString()));

        }

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

        private void Btn_Query_Click(object sender, EventArgs e)
        {
            DataTable dtInteface = (DataTable)cbxInterface.DataSource;
            int i = cbxInterface.SelectedIndex;
            //乘以单据类型后，IRIS会返回整数，关键不知道SQL里咋转换为浮点数
            //string sqlStr = "SELECT SUM(BillType*Sumamt) AS medfee_sumamt,count(*) AS fixmedins_setl_cnt,SUM(BillType*PersonCashPay) AS cash_payamt, ";
            //sqlStr = sqlStr + " SUM(BillType*AccountPaySumamt) AS acct_pay,SUM(BillType*FundPaySumamt) AS fund_pay_sumamt ";

            string sqlStr = "SELECT SUM(BillType*Sumamt) AS medfee_sumamt,count(*) AS fixmedins_setl_cnt,SUM(BillType*PersonCashPay) AS cash_payamt,  ";
            sqlStr = sqlStr + " SUM(billType*AccountPaySumamt)+SUM(billType*AccountMutualAidAmount) AS acct_pay,SUM(BillType*FundPaySumamt) AS fund_pay_sumamt ";
            //sqlStr = sqlStr + " Interface_dr,clearingWay AS clr_way,clearingType AS clr_type ";
            string conditionStr = " Group By";
            if (cbgGroupSet.GetItemCheckState(0))
            {
                sqlStr = sqlStr + ",Interface_Dr";
                conditionStr = conditionStr + " Interface_Dr,";
            }
            if (cbgGroupSet.GetItemCheckState(1))
            {
                sqlStr = sqlStr + ",InsuranceType as insutype";
                conditionStr = conditionStr + " InsuranceType,"; 
            }
            if (cbgGroupSet.GetItemCheckState(2))
            {                       
                sqlStr = sqlStr + ",ClearingType as clr_type";
                conditionStr = conditionStr + " ClearingType,";
            }
            if (cbgGroupSet.GetItemCheckState(3))
            {
                sqlStr = sqlStr + ",ClearingOrgan as setl_optins";
                conditionStr = conditionStr + " ClearingOrgan,";
            }
            if (cbgGroupSet.GetItemCheckState(4))
            {
                sqlStr = sqlStr + ",BillType";
                conditionStr = conditionStr + " BillType,";
            }

            sqlStr = sqlStr + " FROM BS_MedInsuSettlement WHERE Hospital_Dr=" + dtInteface.Rows[i]["HospitalDr"].ToString();
            sqlStr = sqlStr + " and OccurTime>'" + dpST.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED.Text + "'";

            if (cbxInterface.Text != "")
            {
                sqlStr = sqlStr + " and Interface_Dr =" + dtInteface.Rows[i]["ID"].ToString();
            }

            if (cbxInsuType.Text != "")
            {
                sqlStr = sqlStr + " and InsuranceType ='" + cbxInsuType.SelectedValue + "'";
            }

            if (cbxClrType.Text != "")
            {
                sqlStr = sqlStr + " and ClearingType ='" + cbxClrType.SelectedValue + "'";
            }

            if (tbSettlOption.Text != "")
            {
                sqlStr = sqlStr + " and ClearingOrgan ='" + tbSettlOption.Text + "'";
            }

            //ValidFlag=1 and BillType=1 表示正常结算记录   ValidFlag=0 and BillType=-1 表示退费记录  ValidFlag=0表示无效记录 
            if (cbxValid.SelectedIndex != 0)
            {
                if (cbxValid.SelectedIndex == 1)
                    sqlStr = sqlStr + " and ValidFlag =1 and BillType=1";
                else
                    sqlStr = sqlStr + " and ValidFlag =0 and BillType=-1";
            }

            if (Global.inf.interfaceDr == 1)
            {
                sqlStr = sqlStr + " and (left(InsuranceAreaCode,4)='6201' or left(InsuranceAreaCode,4)='6299')";
            }

            sqlStr = sqlStr + " and ReversalFlag<>1 ";

            //ZPF 20231204要求包含移动支付结算有效的记录
            //sqlStr = sqlStr + " and BillType<>9 and ((ConfirmFlag = 1 and AdmType IN ('3','4')) OR (AdmType IN ('1','2'))) "; 

            //conditionStr = conditionStr.Substring(0,conditionStr.Length -1 );
            conditionStr = conditionStr.Remove(conditionStr.Length - 1, 1);

            sqlStr = sqlStr + conditionStr;
            JObject joSqlstr = new JObject();

            //MessageBox.Show(sqlStr);

            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010061");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询汇总结算信息");

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

            //初始化HIS结算明细View数据
            dgvHisSettlRec.DataSource = null;

        }

        private void btnBatchCheck_Click(object sender, EventArgs e)
        {

        }

        private void btnPatchClr_Click(object sender, EventArgs e)
        {

        }

        private void cmsClearing_Opening(object sender, CancelEventArgs e)
        {

        }

        private void dgvSettlSummary_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string error;
            if (queryHisSettlementInfo(out error) != 0)
            {
                MessageBox.Show(error);
            }
        }

        private void btnQueryClrSum_Click_1(object sender, EventArgs e)
        {
          

        }
    }
}
