using Newtonsoft.Json.Linq;
using System;
using System.IO;
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;



namespace PTMedicalInsurance.Forms
{
    public partial class MedInsuQuery : Form
    {
        DataTable dtExport;

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

        public MedInsuQuery()
        {
            InitializeComponent();

            asc.controllInitializeSize(this);
            asc.controlAutoSize(this);
        }

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

        private void MedInsuQuery_Load(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Maximized;

            tbcMain.SelectedIndex = 1;

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

            dt_ST.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_ET.Text = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            // dgvSettlRecord.AutoGenerateColumns = false;
            cbbLevel.SelectedIndex = 0;
            cbbOverPrice.SelectedIndex = 0;

            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfMedInsuHosPerInfo(dgvSettlRecord);
            grdSetter.SetHeaderTextOfSettltMentFeelDetailInfo(dgvInsuFeeUpload);
            grdSetter.DatagridviewColumnWidthAdaptation(dgvInsuFeeUpload);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            btnPrint.Enabled = false;
            string sCZYXM = Global.user.name;

            string SqlHeard = " Adm_Dr,MdtrtID,Name as PatientName,Age,PsnCertNO,Gend,PsnType,EmpName,AdmInDepName,insuplcAdmdvs,sZYZT AS sZTSM, "
                            + " AdmBed,RegDate,MainDiagName,AttendDoctorNO,ChiefPhyDocName,'"+ sCZYXM+ "' as OpertName,'' as InHospNo,''Address ";                           

            string SqlStrMain = " SELECT a.*,b.*,a.PatientName AS Name,a.PsnType AS PsnTypeCode,'在院' sZYZT FROM BS_MIPatCurrentInsuInfo a LEFT JOIN BS_MedInsuRegisterInfo b "
                              + " ON a.MdtrtID=b.InsuRegID AND a.Interface_Dr=b.Interface_Dr AND a.Hospital_Dr=b.Hospital_Dr "
                              + " WHERE b.Type=1 AND b.ValidFlag=1 AND b.Hospital_Dr= " + Global.inf.hospitalDr + " AND b.Interface_Dr= " + Global.inf.interfaceDr
                              + " AND b.InsuRegID NOT IN (SELECT MdtrtID FROM BS_MedInsuSettlement WHERE MdtrtID=b.InsuRegID AND BillType=1 AND ValidFlag=1 AND AdmType=2) "
                              + " AND b.RegDate<='" + dpED.Text + "' AND b.RegDate>'" + dpST.Text + "' "  //
                              + " UNION ALL "
                              + " SELECT a.*,b.*,a.PatientName AS Name,a.PsnType AS PsnTypeCode,'已结算' AS sZYZT "
                              + " FROM BS_MIPatCurrentInsuInfo a LEFT JOIN BS_MedInsuRegisterInfo b "
                              + " ON a.MdtrtID=b.InsuRegID AND a.Interface_Dr=b.Interface_Dr AND a.Hospital_Dr=b.Hospital_Dr "
                              + " LEFT JOIN BS_MedInsuSettlement c ON a.MdtrtID=b.InsuRegID AND b.InsuRegID=c.MdtrtID AND a.Interface_Dr=b.Interface_Dr AND b.Interface_Dr=c.Interface_Dr "
                              + " WHERE b.Type=1 AND b.ValidFlag=1 AND c.BillType=1 AND b.Hospital_Dr= " + Global.inf.hospitalDr + " AND b.Interface_Dr= " + Global.inf.interfaceDr                    
                              + " AND c.AdmType=2 AND c.SettlementDateTime<='" + dpED.Text + "' AND c.SettlementDateTime>'" + dpST.Text + "' ";  //

            string sqlStr = " SELECT "+ SqlHeard + " FROM ("+ SqlStrMain +") M ";

            //MessageBox.Show(sqlStr);

            JObject joSqlstr = new JObject();
            joSqlstr.Add("sqlStr", sqlStr);
            joSqlstr.Add("Type", "MedInsuHosPInfo");
            joSqlstr.Add("hospID", Global.inf.hisHospitalDr);
            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(), "查询结算信息");

            //MessageBox.Show(joRtn.ToString());

            if (joRtn["result"]["data"].ToString() == "[]")
            {
                MessageBox.Show("查询结果为空！");
                return;
            }

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

            if (dt.Rows.Count != 0)
            {
                btnPrint.Enabled = true;
                dtExport = dt;

                //从HIS获取患者的床号（分床前医保登记的病人床号没有写入医保平台登记表）
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string BedNo, BedDocName, InHospNo, Address;
                    JObject joTmp = new JObject();
                    joTmp.Add("admID", dt.Rows[i]["Adm_Dr"].ToString());               
                    JObject joRtn2 = invoker.invokeHISService(JsonHelper.setIrisInpar("05110014", joTmp).ToString(), "获取患者就诊信息");
                    if (JsonHelper.parseIrisRtnValue(joRtn2, out string errMsg) == 0)
                    {
                        BedNo = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.adm_bed");
                        BedDocName = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.chfpdr_name");
                        InHospNo = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.medrcdno");
                        Address = JsonHelper.getDestValue(JObject.Parse(joRtn2.ToString()), "mdtrtinfo.Address");
                        dt.Rows[i]["AdmBed"] = BedNo;
                        dt.Rows[i]["AttendDoctorNO"] = BedDocName;
                        dt.Rows[i]["InHospNo"] = InHospNo;
                        dt.Rows[i]["Address"] = Address;
                    }  
                    else
                    {
                        if (errMsg.IndexOf("请重新登录") > 0)                        
                        {
                            MessageBox.Show("获取患者信息失败，请重新登录系统！");
                            break;
                        }
                    }
                }
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            string LSH = DateTime.Now.ToString("yyyy-MM-dd"); //DateTime.Now.ToString("MMddHHmmssffff");
            string sFliePathName = @"C:\Users\Administrator\Desktop\" + LSH + "医保在院患者登记或结算信息.xls";  
            string ReturnFileName = ExportToExcel.DataTabletoExcel(dtExport, sFliePathName);
            if (ReturnFileName != "")
            {
                MessageBox.Show("导出成功,文件保存路径：【" + ReturnFileName + "】");
                System.Diagnostics.Process.Start(ReturnFileName); //打开excel文件                
            }
            else
            {
                MessageBox.Show("导出失败!");
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string sqlStr;
            sqlStr = " SELECT a.Adm_Dr,c.Name, b.HISCode, b.MedInsuNO, b.Price,b.Sumamt,b.ChargeItemLevel,c.ChargeItemLevelName,b.SelfPayProp, ";
            sqlStr = sqlStr + " b.UpLimitAmount,b.OverLimitAmount,b.InScopeAmount,b.FullOwnPayAmount,b.PreSelfPayAmount,b.LimitUsedFlag ";
            sqlStr = sqlStr + " FROM BS_MedInsuSettlement a LEFT JOIN BS_MedInsuFeeUploadRecord b ";
            sqlStr = sqlStr + " ON a.Hospital_Dr=b.Hospital_Dr AND a.MdtrtID=b.MdtrtID AND a.PersonnelNO=b.PersonnelNO ";
            sqlStr = sqlStr + " LEFT JOIN HB_MedInsuDirectory c ON b.MedInsuNO=c.Code AND a.Interface_Dr=c.Interface_Dr AND a.Hospital_Dr=c.Hospital_Dr ";
            sqlStr = sqlStr + " WHERE b.MedInsuNO<>'' and a.ValidFlag=1 AND a.BillType=1 AND a.AdmType=2 ";
            sqlStr = sqlStr + " AND a.Interface_Dr=" + Global.inf.interfaceDr;
            sqlStr = sqlStr + " AND a.Hospital_Dr= " + Global.inf.hospitalDr;
            sqlStr = sqlStr + " AND a.OccurTime>'" + dt_ST.Text + "'";
            sqlStr = sqlStr + " AND a.OccurTime<'" + dt_ET.Text + "'";

            if (tb_InHospNo.Text != "")
            {
                sqlStr = sqlStr + " and a.BillID='" + tb_InHospNo.Text + "'";
            }
            if (tb_SettleID.Text != "")
            {
                sqlStr = sqlStr + " and a.SettlementID='" + tb_SettleID.Text + "'";
            }

            if (cbbOverPrice.Text == "是")
            {
                sqlStr = sqlStr + " AND b.OverLimitAmount>0 ";
            }
            else if (cbbOverPrice.Text == "否")
            {
                sqlStr = sqlStr + " AND b.OverLimitAmount<=0 ";
            }

            if (cbbLevel.Text == "甲类")
            {
                sqlStr = sqlStr + " AND b.ChargeItemLevel='01' ";
            }
            else if (cbbLevel.Text == "乙类")
            {
                sqlStr = sqlStr + " AND b.ChargeItemLevel='02' ";
            }
            else if (cbbLevel.Text == "丙类")
            {
                sqlStr = sqlStr + " AND b.ChargeItemLevel='03' ";
            }

            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", "09010118");
            JObject joRtn = invoker.invokeInsuService(joSettlQuery.ToString(), "查询医保结算费用信息");

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