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

        //1.声明自适应类实例
        AutoResizeForm asc = new AutoResizeForm();

        public HandleException()
        {
            InitializeComponent();

            //this.StartPosition = FormStartPosition.CenterParent;
            asc.controllInitializeSize(this);
            asc.controlAutoSize(this);
        }

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

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

            dgvSettlRecord.AutoGenerateColumns = false;

            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfSettlList(dgvSettlRecord);
            grdSetter.SetHeaderTextOfCenterLog(dgvLog);
            grdSetter.SetHeaderTextOfRegister(dgvOutPatReg);
            grdSetter.SetHeaderTextOfSign(dgvSignQuery);

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

        }
        #region  结算异常
        private void btnQuerySettleRec_Click(object sender, EventArgs e)
        {
            if (tbName.Text == "")
            {
                MessageBox.Show("请输入患者姓名！");
                return;
            }
            string sqlStr = "SELECT * FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            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 (rbgAdmType.SelectedIndex == 1)
            {
                sqlStr = sqlStr + " and admType=1";
            }
            if (rbgAdmType.SelectedIndex == 2)
            {
                sqlStr = sqlStr + " and admType=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 btnReverseBySettl_Click(object sender, EventArgs e)
        {
            //InvokeHelper invoker = new InvokeHelper();

            DataTable dt = (DataTable)dgvSettlRecord.DataSource;
            string errorMessage = "";
            int a = dgvSettlRecord.CurrentRow.Index;
            //Global.inf.patientAreaCode = dt.Rows[a]["insuplc_admdvs"].ToString();
            Global.pat.insuplc_admdvs = dt.Rows[a]["insuplc_admdvs"].ToString();
            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();

            MessageBox.Show(setl_id);
            
            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]["admType"].ToString() == "1") infno = "2207";
            if (dt.Rows[a]["admType"].ToString() == "2") infno = "2304";
            joData.Add("oinfno", infno);

            JObject joInparam = new JObject();
            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 btCancleSettl_Click(object sender, EventArgs e)
        {
            string outParam;
            DataTable dt = (DataTable)dgvSettlRecord.DataSource;
            int a = dgvSettlRecord.CurrentRow.Index;
            //Global.inf.patientAreaCode = dt.Rows[a]["insuplc_admdvs"].ToString()
            MessageBox.Show("111");
            Global.pat.insuplc_admdvs = dt.Rows[a]["insuplc_admdvs"].ToString();
            MessageBox.Show(dt.Rows[a]["insuplc_admdvs"].ToString());
            MessageBox.Show(Global.pat.insuplc_admdvs);
            Global.pat.mdtrtID = dt.Rows[a]["MdtrtID"].ToString(); 
            Global.pat.psn_no = dt.Rows[a]["PersonnelNO"].ToString();
            Global.pat.settlID = dt.Rows[a]["SettlementID"].ToString();
            Global.pat.adm_Dr = int.Parse(dt.Rows[a]["AdmID"].ToString()); 
            //取消中心结算信息
            if (cBus.cancleSettlement("2305", out outParam) != 0)
            {
                MessageBox.Show( "取消中心结算信息失败！" + outParam);
                return;
            }
            else
            {
                //取消平台结算信息
                //if (mIS.cancleSettlement(out outParam) != 0)
                if (cBus.cancleSettlement("2305", out outParam) != 0)
                {
                    MessageBox.Show("中心结算取消成功，医保平台结算信息取消失败！" + outParam);
                    return ;
                }

                //取消出院登记
                if (cBus.cancleRegister("2405", out outParam) != 0)
                {
                    MessageBox.Show("中心，医保平台及HIS结算信息取消成功，取消出院登记失败！请手工取消出院登记！" +  outParam);
                    return ;
                }
            }
        }
        #endregion

        #region  日志异常

        private void btnQueryLog_Click(object sender, EventArgs e)
        {
            string errMsg;
            string sqlStr = "SELECT * FROM  BS_MedInsuTransactionLog WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            sqlStr = sqlStr + " and InfDate>='" + dpST_Log.Value.ToString("yyyy-MM-dd") + "'";
            sqlStr = sqlStr + " and InfDate<='" + dpED_Log.Value.ToString("yyyy-MM-dd") + "'";
            if (tbPsnNO.Text != "")
            {
                sqlStr = sqlStr + " and PSNNO='" + tbPsnNO.Text + "'";
            }

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


            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            JObject joRtn = mIS.QueryTransactionLog(joSqlstr);
            //if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
            //{
            //    MessageBox.Show(errMsg);
            //    return;
            //}

            try
            {
                DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
                dgvLog.DataSource = dt;
            }
            catch (Exception eX)
            {
                MessageBox.Show(eX.Message);
            }
        }
        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);
            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("冲正成功");
            }
        }

        #endregion

        #region  手工
        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 = "";
            JObject joRtn = new JObject();
            Global.pat.insuplc_admdvs = tbCBD_Hand.Text;
            if (Chk_DealNo.Checked)
            {
                joRtn = invoker.invokeCenterService(tb_DealNo.Text, JsonHelper.setCenterInpar(tb_DealNo.Text, rtbInparam.Text));
            }
            else
            {
                joRtn = invoker.invokeCenterService("2601", JsonHelper.setCenterInpar("2601", rtbInparam.Text));
            }
            if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
            {
                MessageBox.Show("调用失败：" + errorMsg);
            }
            else
            {
                MessageBox.Show("调用成功！：");
            }
        }

        #endregion

        #region  门诊登记
        private void btnQueryOutPatReg_Click(object sender, EventArgs e)
        {
            
            string sqlStr = "SELECT * FROM  BS_MedInsuRegisterInfo WHERE Type=3 and Hospital_Dr=" + Global.inf.hospitalDr;
            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 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 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;
            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("取消门诊费用失败");
            }
        }


        #endregion

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

        private void btnSignQuery_Click(object sender, EventArgs e)
        {
            string sqlStr = "SELECT Top 50 * FROM  HB_MedInsuSignRecord WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            sqlStr = sqlStr + " and Interface_Dr=" + Global.inf.interfaceDr;
            sqlStr = sqlStr + " and CreateTime>'" + dtSignBegin.Text + "'";
            sqlStr = sqlStr + " and CreateTime<'" + dtSignEnd.Text + "'";
            if (edtSignNo.Text != "")
            {
                sqlStr = sqlStr + " and SignNo='" + edtSignNo.Text + "'";
            }

            if (edtSignOpterNo.Text != "")
            {
                sqlStr = sqlStr + " and OperatorNO='" + edtSignOpterNo.Text + "'";
            }

            if (edtOpterName.Text != "")
            {
                sqlStr = sqlStr + " and OperatorName='" + edtOpterName.Text + "'";
            }

            sqlStr = sqlStr + " Order By CreateTime DESC ";

            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", "09010064");
            joSettlQuery.Add("queryType", "All");
            InvokeHelper invoker = new InvokeHelper();
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询签到信息");

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

        private void btnCancelSign_Click(object sender, EventArgs e)
        {
            InvokeHelper invoker = new InvokeHelper();
            DataTable dt = (DataTable)dgvSignQuery.DataSource;
            string errorMessage = "";
            int a = dgvSignQuery.CurrentRow.Index;

            if (a <0)
            {
                MessageBox.Show("请先选中需要签退的签到记录信息！");
                return;            
            }

            //组织签退入参
            JObject joCancleRegInpar = new JObject();
            joCancleRegInpar.Add("sign_no", dt.Rows[a]["SignNo"].ToString());
            joCancleRegInpar.Add("opter_no", dt.Rows[a]["OperatorNO"].ToString());

            JObject joRegInput = new JObject();
            joRegInput.Add("signOut", joCancleRegInpar);
            //取消挂号信息
            JObject jo9002Rtn = invoker.invokeCenterService("9002", JsonHelper.setCenterInpar("9002", joRegInput.ToString()));
            if (JsonHelper.parseCenterRtnValue(jo9002Rtn, out errorMessage) != 0)
            {
                MessageBox.Show("医保签退失败" + errorMessage);
            }
            else
            {
                MessageBox.Show("医保签退成功");
            }
        }

        private void Chk_DealNo_ValueChanged(object sender, bool value)
        {
            if (Chk_DealNo.Checked)
                tb_DealNo.Visible = true;
            else
                tb_DealNo.Visible = false;
        }
    }
}
