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

namespace PTMedicalInsurance.Forms
{
    public partial class PatientInsuInfo : Form
    {
        public DataTable dtInsuInfo;
        public DataTable dtIDInfo;
        public JObject joSelectedInsuInfo;
        public int insuInfoIndex = 0;
        public int idInfoIndex = 0;
        InvokeHelper invoker = new InvokeHelper();
        private MIIrisServices mIS = new MIIrisServices();
        private DataTable dtFundPayType;
        private Form mainForm;

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

        public PatientInsuInfo()
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterParent;
            asc.controllInitializeSize(this);

            asc.controlAutoSize(this);
        }

        public PatientInsuInfo(JObject jo,Form frm)
        {
             InitializeComponent();
             InitForm(jo,frm);
        }

        public PatientInsuInfo(JObject jo)
        {
            InitializeComponent();
            InitForm(jo);
        }

        private void InitForm(JObject jo)
        {
            dtInsuInfo = (DataTable)jo["insuinfo"].ToObject(typeof(DataTable));
            dtIDInfo = (DataTable)jo["idetinfo"].ToObject(typeof(DataTable));
            JObject joBaseInfo = JObject.FromObject(jo["baseinfo"]);
            this.tbName.Text = joBaseInfo["psn_name"].ToString();
            this.tbPsnNO.Text = joBaseInfo["psn_no"].ToString();
            this.tbGend.Text = joBaseInfo["gend"].ToString();
            this.tbBirthDay.Text = joBaseInfo["brdy"].ToString();
            this.tbNaty.Text = joBaseInfo["naty"].ToString();
            this.tbCertType.Text = joBaseInfo["psn_cert_type"].ToString();
            this.tbCertNO.Text = joBaseInfo["certno"].ToString();
            this.tbAge.Text = joBaseInfo["age"].ToString();

            string expContent = joBaseInfo["exp_content"].ToString();  //字段扩展 只有居民返回

            //JObject joInsuInfo = JObject.FromObject(jo["insuinfo"]);
            //Global.pat.insuType= joInsuInfo["insutypeNo"].ToString();

            setDgvIDInfo();
            setDgvInsuInfo();
            setDgvTreatement(dgvTreatment);
            dgvInsuInfo.DataSource = dtInsuInfo;
            dgvIDInfo.DataSource = dtIDInfo;


            //获取通用目录
            string sTYML = mIS.GetCommonInterface_Dr(Global.inf.interfaceDr.ToString(), "");
            if (sTYML == "")
                Global.inf.interfaceDr_TY = Global.inf.interfaceDr;
            else
                Global.inf.interfaceDr_TY = int.Parse(sTYML);

            string sqlCondition = " and A.Interface_Dr = '" + Global.inf.interfaceDr_TY.ToString() + "'";
            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 = 'fund_pay_type'" + sqlCondition;

            dtFundPayType = GetDBLKComboxTable(sqlStr);
        }

        private void InitForm(JObject jo, Form frm)
        {
            InitForm(jo);
            mainForm = frm;
            CheckForIllegalCrossThreadCalls = false;
            // 禁用关闭按钮
            this.FormBorderStyle = FormBorderStyle.None;

            // 隐藏标题栏
            this.ControlBox = false;

            // 其他可能需要的配置
            if (mainForm != this)
            {
                this.TopLevel = false;
                this.Dock = DockStyle.Fill; // 根据需要设置 Dock 属性
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }

            //
            //grdSetter.setHisRegInfo(dgvHisRegInfo);
            //grdSetter.setCenterApplyInfo(dgvCenterApplyInfo);
        }
        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 AddDGVColumn(DataGridView dgv, string headerText, string dataPropertyName, int width = 120)
        {
            DataGridViewColumn newColumn = new DataGridViewTextBoxColumn();
            newColumn.HeaderText = headerText;
            newColumn.Width = width;
            newColumn.DataPropertyName = dataPropertyName;
            newColumn.Name = dataPropertyName;
            dgv.Columns.Add(newColumn);
        }
        public void setDgvTreatement(DataGridView dgv)
        {
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Clear();
            AddDGVColumn(dgv, "人员编号", "psn_no", 300);
            AddDGVColumn(dgv, "待遇检查类型", "trt_chk_type", 140);
            AddDGVColumn(dgv, "基金支付类型", "fund_pay_type", 300);
            AddDGVColumn(dgv, "基金款项待遇享受标志", "trt_enjymnt_flag", 140);
            AddDGVColumn(dgv, "开始日期", "begndate", 200);
            AddDGVColumn(dgv, "结束日期", "enddate", 200);
            AddDGVColumn(dgv, "待遇检查结果", "trt_chk_rslt", 140);
            AddDGVColumn(dgv, "字段扩展", "exp_content", 140);
            dgv.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 9, FontStyle.Bold);
            dgv.ColumnHeadersHeight = 30;
        }

        private void setDgvInsuInfo()
        {
            AddDGVColumn(dgvInsuInfo, "余额", "balc", 80);
            AddDGVColumn(dgvInsuInfo, "险种类型", "insutype",200);
            AddDGVColumn(dgvInsuInfo, "人员类别", "psn_type");
            AddDGVColumn(dgvInsuInfo, "人员参保状态", "psn_insu_stas");
            AddDGVColumn(dgvInsuInfo, "个人参保日期", "psn_insu_date",170);
            AddDGVColumn(dgvInsuInfo, "暂停参保日期", "paus_insu_date");
            AddDGVColumn(dgvInsuInfo, "公务员标志", "cvlserv_flag",95);
            AddDGVColumn(dgvInsuInfo, "参保区划", "insuplc_admdvs",85);
            AddDGVColumn(dgvInsuInfo, "单位名称", "emp_name",300);
            AddDGVColumn(dgvInsuInfo, "险种类型编码", "insutypeNo");
            dgvInsuInfo.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 9, FontStyle.Bold);
            dgvInsuInfo.ColumnHeadersHeight = 40; //341124199210252617
        }

        private void setDgvIDInfo()
        {
            AddDGVColumn(dgvIDInfo, "人员身份类别", "psn_idet_type", 140);
            AddDGVColumn(dgvIDInfo, "人员类别等级", "psn_type_lv", 140);
            AddDGVColumn(dgvIDInfo, "备注", "memo", 150);
            AddDGVColumn(dgvIDInfo, "开始时间", "begntime", 200);
            AddDGVColumn(dgvIDInfo, "结束时间", "endtime", 200);
            dgvIDInfo.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 9, FontStyle.Bold);
            dgvIDInfo.ColumnHeadersHeight = 40;
        }
        private void uiButton1_Click(object sender, EventArgs e)
        {
            
            insuInfoIndex = dgvInsuInfo.CurrentRow.Index;
            if (dtIDInfo.Rows.Count != 0 )
                idInfoIndex = dgvIDInfo.CurrentRow.Index;
            joSelectedInsuInfo = new JObject();
            for (int i = 0; i < dtInsuInfo.Columns.Count; i++)
            {
                string key = dtInsuInfo.Columns[i].ColumnName;
                string value = dgvInsuInfo.CurrentRow.Cells[key].Value.ToString();
                joSelectedInsuInfo.Add(key, value);
            }

            DialogResult = DialogResult.OK;
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private JObject QueryTreamentInfo()
        {
            int i = dgvInsuInfo.SelectedIndex;
            string insutype = dgvInsuInfo.Rows[i].Cells["insutypeNo"].Value.ToString();
            var joData = new { data = new { psn_no = this.tbPsnNO.Text, insutype = insutype, med_type = tools.getDestPosStrBySpliter(cbxMedicalType.Text, 1, "."), begntime = tbBeginDate_treatment.Text, endtime = tbEndDate_treatment.Text, fixmedins_code = Global.inf.hospitalNO } };
            return invoker.invokeCenterService("2001", JsonHelper.setCenterInpar("2001", JObject.FromObject(joData)));
        }

        private void btTreatment_Click(object sender, EventArgs e)
        {
            JObject joRtn = QueryTreamentInfo();
            string err;
            if (JsonHelper.parseCenterRtnValue(joRtn, out err) != 0)
            {
                MessageBox.Show(err);
                return;
            }

            // 创建一个字典来存储 dt2 中的 code 和 desc 键值对，以便快速查找
            var codeDescMap = dtFundPayType.AsEnumerable()
                .ToDictionary(row => row.Field<string>("Code"), row => row.Field<string>("Name"));

            DataTable dt = (DataTable)joRtn["output"]["trtinfo"].ToObject(typeof(DataTable));
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["trt_enjymnt_flag"].ToString() == "0")
                {
                    dr["trt_enjymnt_flag"] = "否";
                }
                else if(dr["trt_enjymnt_flag"].ToString() == "1")
                {
                    dr["trt_enjymnt_flag"] = "是";
                }
                else
                {
                    //
                }

                if (dr["trt_chk_type"].ToString() == "01")
                {
                    dr["trt_chk_type"] = "基金项检查";
                }
                else if (dr["trt_chk_type"].ToString() == "99")
                {
                    dr["trt_chk_type"] = "其它检查";
                }
                else
                {
                    //
                }


                String key = dr["fund_pay_type"].ToString();
                // 检查 codeDescMap 中是否存在对应的描述
                if (codeDescMap.ContainsKey(key))
                {
                    // 使用找到的描述更新当前行的 trt_enjymnt_flag 字段
                    dr["fund_pay_type"] = $"({key}){codeDescMap[key]}";
                }
                else
                {
                    // 如果没有找到对应描述，则可以设置一个默认值或者保留原值
                    //dr["fund_pay_type"] = "未知"; // 或者其他的默认值
                }
            }
            dgvTreatment.DataSource = dt;
        }
    }
}
