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.Helper;
using PTMedicalInsurance.Common;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.FormSetter;
using PTMedicalInsurance.Variables;
using Newtonsoft.Json;
using System.Threading;
using PTMedicalInsurance.Business;

namespace PTMedicalInsurance.Forms
{

    public partial class SettlementChecklist : Form
    {
        private int hospitalDr;
        private int interfaceDr;
        private string hospitalNO;
        private string interfaceNO;
        private string hospitalName;
        private string hospitalAreaCode;

        private bool disposed = false;

        Thread thread_test;

        private InvokeHelper invoker = new InvokeHelper();
        public SettlementChecklist()
        {
            InitializeComponent();
            hospitalDr = Global.inf.hospitalDr;
            hospitalNO = Global.inf.hospitalNO;
            hospitalName = Global.inf.hospitalName;
            hospitalAreaCode = Global.inf.areaCode;
            interfaceDr = Global.inf.interfaceDr;
        }
        public SettlementChecklist(JObject joParam)
        {
            InitializeComponent();
            hospitalDr = Global.inf.hospitalDr;
            hospitalNO = Global.inf.hospitalNO;
            hospitalName = Global.inf.hospitalName;
            hospitalAreaCode = Global.inf.areaCode;

            if (joParam == null) return;

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

            JObject joSqlStr = new JObject();
            joSqlStr.Add("sqlStr", sqlStr);
            MIIrisServices mIS = new MIIrisServices();
            JObject joRtn = mIS.QuerySettlementInfo(joSqlStr);
            DataTable dt = (DataTable)joRtn["result"]["data"].ToObject(typeof(DataTable));
            dgvSettlRecord.DataSource = dt;
        }

        private string getTemplatePath()
        {
            if (Utils.isOtherCityPatient())
            {
                return Global.curEvt.path + "\\frx\\settlement_other.frx";
            }
            return Global.curEvt.path + "\\frx\\settlement.frx";
        }

        new public void Dispose()
        {
        
            Dispose1(true);
            GC.SuppressFinalize(this);
    
        }

        protected virtual void Dispose1(bool disposing)
        {
       
            if (thread_test == null) return;
            if (disposed == false)
            {
                if (disposing == true)
                {
                    Thread.Sleep(100);
                    Global.writeLog("Main - aborting my thread.");
                    thread_test.Abort();//终止线程myThread
                    thread_test.Join();//等待线程myThread结束
                    Global.writeLog("Main - ending.");
                }
                //释放托管资源的代码
            }
            disposed = true;
        
        }

        private void rbgDirecType_ValueChanged(object sender, int index, string text)
        {

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {

        }

        private void btnQuery_Click_1(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);
            MIIrisServices mIS = new MIIrisServices();
            JObject joRtn = mIS.QuerySettlementInfo(joSqlStr);

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



        private void SettlementChecklist_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;

            //赋值
            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();
        }

        [STAThread]
        public void design()
        {

            try
            {
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        [STAThread]
        private void print()
        {
            try
            {
                int i = dgvSettlRecord.CurrentRow.Index;
                DataTable dt = (DataTable)dgvSettlRecord.DataSource;
                JObject jo = new JObject();
                jo.Add("mdtrt_id", dt.Rows[i]["MdtrtID"].ToString());
                jo.Add("file_type", "01");
                jo.Add("psn_no", dt.Rows[i]["PersonnelNO"].ToString());
                jo.Add("setl_id", dt.Rows[i]["SettlementID"].ToString());

                JObject joInput = new JObject();
                joInput.Add("data", jo);
                string FileName = dt.Rows[i]["PatientName"].ToString() + dt.Rows[i]["SettlementID"].ToString();
                InvokeRestCenter irc = new InvokeRestCenter();
                string errMsg, filePath = $"{Global.curEvt.path}\\Download\\{FileName}.pdf";
                if (irc.DownloadPDF(JsonHelper.setCenterInpar("9160", joInput), filePath, out errMsg) != 0)
                {
                    MessageBox.Show("下载失败！" + errMsg);
                }
                else
                {
                    PDFViewer pdf = new PDFViewer();
                    pdf.webBrowser1.Url  = new Uri(filePath); 
                    pdf.WindowState = FormWindowState.Maximized;
                    pdf.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }



        private void uiButton2_Click(object sender, EventArgs e)
        {
            Close();
        }
        /// <summary>
        /// 点击打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnPrint_Click(object sender, EventArgs e)
        {

            try
            {
                Thread thread = new Thread(new ThreadStart(print));
                thread.SetApartmentState(ApartmentState.STA); //重点
                thread.Start();
                thread.Join();
            }
            catch (Exception ex)
            {
                Global.writeLog("结算单打印异常:" + ex.Message);
                MessageBox.Show("打印异常:" + ex.Message);
            }

            //printReport();
            
        }

     
       
        /// <summary>
        /// 点击设计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDesign_Click(object sender, EventArgs e)
        {

            thread_test = new Thread(new ThreadStart(design));
            thread_test.SetApartmentState(ApartmentState.STA); //重点
            thread_test.Start();
        }

        private void SettlementChecklist_FormClosed(object sender, FormClosedEventArgs e)
        {
      
            Dispose();
        }


    }

    






}
