using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using WinFrom1;
using static PTMedicalInsurance.Helper.DropHelper;

namespace PTMedicalInsurance
{
    public partial class PerDesigRecord : Form
    {
        DropHelper drop = new DropHelper();
        IrisDataHelper irisData = new IrisDataHelper();
        InvokeHelper invoker = new InvokeHelper();
        Dictionary<string, string> cardTypeDic = new Dictionary<string, string>();
        Dictionary<string, string> mediDic = new Dictionary<string, string>();
        //string user = HaErBinMIMI.Forms.ToRecord.Helper.UserMessage.session;
        JObject userMsg = (JObject)JsonConvert.DeserializeObject("");
        //Dictionary<string, string> cardType = new Dictionary<string, string>();
        public PerDesigRecord()
        {
            InitializeComponent();
        }

        private void btn_GetMsg_Click(object sender, EventArgs e)
        {
            var cardType = (ComboBoxItem)cbx_CardType.Items[cbx_CardType.SelectedIndex == -1 ? 0 : cbx_CardType.SelectedIndex];
            JObject joData = new JObject();
            joData.Add("mdtrt_cert_type", cardType.Text.ToString());//就医凭证类型
            joData.Add("mdtrt_cert_no", cardType.Value.ToString());          //就医凭证编码
            //joData.Add("card_sn", Global.pat.cardSN);   //为社保卡时必填
            //joData.Add("begntime", "");               //开始时间         
            joData.Add("psn_cert_type", cardType.Value.ToString());  //证件类型  -02
            joData.Add("certno", this.tbx_IdCard.Text.Trim());    //身份证号
            joData.Add("psn_name", Global.pat.name);    //人员姓名

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


            JObject joRtn = invoker.invokeInsuService(JsonHelper.setCenterInpar("1101", joInput), "获取人员信息");

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

            if (!string.IsNullOrEmpty(joRtn.ToString()))
            {
                if (joRtn.ToString().IndexOf("errorCode") != -1) {
                    if (joRtn["errorCode"].ToString() == "-1") {
                        MessageBox.Show(joRtn["errorMessage"].ToString());
                        return;
                    }
                }
                if (joRtn["infcode"].ToString() == "-1") return;
                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")
                {
                    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();
                    //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();
                }
            }

        }

        private void PerDesigRecord_Load(object sender, EventArgs e)
        {
            //初始化身份选择
            cardTypeDic = drop.CredenecType();
            ComBoxChoose(cardTypeDic, cbx_CardType, false);
            ComBoxChoose(cardTypeDic, cbx_AgencyType, false);
            cbx_CardType.SelectedIndex = 0;
            cbx_AgencyType.SelectedIndex = 0;

            //初始化医药机构
            mediDic = drop.Medinsinfo();
            ComBoxChoose(mediDic, cbx_MedInst, false);
            cbx_MedInst.SelectedIndex = 0;

        }

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

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

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

        private void btn_OK_Click(object sender, EventArgs e)
        {
            //JObject joRtn = invoker.invokeInsuService(ToJson("data"), "定点备案");
            JObject joRtn = invoker.invokeInsuService(JsonHelper.setCenterInpar("2506", ToJson("data")),"人员定点备案");
            MessageBox.Show(joRtn.ToString());
            //JObject jo = (JObject)JsonConvert.DeserializeObject(rtnJson);
            if (joRtn.ToString().IndexOf("errorCode") != -1)
            {
                string errorCode = joRtn["errorCode"].ToString();
                if (errorCode == "-1")
                {
                    MessageBox.Show(joRtn["errorMessage"].ToString());
                    return;
                }
            }
            string code = joRtn["code"].ToString();
            string csbCode = joRtn["csbCode"].ToString();
            string message = joRtn["message"].ToString();

            if (code == "200" && message == "SUCCESS")      //调用IRIS
            {
                string infcode = joRtn["infcode"].ToString();
                if (infcode == "-1") MessageBox.Show("备案失败，原因是：" + joRtn.ToString());
                if (infcode == "200")//成功时调用
                {
                    string dcla = joRtn["trt_dcla_detl_sn"].ToString();
                    //提交IRIS
                    JObject toJson = (JObject)JsonConvert.DeserializeObject(ToJson("params", dcla));
                    toJson.Add(new JProperty("code", "02030007"));
                    toJson.Add(new JProperty("session", userMsg));
                    JObject rtn = invoker.invokeIrisService(toJson.ToString().Replace("\r\n",""), "人员定点备案");
                    string errorCode = rtn["errorCode"].ToString().Trim();
                    if (errorCode == "0")
                    {
                        MessageBox.Show("备案操作已完成！");
                    }
                    else
                    {
                        MessageBox.Show("写入IRIS失败！");
                    }   
                }
            }
        }

        /// <summary>
        /// 组装json
        /// </summary>
        /// <param name="parmName">传入Key值</param>
        /// <param name="dclaRtn">流水号</param>
        /// <returns></returns>
        public string ToJson(string parmName, string dclaRtn = "")
        {
            System.Text.StringBuilder json = new System.Text.StringBuilder("{\"" + parmName + "\":[{", 1000);
            json.AppendFormat("\"psn_no\":\"{0}\",", tbx_No.Text.Trim());
            json.AppendFormat("\"biz_appy_type\":\"{0}\",", tbx_BizAppy.Text.Trim());
            json.AppendFormat("\"tel\":\"{0}\",", tbx_Phone.Text.Trim());
            json.AppendFormat("\"addr\":\"{0}\",", tbx_address.Text.Trim());
            json.AppendFormat("\"begndate\":\"{0}\",", dpk_StaDate.Text.Trim());
            json.AppendFormat("\"enddate\":\"{0}\",", dpk_EndDate.Text.Trim());
            json.AppendFormat("\"agnter_name\":\"{0}\",", tbx_AgnterName.Text.Trim());
            var agencyType = (ComboBoxItem)cbx_AgencyType.Items[cbx_AgencyType.SelectedIndex == -1 ? 0 : cbx_AgencyType.SelectedIndex];
            json.AppendFormat("\"agnter_cert_type\":\"{0}\",", agencyType.Value);
            json.AppendFormat("\"agnter_certno\":\"{0}\",", tbx_AgnterNo.Text.Trim());
            json.AppendFormat("\"agnter_tel\":\"{0}\",", tbx_AgnterTel.Text.Trim());
            json.AppendFormat("\"agnter_addr\":\"{0}\",", tbx_AgnterAddr.Text.Trim());
            json.AppendFormat("\"agnter_rlts\":\"{0}\",", tbx_AgnteRlts.Text.Trim());
            json.AppendFormat("\"fix_srt_no\":\"{0}\",", tbx_FixSrt.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 cardType = (ComboBoxItem)cbx_CardType.Items[cbx_CardType.SelectedIndex == -1 ? 0 : cbx_CardType.SelectedIndex];
            json.AppendFormat("\"psn_cert_type\":\"{0}\",", cardType.Value);
            //json.AppendFormat("\"dise_name\":\"{0}\",", cardType.Text.Trim());
            json.AppendFormat("\"certno\":\"{0}\",", tbx_IdCard.Text.Trim());
            json.AppendFormat("\"psn_name\":\"{0}\",", tbx_Name.Text.Trim());
            json.AppendFormat("\"med_trt_type\":\"{0}\",", tbx_MedType.Text.Trim());

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

            #region 拼上Iris所需

            json.AppendFormat("\"iresult\":\"\",");        //操作结果 0已上传 9已撤销 
            json.AppendFormat("\"InPut\":\"\",");          //调用入参
            json.AppendFormat("\"OutPut\":\"\",");         //调用反参

            #endregion

            json.AppendFormat("\"memo\":\"{0}\"", rtb_Remark.Text.Trim());
            json.Append("}]}");
            return json.ToString();
        }

        #region 下拉框自动选择
        /// <summary>
        /// 下拉框自动选择
        /// </summary>
        /// <param name="data">数据源（字典）</param>
        /// <param name="comBox">框体</param>
        public void ComBoxChoose(Dictionary<string, string> data, ComboBox comBox, bool drop)
        {
            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_Cancel_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}
