using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.FormSetter;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;


namespace PTMedicalInsurance.Forms
{
    public partial class SettlementBillPrint : Form
    {
        private int hospitalDr;
        private int interfaceDr;
        private string hospitalNO;
        private string interfaceNO;
        private string hospitalName;
        private string hospitalAreaCode;

        private InvokeHelper invoker = new InvokeHelper();

        public SettlementBillPrint()
        {
            InitializeComponent();
            hospitalDr = Global.inf.hospitalDr;
            hospitalNO = Global.inf.hospitalNO;
            hospitalName = Global.inf.hospitalName;
            hospitalAreaCode = Global.inf.areaCode;
            interfaceDr = Global.inf.interfaceDr;
        }

        public SettlementBillPrint(JObject joParam)
        {
            InitializeComponent();
            hospitalDr = Global.inf.hospitalDr;
            hospitalNO = Global.inf.hospitalNO;
            hospitalName = Global.inf.hospitalName;
            hospitalAreaCode = Global.inf.areaCode;

            if (joParam == null) return;

            string setl_id = JsonHelper.getDestValue(joParam, "setl_id");
            Global.pat.insuplc_admdvs = JsonHelper.getDestValue(joParam, "insuplc_admdvs");
            if (setl_id == "")
            {
                MessageBox.Show("根据传入的结算编号为查询到相关信息，请手动输入查询！");
                return;
            }
            string sqlStr = "SELECT * FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + Global.inf.hospitalDr;
            sqlStr = sqlStr + " and SettlementID='" + setl_id + "'";

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            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 SettlementBillPrint_Load(object sender, EventArgs e)
        {
            dpST.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            dpED.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            ComboxSetter cbxSetter = new ComboxSetter();
            cbxSetter.setCbxInterfaceDataSource(cbxInterface);
            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfSettlList(dgvSettlRecord);
            rbgAdmType.SelectedIndex = 0;
            rbgBillType.SelectedIndex = 1;
            //cbxInterface.SelectedValueChanged += new EventHandler(cbxInterface_SelectedValueChanged);
        }

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

            if (i >= 0)
            {
                //赋值
                hospitalNO = dt.Rows[i]["HospitalNO"].ToString();
                //MessageBox.Show(dt.Rows[i]["HospitalDr"].ToString());
                //MessageBox.Show(dt.Rows[i]["HospitalDr"].ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                hospitalDr = int.Parse(dt.Rows[i]["HospitalDr"].ToString());
                interfaceNO = dt.Rows[i]["InterfaceNO"].ToString();
                interfaceDr = int.Parse(dt.Rows[i]["ID"].ToString());
                hospitalAreaCode = dt.Rows[i]["AreaCode"].ToString();
                //Global.inf.centerURL = dt.Rows[i]["CenterURL"].ToString();
                //Global.inf.businessDllName = dt.Rows[i]["DLLName"].ToString();
                //Global.inf.patientAreaCode = dt.Rows[i]["AreaCode"].ToString();    
            }
        }

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

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string sqlStr = " SELECT * FROM  BS_MedInsuSettlement WHERE Hospital_Dr=" + hospitalDr;
            sqlStr = sqlStr + " and OccurTime>'" + dpST.Text + "'";
            sqlStr = sqlStr + " and OccurTime<'" + dpED.Text + "'";
            if (tbName.Text != "")
            {
                sqlStr = sqlStr + " and PatientName='" + tbName.Text + "'";
            }
            if (tbPatSettlID.Text != "")
            {
                sqlStr = sqlStr + " and SettlementID='" + tbPatSettlID.Text + "'";
            }
            if (tbHisNO.Text != "")
            {
                sqlStr = sqlStr + " and Adm_Dr='" + tbHisNO.Text + "'";
            }
            if (cbxInterface.Text != "")
            {
                sqlStr = sqlStr + " and Interface_Dr=" + Global.inf.interfaceDr + "";
            }
            if (rbgAdmType.SelectedIndex == 1)
            {
                sqlStr = sqlStr + " and AdmType=2";
            }
            if (rbgAdmType.SelectedIndex == 2)
            {
                sqlStr = sqlStr + " and AdmType=1";
            }
            if (rbgBillType.SelectedIndex == 1)
            {
                sqlStr = sqlStr + " and BillType=1 and ValidFlag=1 ";
            }
            if (rbgBillType.SelectedIndex == 2)
            {
                sqlStr = sqlStr + " and BillType=-1 and ValidFlag=0 ";
            }

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

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

        public void btnPrint_Click(object sender, EventArgs e)
        {
            string errorMsg, outParam, FunNo = "", FunDesc = "";

            if (dgvSettlRecord.RowCount <= 0)
            {
                MessageBox.Show("请先查询结算数据!");
                return;
            }
            
            try
            {
                int i = dgvSettlRecord.CurrentRow.Index;
                DataTable dt = (DataTable)dgvSettlRecord.DataSource;

                string AdmType = dt.Rows[i]["admType"].ToString();
                string SettlementID = dt.Rows[i]["SettlementID"].ToString();
                string PatientName = dt.Rows[i]["PatientName"].ToString();
                string PersonnelNO = dt.Rows[i]["PersonnelNO"].ToString();

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

                if (AdmType == "1")
                {
                    FunNo = "5601_A"; //人员门诊支付结算打印
                    FunDesc = "人员门诊支付结算打印";
                }
                else if (AdmType == "2")
                {
                    FunNo = "5602_A"; //人员住院支付结算打印
                    FunDesc = "人员住院支付结算打印";
                }

                JObject joData = new JObject();
                joData.Add("mdtrt_cert_type", "");
                joData.Add("mdtrt_cert_no", "");
                joData.Add("card_sn", "");
                joData.Add("psn_cert_type", "");
                joData.Add("certno", "");
                joData.Add("psn_name", PatientName);
                joData.Add("setl_id", SettlementID);
                joData.Add("begndate", "");
                joData.Add("enddate", "");
                joData.Add("name", PatientName);
                joData.Add("psn_no", PersonnelNO);

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

                JObject joRtn = invoker.invokeCenterService(FunNo, JsonHelper.setCenterInpar(FunNo, joInput));
                if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-1, FunDesc + "失败！", errorMsg).ToString();
                    return;
                }
                else
                {
                    //MessageBox.Show("结算单下载成功！存放路径：" + errorMsg); 

                    //打开pdf文件(激活默认打开pdf的浏览器)
                    Process.Start(errorMsg);                     
                }    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }     
      
        /// <summary>
        /// 【5204】费用明细查询更新医保费用上传记录表
        /// </summary>
        /// <returns></returns>
        public JObject UpdateMedInsuUploadData(string AdmID, string psnNo, string MdtrtID, string SettlementID)
        {
            string errorMsg, outParam;

            if (AdmID == "")
            {
                return JObject.Parse(JsonHelper.setExceptionJson(-1, "", "AdmID不能为空！").ToString());
            }

            if (psnNo == "")
            {
                return JObject.Parse(JsonHelper.setExceptionJson(-1, "", "psnNo不能为空！").ToString());
            }

            if (MdtrtID == "")
            {
                return JObject.Parse(JsonHelper.setExceptionJson(-1, "", "MdtrtID不能为空！").ToString());
            }

            if (SettlementID == "")
            {
                return JObject.Parse(JsonHelper.setExceptionJson(-1, "", "settlementID不能为空！").ToString());
            }

            if (Global.inf.hospitalDr.ToString() == "")
            {                
                return JObject.Parse(JsonHelper.setExceptionJson(-1, "", "hospitalDr不能为空！").ToString());
            }

            try
            {
                #region【5204】费用明细查询
                JObject joData = new JObject();
                joData.Add("psn_no", psnNo);
                joData.Add("setl_id", SettlementID);
                joData.Add("mdtrt_id", MdtrtID);
                JObject joInput = new JObject();
                joInput.Add("data", joData);

                JObject joRtn5204 = invoker.invokeCenterService("5204", JsonHelper.setCenterInpar("5204", joInput));
                if (JsonHelper.parseCenterRtnValue(joRtn5204, out errorMsg) != 0)
                {                    
                    outParam = JsonHelper.setExceptionJson(-1, "【5204】费用明细查询失败！", errorMsg).ToString();
                    return JObject.Parse(outParam);                    
                }
                #endregion

                JArray jaRtn5204 = JArray.Parse(JsonHelper.getDestValue(joRtn5204, "output"));

                if (jaRtn5204.Count <= 0)                                
                {
                    return JObject.Parse(JsonHelper.setExceptionJson(-1, "", "【5204】医保费用明细查询返回结果为空！").ToString());
                }

                dynamic joTmp = new JObject();
                joTmp.code = "09010090";
                JArray jaParams = jaRtn5204;
                joTmp.Add("params", jaParams);
                joTmp.HospitalDr = Global.inf.hospitalDr;
                joTmp.InterfaceDr = Global.inf.interfaceDr; //如果是通用目录就更新通用目录 
                joTmp.admID = AdmID;
                joTmp.mdtrt_id = MdtrtID;
                joTmp.psn_no = psnNo;
                joTmp.updateUserID = Global.user.ID;
                JObject joRtn = invoker.invokeInsuService(joTmp.ToString(), "更新医保费用上传明细表");
                if (JsonHelper.parseIrisRtnValue(joRtn, out errorMsg) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-1, "更新医保费用上传明细表失败！", errorMsg).ToString();
                    return JObject.Parse(outParam);
                }
                else
                {
                    return joRtn;
                }
            }
            catch (Exception ex)
            {
                JObject joRtnEx = new JObject();
                joRtnEx.Add("errorCode", -1);
                joRtnEx.Add("errorMessage", ex.Message);
                return joRtnEx;
            }
        }


        private JObject getPatCheckList()
        {
            try
            {
                int i = dgvSettlRecord.CurrentRow.Index;
                DataTable dt = (DataTable)dgvSettlRecord.DataSource;
                JObject joSettel = new JObject();
                joSettel.Add("HospitalDr", Global.inf.hospitalDr);
                joSettel.Add("interfaceDr", Global.inf.interfaceDr);
                joSettel.Add("admID", dt.Rows[i]["AdmID"].ToString());
                joSettel.Add("SettlementID", dt.Rows[i]["SettlementID"].ToString());
                joSettel.Add("ValidFlag", dt.Rows[i]["ValidFlag"].ToString());

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

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

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

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

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

            #region【5204】1.医保费用明细查询  2.更新医保平台费用上传明细表                    
            JObject joRtnFee = UpdateMedInsuUploadData(AdmID, PsnNo, MdtrtID, SettlementID);
            if (JsonHelper.parseIrisRtnValue(joRtnFee, out errorMsg) != 0)
            {
                MessageBox.Show("更新医保费用明细表失败：" + errorMsg);
                return;
            }
            else
            {
                MessageBox.Show("更新医保费用明细表成功");
            }
            #endregion
        }

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

            if (dgvSettlRecord.Rows[dgvSettlRecord.CurrentRow.Index].Cells["CommercialRenFlag"].Value.ToString() == "1")
                btnPrintComRe.Enabled = true;
            else
                btnPrintComRe.Enabled = false;                    
        }

        private void btnPrintComRe_Click(object sender, EventArgs e)
        {
            string errorMsg, outParam, FunNo = "", FunDesc = "";

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

            if (dgvSettlRecord.Rows[dgvSettlRecord.CurrentRow.Index].Cells["CommercialRenFlag"].Value.ToString() != "1")
            {
                MessageBox.Show("该笔医保结算记录不含商保支付，无需打印!");
                return;
            }

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

                string AdmType = dt.Rows[i]["admType"].ToString();
                string SettlementID = dt.Rows[i]["SettlementID"].ToString();
                string PatientName = dt.Rows[i]["PatientName"].ToString();
                string PersonnelNO = dt.Rows[i]["PersonnelNO"].ToString();

                if (AdmType == "1")
                {
                    FunNo = "5601_B"; //人员门诊支付结算打印
                    FunDesc = "人员门诊支付结算打印";
                }
                else if (AdmType == "2")
                {
                    FunNo = "5602_B"; //人员住院支付结算打印
                    FunDesc = "人员住院支付结算打印";
                }

                JObject joData = new JObject();
                joData.Add("mdtrt_cert_type", "");
                joData.Add("mdtrt_cert_no", "");
                joData.Add("card_sn", "");
                joData.Add("psn_cert_type", "");
                joData.Add("certno", "");
                joData.Add("psn_name", PatientName);
                joData.Add("setl_id", SettlementID);
                joData.Add("begndate", "");
                joData.Add("enddate", "");
                joData.Add("name", PatientName);
                joData.Add("psn_no", PersonnelNO);

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

                JObject joRtn = invoker.invokeCenterService(FunNo, JsonHelper.setCenterInpar(FunNo, joInput));
                if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-1, FunDesc + "失败！", errorMsg).ToString();
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
    }
}
