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
    {
        InvokeHelper invoker = new InvokeHelper();
        DataTable dtExport;

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

        public MedInsuQuery()
        {
            InitializeComponent();

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

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

        private DataTable GetDBLKComboxTable(string sqlStr)
        {
            InvokeHelper invoker = new InvokeHelper();
            dynamic joInparm = new JObject();

            dynamic joTmp = new JObject();
            joTmp.sqlStr = sqlStr;
            JArray jaParams = new JArray();
            jaParams.Add(joTmp);
            joInparm.Add("params", JArray.FromObject(jaParams));
            joInparm.code = "09010014";
            string inParam = joInparm.ToString();
            JObject joRtn = invoker.invokeInsuService(inParam, "获取下拉框消息");
            //dynamic jsonRtn = JsonConvert.DeserializeObject(strRtn);
            DataTable dt = (DataTable)joRtn["result"].ToObject(typeof(DataTable));
            //dt.Columns[0].ColumnName = "编码";
            //dt.Columns[1].ColumnName = "名称";
            //dt.Columns[2].ColumnName = "拼音查找码";
            return dt;
        }

        private void GetCheckBoxGroupItem(string sqlStr,CheckedListBox checkedListBox1)
        {
            DataTable DT = GetDBLKComboxTable(sqlStr);
            checkedListBox1.Items.Clear();
            for (int i = 0; i < DT.Rows.Count; i++)
            {
                string Code = DT.Rows[i]["Code"].ToString();
                string Name = DT.Rows[i]["Name"].ToString();
                string Str = Code + "-" + Name;
                checkedListBox1.Items.Add(Str);
            }
        }

        private void MedInsuQuery_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");

            dt_Begin.Text = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            dt_End.Text = DateTime.Now.ToString("yyyy-MM-30 23:59:59");
            edt_SetlNY.Text = DateTime.Now.ToString("yyyyMM");

            // dgvSettlRecord.AutoGenerateColumns = false;
            GridViewSetter grdSetter = new GridViewSetter();
            grdSetter.SetHeaderTextOfMedInsuHosPerInfo(dgvSettlRecord);

            //医保查询页
            rb_query1.Visible = true;
            rb_query2.Visible = false;
            cb_MedQueryType.SelectedIndex = 0;
                        
            string sqlStr = " SELECT B.Code,B.Descripts AS Name FROM HB_Dictionary A JOIN HB_DictionaryDataDetail B ON A.ID = B.HBDictionary_Dr  "
                          + " WHERE A.InsuCode = 'Med_Type' and A.Interface_Dr = '" + Global.inf.interfaceDr.ToString() + "'";

            GetCheckBoxGroupItem(sqlStr, chklst_MedTypeList);
        }

        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 cb_MedQueryType_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewSetter gvdSetter = new GridViewSetter();
            if (cb_MedQueryType.SelectedIndex < 3)
            {
                rb_query1.Visible = true;
                rb_query2.Visible = false;

                switch (cb_MedQueryType.SelectedIndex)
                {
                    case 0://【3605】DRG 分组结果查询
                        {
                            gvdSetter.SetHeaderTextOfDRGGroupResultQuery(dgv_MainData);
                            break;
                        }
                    case 1://【3606】DIP 分组结果查询
                        {
                            gvdSetter.SetHeaderTextOfDIPGroupResultQuery(dgv_MainData);
                            break;
                        }
                    case 2://【3607】结算清单质控结果查询
                        {
                            gvdSetter.SetHeaderTextOfSetlBillQualityResultQuery(dgv_MainData);
                            break;
                        }
                }
            }
            else if (cb_MedQueryType.SelectedIndex == 3)
            {
                rb_query1.Visible = false;
                rb_query2.Visible = true;

                //【4105】医疗保障基金结算清单数量统计查询
                gvdSetter.SetHeaderTextOfSetlBillCountQuery(dgv_MainData);
            }
        }

        private void btnMedQuery_Click(object sender, EventArgs e)
        {
            string errorMsg;
            string sBussiesID;
            DataTable dt;
            JObject joData = new JObject();
            JObject joInput = new JObject();            

            sBussiesID = cb_MedQueryType.Text.Substring(0, 4);
            if (cb_MedQueryType.SelectedIndex < 3)
            {                
                joData.Add("setl_ym", edt_SetlNY.Text);
                joData.Add("page_num", edt_Page.Text);
                joData.Add("page_size", edt_PageCount.Text);
                joData.Add("setl_id", edt_SetID.Text);
                joInput.Add("data", joData);
            }
            else
            {
                //医疗类别获取选中项
                JArray ja = new JArray();
                string selectedOptions = string.Empty;
                foreach (var item in chklst_MedTypeList.CheckedItems)
                {
                    string sItem = item.ToString();
                    string[] sArry = sItem.Split('-'); 
                    string medType = sArry[0]; //截取分隔符-前的字符串                    
                    //selectedOptions += item.ToString() + Environment.NewLine + selectedOptions;
                    ja.Add(medType);
                }

                string stt_flag="0", refdset_flag="false";
                if (chk_returnFlag.Checked)
                    stt_flag = "1";
                if (chk_TotleFlag.Checked)
                    refdset_flag = "true";
                   
                joData.Add("fixmedins_code", Global.inf.hospitalNO);
                joData.Add("medtype_list", ja);
                joData.Add("stt_begntime", dt_Begin.Text);
                joData.Add("stt_endtime", dt_End.Text);
                joData.Add("stt_flag", stt_flag);
                joData.Add("refdset_flag", refdset_flag);
                joInput.Add("data", joData);
            }

            JObject joRtn = invoker.invokeCenterService(sBussiesID, JsonHelper.setCenterInpar(sBussiesID, joInput));
            if (JsonHelper.parseCenterRtnValue(joRtn, out errorMsg) != 0)
            {
                MessageBox.Show(cb_MedQueryType.Text + " 查询失败：" + errorMsg);
                return;
            }
            else
            {
                if ((cb_MedQueryType.SelectedIndex == 0) || (cb_MedQueryType.SelectedIndex == 1))                
                {
                    dt = (DataTable)joRtn["output"]["data"].ToObject(typeof(DataTable));
                }
                else
                if (cb_MedQueryType.SelectedIndex == 3)
                {
                    dt = (DataTable)joRtn["output"].ToObject(typeof(DataTable));
                }
                else
                {
                    //dt = (DataTable)joRtn["output"]["data"].ToObject(typeof(DataTable));
                    JArray RtnjaArray = JArray.Parse(JsonHelper.getDestValue(joRtn, "output.data").ToString());
                    JArray ja = new JArray();
                    
                    foreach (JObject obj in RtnjaArray)
                    {
                        string qltctrl_chk_rslt = "";
                        //取值重新组织
                        string cert_no = (string)obj["cert_no"].ToString();
                        string grp_stas = (string)obj["grp_stas"].ToString();
                        string qltctrl_rslt = (string)obj["qltctrl_rslt"].ToString();
                        string setl_id = (string)obj["setl_id"].ToString();
                        string psn_name = (string)obj["psn_name"].ToString();
                        string err_lv = (string)obj["err_lv"].ToString();
                        string setl_ym = (string)obj["setl_ym"].ToString();
                        string fixmedins_code = (string)obj["fixmedins_code"].ToString();
                        string psn_no = (string)obj["psn_no"].ToString();
                        string qltctrl_ver = (string)obj["qltctrl_ver"].ToString();
                        string detl_list = (string)obj["detl_list"].ToString();                              
                        string fixmedins_name = (string)obj["fixmedins_name"].ToString();
                        string psn_cert_type = (string)obj["psn_cert_type"].ToString();
                        string retn_flag = (string)obj["retn_flag"].ToString();
                        //int age = (int)obj["age"];                        
                        if (err_lv == "3")
                        {
                            JArray jaDetList = JArray.Parse(obj["detl_list"].ToString());

                            foreach (JObject obj1 in jaDetList)
                            {
                                //string qltctrl_chk_rslt = (string)obj1["qltctrl_chk_rslt"].ToString();
                                qltctrl_chk_rslt = (string)obj1["qltctrl_chk_rslt"].ToString() + ";" + qltctrl_chk_rslt;
                            }
                        }

                        JObject jo = new JObject();
                        jo.Add("cert_no", cert_no);
                        jo.Add("grp_stas", grp_stas);
                        jo.Add("qltctrl_rslt", qltctrl_rslt);
                        jo.Add("setl_id", setl_id);
                        jo.Add("psn_name", psn_name);
                        jo.Add("err_lv", err_lv);
                        jo.Add("fixmedins_code", fixmedins_code);
                        jo.Add("psn_no", psn_no);
                        jo.Add("qltctrl_ver", qltctrl_ver);
                        jo.Add("detl_list", qltctrl_chk_rslt);
                        jo.Add("fixmedins_name", fixmedins_name);
                        jo.Add("psn_cert_type", psn_cert_type);
                        jo.Add("retn_flag", retn_flag);
                        ja.Add(jo);
                    }  

                    dt = (DataTable)ja.ToObject(typeof(DataTable));
                }              

                dgv_MainData.DataSource = dt;

                if (dt.Rows.Count > 0)
                {
                    btnImport.Enabled = true;
                    dtExport = dt;
                }
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string sBussiesID = cb_MedQueryType.Text;
            string LSH = DateTime.Now.ToString("yyyyMMdd"); //DateTime.Now.ToString("MMddHHmmssffff");
            string sFliePathName = @"C:\Users\Administrator\Desktop\" + LSH + sBussiesID + "信息.xls";
            string ReturnFileName = ExportToExcel.DataTabletoExcel(dtExport, sFliePathName);
            if (ReturnFileName != "")
            {
                MessageBox.Show("导出成功,文件保存路径：【" + ReturnFileName + "】");
                System.Diagnostics.Process.Start(ReturnFileName); //打开excel文件                
            }
            else
            {
                MessageBox.Show("导出失败!");
            }
        }
    }
}