using Newtonsoft.Json.Linq;
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 PTMedicalInsurance.FormSetter;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.Variables;
using FastReport;

namespace PTMedicalInsurance.Forms
{
    public partial class HandleException : Form
    {
        private DataTable dtLog;
        private DataTable dtSettl;
        private DataTable dtReg;
        private int iLog = 0;
        private int iSettl = 0;
        private int iReg = 0;


        //设置业务实例
        CenterBusiness cBus = new CenterBusiness();
        HisMainBusiness hBus = new HisMainBusiness();
        HisIrisServices hIS = new HisIrisServices();
        MIIrisServices mIS = new MIIrisServices();
        InvokeHelper invoker = new InvokeHelper();
        public HandleException()
        {
            InitializeComponent();

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            
          

            
        }

        private void btnReverse_Click(object sender, EventArgs e)
        {
            
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            string sqlStr = "SELECT * FROM  MedInsu_Tables.Settlement WHERE Hosp_Dr=" + Global.inf.hospitalDr;
            sqlStr = sqlStr + " and OccurTime>'" + dpST_Log.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED_Log.Text + "'";

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

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

        private void btnReverseSettlRec_Click(object sender, EventArgs e)
        {
            string infno = "";
            
            InvokeHelper invoker = new InvokeHelper();
            DataTable dt = (DataTable)dgvLog.DataSource;
            JObject joInparam = new JObject();
            JObject joData = new JObject();
            int a = dgvLog.CurrentRow.Index;
            joData.Add("omsgid", dt.Rows[a]["msgid"].ToString());
            joData.Add("psn_no", dt.Rows[a]["PersonnelNO"].ToString());
            if (dt.Rows[a]["admType"].ToString() == "1")
            {
                infno = "2207";
            }

            if (dt.Rows[a]["admType"].ToString() == "2")
            {
                infno = "2304";
            }
            joData.Add("oinfno", infno);
            joInparam.Add("data", joData);
            JObject joRtn = invoker.invokeCenterService("2601",JsonHelper.setCenterInpar("2601", joInparam.ToString()));
        }

        private void btnQuerySettlRec_Click(object sender, EventArgs e)
        {

        }

        private void btnQuerySettleRec_Click(object sender, EventArgs e)
        {
            if (tbName.Text == "")
            {
                MessageBox.Show("请输入患者姓名！");
                return;
            }
            string sqlStr = "SELECT * FROM  MedInsu_Tables.Settlement WHERE Hosp_Dr=" + dtSettl.Rows[iSettl]["HospitalDr"].ToString();
            sqlStr = sqlStr + " and OccurTime>'" + dpST_Settl.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED_Settl.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=" + GlobalVariables.interfaceDr + "";
            //}

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

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

            if (rbgBillType.SelectedIndex == 2)
            {
                sqlStr = sqlStr + " and BillType=-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));
            dgvSettlRecord.DataSource = dt;
        }

        private void HandleException_Load(object sender, EventArgs e)
        {
            dpST_Log.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dpED_Log.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            dpST_Settl.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dpED_Settl.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            dpST_OutPatReg.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dpED_OutPatReg.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            dgvSettlRecord.AutoGenerateColumns = false;


            ComboxSetter cbxSetter = new ComboxSetter();
            cbxSetter.setCbxInterfaceDataSource(cbxInterface_Log);
            cbxSetter.setCbxInterfaceDataSource(cbxInterface_settl);
            cbxSetter.setCbxInterfaceDataSource(cbxInterface_OutPatReg);
            dtLog =(DataTable)cbxInterface_Log.DataSource;
            dtReg = (DataTable)cbxInterface_OutPatReg.DataSource;
            dtSettl = (DataTable)cbxInterface_settl.DataSource;

            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfSettlList(dgvSettlRecord);
            grdSetter.SetHeaderTextOfCenterLog(dgvLog);
            grdSetter.SetHeaderTextOfRegister(dgvOutPatReg);
            rbgAdmType.SelectedIndex = 0;
            rbgBillType.SelectedIndex = 1;


            cbxInterface_settl.SelectedValueChanged += new EventHandler(cbxInterface_settl_SelectedValueChanged);
            cbxInterface_OutPatReg.SelectedValueChanged += new EventHandler(cbxInterface_OutPatReg_SelectedValueChanged);
            cbxInterface_Log.SelectedValueChanged += new EventHandler(cbxInterface_Log_SelectedValueChanged);
        }

        private void cbxInterface_settl_SelectedValueChanged(object sender, EventArgs e)
        {
            dtSettl = (DataTable)cbxInterface_settl.DataSource;
            iSettl = cbxInterface_settl.SelectedIndex;

        }

        private void btnReverseBySettl_Click(object sender, EventArgs e)
        {

            MessageBox.Show("1111");
            InvokeHelper invoker = new InvokeHelper();

            DataTable dt = (DataTable)dgvSettlRecord.DataSource;
            string errorMessage = "";
            int a = dgvOutPatReg.CurrentRow.Index;
            //GlobalVariables.patientAreaCode = dt.Rows[a]["insuplc_admdvs"].ToString();
            Global.pat.insuplc_admdvs = "510106";
            string mdtrt_id = dt.Rows[a]["MdtrtID"].ToString();
            string psn_no = dt.Rows[a]["PersonnelNO"].ToString();
            string adm_Dr = dt.Rows[a]["AdmID"].ToString();
            string setl_id = dt.Rows[a]["SettlementID"].ToString();
            JObject joInparam = new JObject();
            JObject joData = new JObject();
            joData.Add("omsgid", dt.Rows[a]["msgid"].ToString());
            joData.Add("psn_no", dt.Rows[a]["PersonnelNO"].ToString());
            string infno = "";
            if (dt.Rows[a]["infno"].ToString() == "1") infno = "2207A";
            if (dt.Rows[a]["infno"].ToString() == "2") infno = "2304";
            joData.Add("oinfno", infno);
            joInparam.Add("data", joData);
            MessageBox.Show(joInparam.ToString());
            JObject joRtn = invoker.invokeCenterService("2601",JsonHelper.setCenterInpar("2601", joInparam.ToString()));
            //将中心返回的结果返回HIS 调用HIS服务进行保存
            if (JsonHelper.parseIrisRtnValue(joRtn, out errorMessage) != 0)
            {
                MessageBox.Show("冲正失败:" + errorMessage);
            }
            else
            {
                dynamic joTmp = new JObject();
                joTmp.admID = adm_Dr;
                joTmp.PersonalNO = psn_no;
                joTmp.mdtrt_id = mdtrt_id;
                joTmp.setl_id = setl_id;

                //JObject jo2305IrisRtn = mIS.cancleSettlement(joTmp);
                JObject jo2305IrisRtn = new JObject();
                if (JsonHelper.parseIrisRtnValue(jo2305IrisRtn, out errorMessage) != 0)
                {
                    errorMessage = "中心取消结算成功但云HIS平台取消失败，请联系管理员！" + errorMessage;
                    MessageBox.Show(errorMessage);
                }
            }
            }

        private void btnQueryLog_Click(object sender, EventArgs e)
        {
            string sqlStr = "SELECT * FROM  MedInsu_Tables.TransactionLog WHERE Hosp_Dr=" + dtLog.Rows[iLog]["HospitalDr"].ToString();
            sqlStr = sqlStr + " and inf_time>'" + dpST_Log.Text + "'";
            sqlStr = sqlStr + " and inf_time<'" + dpED_Log.Text + "'";
            if (tbPsnNO.Text != "")
            {
                sqlStr = sqlStr + " and psn_no='" + tbPsnNO.Text + "'";
            }

            if (tbTransNO.Text != "")
            {
                sqlStr = sqlStr + " and infno='" + tbTransNO.Text + "'";
            }


            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010060");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询交易日志（冲正）");

            try
            {
                DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
                dgvLog.DataSource = dt;
            }
            catch (Exception eX)
            {
                MessageBox.Show(eX.Message);
            }
        }

        private void gbInterface_Click(object sender, EventArgs e)
        {

        }

        private void btnReverseByLog_Click(object sender, EventArgs e)
        {
            
            InvokeHelper invoker = new InvokeHelper();
            DataTable dt = (DataTable)dgvLog.DataSource;
            JObject joInparam = new JObject();
            JObject joData = new JObject();
            int a = dgvLog.CurrentRow.Index;
            if (tbCBD_Log.Text != "")
            { Global.pat.insuplc_admdvs = tbCBD_Log.Text; }
            else
                Global.pat.insuplc_admdvs = dt.Rows[a]["insuplc_admdvs"].ToString();
            joData.Add("omsgid", dt.Rows[a]["msgid"].ToString());
            joData.Add("psn_no", dt.Rows[a]["psn_no"].ToString());
            joData.Add("oinfno", dt.Rows[a]["infno"].ToString());
            //joData.Add("oinfno", "2207");
            joInparam.Add("data", joData);
            MessageBox.Show(joInparam.ToString());
            JObject joRtn = invoker.invokeCenterService("2601",JsonHelper.setCenterInpar("2601", joInparam.ToString()));
            string errorMessage = "";
            if (JsonHelper.parseCenterRtnValue(joRtn, out errorMessage) != 0)
            {
                MessageBox.Show("冲正失败" + errorMessage);
            }
            else
            {
                MessageBox.Show("冲正成功" );
            }
        }

        private void btPatInfo_ex_Click(object sender, EventArgs e)
        {
            rtbInparam.Text = @"{""data"":{""omsgid"":""H51010604235202205280848088230"",""psn_no"":""1530541881"",""oinfno"":""2201""}}";
            JObject joTmp = JObject.Parse(rtbInparam.Text);
            rtbInparam.Text = joTmp.ToString();
        }

        private void btnPatInfoShow_Click(object sender, EventArgs e)
        {
            string errorMsg = "";
            Global.pat.insuplc_admdvs = tbCBD_Hand.Text;
            JObject joRtn = invoker.invokeCenterService("2601",JsonHelper.setCenterInpar("2601", rtbInparam.Text));
            if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
            {
                MessageBox.Show("冲正失败：" + errorMsg);
            }
            else
            {
                MessageBox.Show("冲正成功！：" );
            }

        }

        private void btnQueryOutPatReg_Click(object sender, EventArgs e)
        {
            
            string sqlStr = "SELECT * FROM  MedInsu_Tables.RegisterInfo WHERE Type=3 and Hosp_Dr=" + dtReg.Rows[iReg]["HospitalDr"].ToString();
            sqlStr = sqlStr + " and OccurTime>'" + dpST_OutPatReg.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED_OutPatReg.Text + "'";
            if (tbOutPatName.Text != "")
            {
                sqlStr = sqlStr + " and Pat_Name='" + tbOutPatName.Text + "'";
            }

            if (tbOutPatRegID.Text != "")
            {
                sqlStr = sqlStr + " and InsuRegID='" + tbOutPatRegID.Text + "'";
            }

            if (tbOutPatPsnNO.Text != "")
            {
                sqlStr = sqlStr + " and PersonalNO='" + tbOutPatPsnNO.Text + "'";
            }


            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JArray jaParam = new JArray();
            jaParam.Add(joSqlstr);
            JObject joSettlQuery = new JObject();
            joSettlQuery.Add("params", jaParam);
            joSettlQuery.Add("code", "09010062");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询门诊挂号");

            try
            {
                DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
                dgvOutPatReg.DataSource = dt;
            }
            catch (Exception eX)
            {
                MessageBox.Show(eX.Message);
            }
        }

        private void cbxInterface_OutPatReg_SelectedValueChanged(object sender, EventArgs e)
        {
            dtReg = (DataTable)cbxInterface_OutPatReg.DataSource;
            iReg = cbxInterface_OutPatReg.SelectedIndex;
        }

        private void btnCancleOutPatReg_Click(object sender, EventArgs e)
        {
            InvokeHelper invoker = new InvokeHelper();
            DataTable dt = (DataTable)dgvOutPatReg.DataSource;
            string errorMessage = "";
            int a = dgvOutPatReg.CurrentRow.Index;
            //组织挂号入参
            JObject joCancleRegInpar = new JObject();
            Global.pat.insuplc_admdvs = dt.Rows[a]["insuplc_admdvs"].ToString();
            joCancleRegInpar.Add("psn_no", dt.Rows[a]["PersonalNO"].ToString());
            joCancleRegInpar.Add("mdtrt_id", dt.Rows[a]["InsuRegID"].ToString());
            joCancleRegInpar.Add("ipt_otp_no", dt.Rows[a]["AdmID"].ToString());

            JObject joRegInput = new JObject();
            joRegInput.Add("data", joCancleRegInpar);
            //取消挂号信息
            JObject jo2202Rtn = invoker.invokeCenterService("2202",JsonHelper.setCenterInpar("2202", joRegInput.ToString()));
            if (JsonHelper.parseCenterRtnValue(jo2202Rtn, out errorMessage) != 0)
            {
                MessageBox.Show("取消挂号失败" + errorMessage);
            }
            else
            {
                dynamic joTmp = new JObject();
                joTmp.admID = dt.Rows[a]["AdmID"].ToString();
                joTmp.PersonalNO = dt.Rows[a]["PersonalNO"].ToString();
                joTmp.InsuRegID = dt.Rows[a]["InsuRegID"].ToString();
                joTmp.Add("billID", "");
                joTmp.Type = 3;
                joTmp.CancleRegDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                JObject jo2404IrisRtn = hIS.cancleRegister(joTmp);
                if (JsonHelper.parseIrisRtnValue(jo2404IrisRtn, out errorMessage) != 0)
                {
                    MessageBox.Show(errorMessage);
                }
                else
                {
                    MessageBox.Show("取消挂号成功");
                }
            }
        }

        private void cbxInterface_Log_SelectedValueChanged(object sender, EventArgs e)
        {
            dtLog = (DataTable)cbxInterface_Log.DataSource;
            iLog = cbxInterface_Log.SelectedIndex;

            //赋值
            //hospitalNO = dt.Rows[i]["HospitalNO"].ToString();
            //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();
        }

        private void btnCancleOutPatFee_Click(object sender, EventArgs e)
        {

            InvokeHelper invoker = new InvokeHelper();
            DataTable dt = (DataTable)dgvOutPatReg.DataSource;
            string errorMessage = "";
            int a = dgvOutPatReg.CurrentRow.Index;
            Global.pat.insuplc_admdvs = dt.Rows[a]["insuplc_admdvs"].ToString();
            string mdtrt_id = dt.Rows[a]["InsuRegID"].ToString();
            string psn_no = dt.Rows[a]["PersonalNO"].ToString();
            string adm_Dr = dt.Rows[a]["AdmID"].ToString(); 
            //组织入参
            dynamic joTmp = new JObject();
            joTmp.chrg_bchno = "0000";
            joTmp.mdtrt_id = mdtrt_id;
            joTmp.psn_no = psn_no;
            joTmp.expContent = "";
            JObject joData = new JObject();
            joData.Add("data", joTmp);

            //组织好后上传给中心
            JObject joCenterRtn = invoker.invokeCenterService("2205",JsonHelper.setCenterInpar("2205", joData.ToString()));
            if (joCenterRtn["infcode"].ToString() == "0")
            {

                //删除医保传送表的数据
                joTmp = new JObject();
                joTmp.code = "09010048";
                joTmp.HospitalDr = Global.inf.hospitalDr;
                joTmp.admID = adm_Dr;
                joTmp.mdtrt_id = mdtrt_id;
                joTmp.updateUserID = Global.user.ID;
                JObject joIris2301DeleteRtn = invoker.invokeInsuService(joTmp.ToString(), "删除门诊明细");
                if (JsonHelper.parseCenterRtnValue(joIris2301DeleteRtn, out errorMessage) != 0)
                {
                    MessageBox.Show("取消门诊费用失败" + errorMessage);
                }
                else
                {
                    MessageBox.Show("取消门诊费用成功");
                }
            }
            else
            {
                MessageBox.Show("取消门诊费用失败" );
            }
        }

        private void uiButton1_Click_1(object sender, EventArgs e)
        {
            Report report1 = new Report();
            //report.RegisterData(json.result.data.classification, "classification");
            //report.RegisterData(json.result.data.settlement, "settlement");
            report1.Load(Global.curEvt.path + "\\frx\\Test.frx");
            report1.Design();
        }
    }
}
