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

namespace PTMedicalInsurance.Forms
{
    public partial class ToRecordFrom : Form
    {
        public ToRecordFrom()
        {
            InitializeComponent();
        }
        JObject userMsg = (JObject)JsonConvert.DeserializeObject("");
        DropHelper drop = new DropHelper();
        IrisDataHelper irisData = new IrisDataHelper();
        InvokeHelper invoker = new InvokeHelper();

        #region 下拉框自动选择
        /// <summary>
        /// 下拉框自动选择
        /// </summary>
        /// <param name="data">数据源（字典）</param>
        /// <param name="comBox">框体</param>
        public void ComBoxChoose(Dictionary<string, string> data, ComboBox comBox,bool drop=false)
        {
            comBox.Items.Clear();
            List<ComboBoxItem> temp = new List<ComboBoxItem>();
            foreach (var item in data)
            {
                //循环添加数据源
                if (item.Value.Contains(comBox.Text))
                {
                    ComboBoxItem com = new ComboBoxItem();
                    com.Text = item.Value;
                    com.Value = item.Key;
                    temp.Add(com);
                }
            }
            if (temp.Count < 1)
            {
                //输入参数未找到时添加空白选择
                ComboBoxItem zero = new ComboBoxItem();
                zero.Text = "";
                zero.Value = "";
                temp.Add(zero);
            }
            try
            {
                comBox.Items.AddRange(temp.ToArray());
                comBox.SelectionStart = comBox.Text.Length;    //更新索引
                Cursor = Cursors.Default;                      //设置光标
                if (drop)
                {
                    comBox.DroppedDown = true;                 //自动弹出下拉框
                }
            }
            catch (Exception ee)
            {
                comBox.SelectedIndex = -1;
            }
        }
        #endregion

        private void btn_GetMsg_Click(object sender, EventArgs e)
        {
            //InsuBusiness insu = new InsuBusiness();
            //MessageBox.Show("调用读卡：" + insu.GetPatientInfo(""));

            #region 调用1101
            ////调用1101
            //JObject joData = new JObject();
            //joData.Add("mdtrt_cert_type", "居民身份证");//就医凭证类型
            //joData.Add("mdtrt_cert_no", "02");          //就医凭证编码
            //joData.Add("card_sn", Global.pat.cardSN);   //为社保卡时必填
            ////joData.Add("begntime", "");               //开始时间         
            //joData.Add("psn_cert_type", "居民身份证");  //证件类型
            //joData.Add("certno", "511923187001...");    //身份证号
            //joData.Add("psn_name", Global.pat.name);    //人员姓名

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

            //InvokeHelper invoker = new InvokeHelper();
            //JObject joRtn = invoker.invokeCenterService("1101", JsonHelper.setCenterInpar("1101", joInput));

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

            string rtnJson = "{\"body\":{\"output\":{\"idetinfo\":[],\"baseinfo\":{\"certno\":\"342822196511171215\",\"psn_no\":\"13465308\",\"gend\":\"1\",\"brdy\":-130147200000,\"psn_cert_type\":\"01\",\"psn_name\":\"高国正\",\"age\":56},\"insuinfo\":[{\"insuplc_admdvs\":\"340800\",\"cvlserv_flag\":\"0\",\"balc\":0,\"psn_type\":\"1501\",\"emp_name\":\"云水村\",\"psn_insu_stas\":\"1\",\"insutype\":\"390\"}]},\"infcode\":0,\"inf_refmsgid\":\"349900202208221634300039305403\"},\"code\":200,\"csbCode\":200,\"message\":\"SUCCESS\",\"requestId\":\"0a429bab16611572691156719d0116\",\"state\":{}}";
            #region 解析返回值，填充
            
            JObject joRtn = (JObject)JsonConvert.DeserializeObject(rtnJson);
            string code = joRtn["code"].ToString();
            string csbCode = joRtn["csbCode"].ToString();
            string message = joRtn["message"].ToString();
            string requestId = joRtn["requestId"].ToString();

            if (code == "200" && message == "SUCCESS")
            {
                string infcode =  joRtn["body"]["infcode"].ToString();
                if (infcode == "-1") return;
                JObject baseinfo = (JObject)JsonConvert.DeserializeObject(joRtn["body"]["output"]["baseinfo"].ToString());
                this.tbx_No.Text = baseinfo["psn_no"].ToString();
                //this.cbx_CardType.Text = baseinfo["certno"].ToString();
                //this.cbx_CardType.Text = baseinfo["psn_cert_type"].ToString();
                this.tbx_Name.Text = baseinfo["psn_name"].ToString();
                this.tbx_TranType.Text = baseinfo["age"].ToString();
                JArray insuData = (JArray)JsonConvert.DeserializeObject(joRtn["body"]["output"]["insuinfo"].ToString());
                JObject insuinfo = (JObject)insuData[0];
                tbx_AddNo.Text = insuinfo["insuplc_admdvs"].ToString();
                //tbx_AddNo.Text = insuinfo["cvlserv_flag"].ToString();
                tbx_InsuType.Text = insuinfo["insutype"].ToString();
                //tbx_MediGen.Text = insuinfo["insuplc_admdvs"].ToString();
            }

            #endregion

            int fdee = 1;
        }

        private void ToRecordFrom_Load(object sender, EventArgs e)
        {
            //初始化身份选择
            Dictionary<string, string> data = drop.CredenecType();
            ComBoxChoose(data, cbx_CardType, false);
            cbx_CardType.SelectedIndex = 0;
            //初始化病种选择
            Dictionary<string, string> dise = drop.DiseName();
            ComBoxChoose(dise, cbx_DiseName, false);
            cbx_DiseName.SelectedIndex = 0;

        }

        private void cbx_CardType_TextUpdate(object sender, EventArgs e)
        {
            Dictionary<string, string> data = drop.CredenecType();
            ComboBox cb = sender as ComboBox;
            ComBoxChoose(data, cb, true);
        }

        private void cbx_DiseName_TextUpdate(object sender, EventArgs e)
        {
            Dictionary<string, string> data = drop.DiseName();
            ComboBox cb = sender as ComboBox;
            ComBoxChoose(data, cb, true);
        }

        /// <summary>
        /// 提交备案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OK_Click(object sender, EventArgs e)
        {            
            JObject joRtn = invoker.invokeCenterService("2501", JsonHelper.setCenterInpar("2501", ToJson()));
            //JObject jo = (JObject)JsonConvert.DeserializeObject(rtnJson);
            if (string.IsNullOrWhiteSpace(joRtn.ToString())) MessageBox.Show("备案失败，原因是：" + joRtn.ToString()) ;
            string code = joRtn["infcode"].ToString();
            if(code=="-1") MessageBox.Show("备案失败，原因是：" + joRtn.ToString());
            //string code = joRtn["code"].ToString();
            //string csbCode = joRtn["csbCode"].ToString();
            //string message = joRtn["message"].ToString();
            //string requestId = joRtn["requestId"].ToString();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                oString();

            if (code == "200")//成功时调用
            {
                string dcla = joRtn["trt_dcla_detl_sn"].ToString();
                //提交备案
                JObject rtn = invoker.invokeInsuService(ToJson(dcla), "ToRecord");

            }
        }

        public string ToJson(string dclaRtn="")
        {
            #region 下拉框取值
            var diseName = (ComboBoxItem)cbx_DiseName.Items[cbx_DiseName.SelectedIndex == -1 ? 0 : cbx_DiseName.SelectedIndex];
            //var diagName = (ComboBoxItem)cbx_DiagName.Items[cbx_DiagName.SelectedIndex == -1 ? 0 : cbx_DiagName.SelectedIndex];
            //json.AppendFormat("\"diag_code\":\"{0}\",", diagName.Value);
            //json.AppendFormat("\"diag_name\":\"{0}\",", diagName.Text.Trim());
            //var MedInst = (ComboBoxItem)cbx_MedInst.Items[cbx_MedInst.SelectedIndex == -1 ? 0 : cbx_MedInst.SelectedIndex];
            //json.AppendFormat("\"fixmedins_code\":\"{0}\",", MedInst.Value);
            //json.AppendFormat("\"fixmedins_name\":\"{0}\",", MedInst.Text.Trim());
            var ToMedInst = (ComboBoxItem)cbx_ToMedInst.Items[cbx_ToMedInst.SelectedIndex == -1 ? 0 : cbx_ToMedInst.SelectedIndex];
            //json.AppendFormat("\"reflin_medins_no\":\"{0}\",", ToMedInst.Value);
            //json.AppendFormat("\"reflin_medins_name\":\"{0}\",", ToMedInst.Text.Trim());
            #endregion

            JObject joData = new JObject();
            joData.Add("psn_no", tbx_No.Text.Trim());
            joData.Add("insutype", tbx_InsuType.Text.Trim());
            joData.Add("tel", tbx_Phone.Text.Trim());
            joData.Add("addr", tbx_address.Text.Trim());
            joData.Add("insu_optins", tbx_AddNo.Text.Trim());
            joData.Add("diag_code", diseName.Value.ToString()); 
            joData.Add("diag_name", diseName.Text.Trim());
            joData.Add("dise_cond_dscr", rtb_DiagDesc.Text.Trim());
            joData.Add("reflin_medins_no", ToMedInst.Value.ToString());
            joData.Add("reflin_medins_name", ToMedInst.Text.Trim());
            joData.Add("mdtrtarea_admdvs", tbx_ToAddNo.Text.Trim());
            joData.Add("hosp_agre_refl_flag", "1");
            joData.Add("refl_type", tbx_TranType.Text.Trim());
            joData.Add("refl_date", dpk_TranDate.Text.Trim());
            joData.Add("refl_rea", tbx_TranRea.Text.Trim());
            joData.Add("refl_opnn", tbx_TranOpin.Text.Trim());
            joData.Add("begndate", dpk_StaDate.Text.Trim());
            joData.Add("enddate", dpk_EndDate.Text.Trim());
            joData.Add("refl_used_flag", "");    
            JObject joInput = new JObject();
            joInput.Add("refmedin", joData);

            return joInput.ToString();

            /*
            System.Text.StringBuilder json = new System.Text.StringBuilder("{\"refmedin\":[{", 1000);
            json.AppendFormat("\"psn_no\":\"{0}\",", tbx_No.Text.Trim());
            json.AppendFormat("\"insutype\":\"{0}\",", tbx_InsuType.Text.Trim());
            json.AppendFormat("\"tel\":\"{0}\",", tbx_Phone.Text.Trim());
            json.AppendFormat("\"addr\":\"{0}\",", tbx_address.Text.Trim());
            json.AppendFormat("\"insu_optins\":\"{0}\",", tbx_AddNo.Text.Trim());
            json.AppendFormat("\"med_type\":\"{0}\",", tbx_MediGen.Text.Trim());

            #region 下拉框取值
            var diseName = (ComboBoxItem)cbx_DiseName.Items[cbx_DiseName.SelectedIndex == -1 ? 0 : cbx_DiseName.SelectedIndex];
            json.AppendFormat("\"dise_codg\":\"{0}\",", diseName.Value);
            json.AppendFormat("\"dise_name\":\"{0}\",", diseName.Text.Trim());
            //var diagName = (ComboBoxItem)cbx_DiagName.Items[cbx_DiagName.SelectedIndex == -1 ? 0 : cbx_DiagName.SelectedIndex];
            //json.AppendFormat("\"diag_code\":\"{0}\",", diagName.Value);
            //json.AppendFormat("\"diag_name\":\"{0}\",", diagName.Text.Trim());
            //var MedInst = (ComboBoxItem)cbx_MedInst.Items[cbx_MedInst.SelectedIndex == -1 ? 0 : cbx_MedInst.SelectedIndex];
            //json.AppendFormat("\"fixmedins_code\":\"{0}\",", MedInst.Value);
            //json.AppendFormat("\"fixmedins_name\":\"{0}\",", MedInst.Text.Trim());
            //var ToMedInst = (ComboBoxItem)cbx_ToMedInst.Items[cbx_ToMedInst.SelectedIndex == -1 ? 0 : cbx_ToMedInst.SelectedIndex];
            //json.AppendFormat("\"reflin_medins_no\":\"{0}\",", ToMedInst.Value);
            //json.AppendFormat("\"reflin_medins_name\":\"{0}\",", ToMedInst.Text.Trim());
            #endregion

            //若返回流水号非空，则表示成功，保存到IRIS
            if (dclaRtn != "") {
                json.AppendFormat("\"trt_dcla_detl_sn\":\"{0}\",", dclaRtn);
            }

            json.AppendFormat("\"dise_cond_dscr\":\"{0}\",", rtb_DiagDesc.Text.Trim());
            json.AppendFormat("\"refl_type\":\"{0}\",", tbx_TranType.Text.Trim());
            json.AppendFormat("\"mdtrtarea_admdvs\":\"{0}\",", tbx_ToAddNo.Text.Trim());
            json.AppendFormat("\"refl_date\":\"{0}\",", dpk_TranDate.Text.Trim());
            json.AppendFormat("\"refl_rea\":\"{0}\",", tbx_TranRea.Text.Trim());
            json.AppendFormat("\"refl_opnn\":\"{0}\",", tbx_TranOpin.Text.Trim());
            json.AppendFormat("\"begndate\":\"{0}\",", dpk_StaDate.Text.Trim());
            json.AppendFormat("\"enddate\":\"{0}\",", dpk_EndDate.Text.Trim());

            #region 拼上Iris所需

            json.AppendFormat("\"iresult\":\"\",");        //操作结果 0已上传 9已撤销 
            json.AppendFormat("\"InPut\":\"\",");          //调用入参
            json.AppendFormat("\"OutPut\":\"\",");         //调用反参
            //json.AppendFormat("\"trtDclaDetlSn\":\"\",");  //申报流水号
            
            #endregion

            json.AppendFormat("\"hosp_agre_refl_flag\":\"{0}\"", "1");
            json.Append("}]}");

            return json.ToString();
            */           
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            
            ////获取拼装的接口调用json
            //string getJson = irisData.GetToFileData();
            JObject toIris = new JObject();
            string code = "";
            toIris.Add(new JProperty("params", SetJsonObject("SetToFile", out code)));
            toIris.Add(new JProperty("code", code));
            //toIris.Add(new JProperty("session", irisData.AddUserJson()));
            toIris.Add(new JProperty("session", userMsg));

            string rtnStr = toIris.ToString();
            //去除json数据里的换行符转义
            rtnStr = rtnStr.Replace("\r\n","");
            //调用iris推送
            JObject rtn = invoker.invokeIrisService(rtnStr, "applyDataToIris");

            //this.Close();
            

        }
        
        #region 拼装Json
        private JArray SetJsonObject(string types, out string code)
        {
            code = "";
            JArray jaData = new JArray();
            switch (types)
            {
                case "SetToFile"://民族药品目
                    {
                        code = "02030001";
                        JObject jo = (JObject)JsonConvert.DeserializeObject(ToJson());
                        jaData = (JArray)JsonConvert.DeserializeObject(jo["refmedin"].ToString());
                        break;
                    }
            }

            return jaData;
        }

        
        #endregion
    }
}
