using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Entity;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PTMedicalInsurance.Business
{
    class LocalMedDirDownloadProcess : AbstractProcess
    {
        int maxNo = 0;
        /// <summary>
        /// 药品、诊疗目录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override CallResult Process(JObject input)
        {
            // sbjgbh传需要查询的社保局编号,济南医疗传370100（或37010101），工伤传37019L（或37019L01）省医保37000000
            if(!string.IsNullOrEmpty(input["ver"].Text()))
            {
                maxNo = int.Parse(input["ver"].Text());
            }
            bool hasMore = true;

            while (hasMore)
            {

                var ret = FetchDirectory(TradeEnum.DirectoryDownloadCore, "ylxm_ds", "sxzfbl_ds", "xj_ds");

                hasMore = ret.hasMore;

                updateDirectory(ret.data);

                updateLimitPrice(ret.limitData);
                // 多自费项目
                updateSelfPercent(ret.percentData);
            }

            return IrisReturn("更新成功!", null);
        }

        private void updateDirectory(JArray data)
        {
            List<HBMedInsuDirectory> list = new List<HBMedInsuDirectory>();
            try
            {
                foreach (var dir in data)
                {
                    HBMedInsuDirectory obj = ConvertToEntity((JObject)dir);
                    list.Add(obj);
                }
                // 保存
                saveToServer(list);
            }
            catch (Exception ex)
            {

            }
        }

        private JObject saveToServer(List<HBMedInsuDirectory> data)
        {
            JObject joIn = new JObject();
            JObject joRtn = new JObject();
            string outParam = "";
            try
            {

                joIn.Add("params", JArray.Parse(JsonHelper.toJsonString(data)));
                joIn.Add("code", "09010035");
                joIn.Add("updateUserID", Global.user.ID);
                InvokeHelper invoker = new InvokeHelper();
                string sInput = joIn.ToString();
                joRtn = invoker.invokeInsuService(sInput, "applyDataToIris");
                outParam = joRtn.ToString();
                return joRtn;
            }
            catch (Exception ex)
            {
                joRtn = JsonHelper.setExceptionJson(-1, "applyDataToIris", ex.Message);
                outParam = joRtn.ToString();
                return joRtn;
            }
        }

        private (bool hasMore, JArray data, JArray percentData, JArray limitData) FetchDirectory(TradeEnum trade, string dsName)
        {
            return FetchDirectory(trade,dsName,null,null);
        }

        private (bool hasMore, JArray data,JArray percentData,JArray limitData) FetchDirectory(TradeEnum trade, string dsName,string percentName,string limitName)
        {
            JObject joInput = new JObject();
            joInput["p_sxh"] = maxNo.ToString(); //全量下载0,后面传最大
            Global.pat.insuplc_admdvs = "370100";
            JObject joRtn = invoker.invokeCenterService(trade, joInput);
            if ("0".Equals(JsonHelper.getDestValue(joRtn, "resultcode")))
            {
                // 是否还有数据
                bool hasMore = "1".Equals(JsonHelper.getDestValue(joRtn, "sfjxxz"));
                JArray data = JArray.Parse(JsonHelper.getDestValue(joRtn, dsName));
                JArray percent = new JArray();
                if (!string.IsNullOrEmpty(percentName))
                {
                    percent = JArray.Parse(JsonHelper.getDestValue(joRtn, percentName));
                }
                JArray limit = new JArray();
                if (!string.IsNullOrEmpty(limitName))
                {
                    limit = JArray.Parse(JsonHelper.getDestValue(joRtn, limitName));
                }
                return (hasMore, data, percent, limit);
            }
            else
            { 
                MessageBox.Show(JsonHelper.getDestValue(joRtn, "err_msg"));
            }

            return (false, new JArray(), new JArray(), new JArray());
        }

        /// <summary>
        /// 诊断目录下载
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CallResult DownloadDiagnosis(JObject input)
        {
            //sbjgbh传需要查询的社保局编号,济南医疗传370100（或37010101），工伤传37019L（或37019L01）
            if (!string.IsNullOrEmpty(input["ver"].Text()))
            {
                maxNo = int.Parse(input["ver"].Text());
            }
            bool hasMore = true;
            while (hasMore)
            {
                var ret = FetchDirectory(TradeEnum.DirectoryDownloadCore, "ybjb_ds");
                hasMore = ret.hasMore;
                List<HBMedInsuDirectory> list = new List<HBMedInsuDirectory>();
                foreach (var d in ret.data)
                {
                    list.Add(NewDiagnosis((JObject)d));
                }
                saveToServer(list);
            }
            return IrisReturn("下载成功",null);
        }

        /// <summary>
        /// 科室查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CallResult QueryDepartment()
        {
            JObject joInput = new JObject();
            joInput["p_ksbm"] = ""; //全量下载
            Global.pat.insuplc_admdvs = "370100";
            JObject joRtn = invoker.invokeCenterService(TradeEnum.DepartmentQuery, joInput);
            if ("0".Equals(JsonHelper.getDestValue(joRtn, "resultcode")))
            {
                // 是否还有数据
                outParam = JsonHelper.getDestValue(joRtn, "dept_ds");
            }
            return Success();
        }
        private HBMedInsuDirectory NewDiagnosis(JObject obj)
        {
            HBMedInsuDirectory jsonTemp = new HBMedInsuDirectory();
            jsonTemp.updateUserID = Global.user.ID;
            jsonTemp.HospitalDr = Global.inf.hospitalDr;
            jsonTemp.InterfaceDr = Global.inf.interfaceDr;
            jsonTemp.Code = obj["jbbm"].Text();
            jsonTemp.Name = obj["jbmc"].Text();
            jsonTemp.HisType = "4";
            jsonTemp.HisTypeName = "诊断";
            jsonTemp.ValidFlag = "1".Equals(obj["zxbz"].Text()) ? 0 : 1;
            jsonTemp.Note = obj["bz"].Text();
            jsonTemp.PinyinSearchCode = obj["py"].Text();
            jsonTemp.DrugSafetyStandardCode = "";
            return jsonTemp;
        }

        private HBMedInsuDirectory ConvertToEntity(JObject obj)
        {
            string hisType = obj["ypbz"].Text() ?? "2";
            string hisTypeName = hisType.Equals("1") ? "药品" : "诊疗";             HBMedInsuDirectory insu = new HBMedInsuDirectory();

            maxNo = Math.Max(maxNo, int.Parse(obj["sxh"].ToString()));
            insu.ID = "";
            insu.updateUserID = Global.user.ID;
            insu.HospitalDr = Global.inf.hospitalDr;
            insu.InterfaceDr = Global.inf.interfaceDr;
            insu.Code = obj["ylxmbm"].Text();
            insu.Name = obj["ylxmbzmc"].Text();
            insu.NationalCode = obj["gbxmbm"].Text();
            insu.NationalName = obj["gbxmmc"].Text();
            insu.HisType = hisType;
            insu.HisTypeName = hisTypeName;
            insu.LocateCode = obj["pms_id"].Text();
            insu.LocateName = obj["pms_name"].Text();
            insu.DosageFormCode = obj["jxm"].Text();
            insu.DosageFormName = obj["jxm"].Text();
            insu.CategoryCode = obj["listtype"].Text();
            insu.CategoryName = "";
            // 规格
            insu.Specification = obj["bzgg"].Text();
            insu.SpecificationCode = obj["gg"].Text();
            insu.UnitOfPackag = obj["dw"].Text();
            insu.UnitOfValuation = obj["ms_charge_unit"].Text();
            //insu.StartDate = obj["qsrq"].Text();
            //insu.EndDate = obj["zzrq"].Text();
            insu.PinyinSearchCode = obj["py"].Text();
            insu.Instructions = obj["ms_explain"].Text();
            insu.ExceptContent = obj["cwnr"].Text();
            insu.Connotation = obj["xmnh"].Text();    
            insu.ValidFlag = obj["spbz"].Int();
            insu.Note = "";
            insu.VersionNO = obj["sxh"].Text();
            insu.VersionName = obj["sxh"].Text();
            string cancelFlag = obj["zxbz"].Text();
            insu.UseFlag = "1".Equals(cancelFlag)?0:1;
            insu.DrugSafetyStandardCode = obj["ypbwm"].Text();
            insu.ApprovalNO = obj["bzwh"].Text(); ;
            //insu.SpecialFlag = obj[""].Int();
            //insu.LimitFlag = obj[""].Int();
            //insu.LimitRange = obj[""].Text();
            insu.UniqueRecordNO = obj["sxh"].Text();
            insu.Manufacturers = obj["scqy"].Text();
            insu.SelfPercent = obj["zfbl"].Text(); 
            insu.ChargeItemLevelName = obj["mldj"].Text();
            insu.MinPackagingQuantity = obj["zxbzsl"].Text();
            insu.MinPackagingUnit = obj["gjjzxbzdw"].Text();

            insu.UpdateTime = obj["gxsj"].Text();

            if (insu.SelfPercent == "100")
            {
                insu.ChargeItemLevel = "01";
                insu.ChargeItemLevelName = "甲";
            }
            else if (insu.ChargeItemLevelName == "0")
            {
                insu.ChargeItemLevel = "03";
                insu.ChargeItemLevelName = "丙";
            }
            else
            {
                insu.ChargeItemLevel = "02";
                insu.ChargeItemLevelName = "乙";
            }

            return insu;
        }

        private int updateLimitPrice(JArray data)
        {
            if (data?.Count < 1) return 0;
            string errMsg = "";
            JArray joArray = new JArray();

            try
            {
                foreach (var dir in data)
                {
                    dynamic joTmp = new JObject();
                    joTmp.HospitalDr = Global.inf.hospitalDr;
                    joTmp.InterfaceDr = Global.inf.interfaceDr;
                    joTmp.updateUserID = Global.user.ID;
                    joTmp.Code = dir["ylxmbm"].Text();

                    joTmp.PersonnelType = dir["rqlb"].Text();  //人群类别
                    joTmp.LimitType = dir["yltclb"].Text();     //限价类型（统筹类别）
                    joTmp.BeginDate = Utils.ConvertShortDate(dir["qsrq"].Text());
                    joTmp.EndDate = Utils.ConvertShortDate(dir["zzrq"].Text());
                    joTmp.UpLimitAmount = dir["xj"].Text(); //限价
                    joArray.Add(joTmp);
                }
                JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("09010084", joArray).ToString(), "更新限价信息");

                if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                {
                    return -1;
                }
                else
                {
                    outParam = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outParam = "更新项目自费比例：" + ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 如果存在同一个目录多个比例，则保存在比例扩展表
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private int updateSelfPercent(JArray data)
        {
            if (data?.Count < 1) return 0;
            string errMsg = "";
            JArray joArray = new JArray();
            
            try
            {
                foreach (var dir in data)
                {
                    dynamic joTmp = new JObject();
                    joTmp.HospitalDr = Global.inf.hospitalDr;
                    joTmp.InterfaceDr = Global.inf.interfaceDr;
                    joTmp.updateUserID = Global.user.ID;
                    joTmp.Code = dir["ylxmbm"].Text();
                    string personType = dir["rqlb"].Text(); //人群类别
                    if (string.IsNullOrEmpty(personType))
                    {
                        personType = "A"; //职工
                    }
                    joTmp.PersonnelType = personType;
                    string proportionType = dir["yltclb"].Text(); //自费类型（统筹类别）
                    if (string.IsNullOrEmpty(personType))
                    {
                        proportionType = "6"; //普通门诊
                    }
                    joTmp.ProportionType = proportionType;
                    joTmp.BeginDate = Utils.ConvertShortDate(dir["qsrq"].Text());
                    joTmp.EndDate = Utils.ConvertShortDate(dir["zzrq"].Text());
                    joTmp.Proportion = dir["sxzfbl"].Text();
                    joArray.Add(joTmp);
                 }
                JObject joRtn = invoker.invokeInsuService(JsonHelper.setIrisInpar("09010085", joArray).ToString(), "更新项目自费比例");

                if (JsonHelper.parseIrisRtnValue(joRtn, out errMsg) != 0)
                {
                    return -1;
                }
                else
                {
                    outParam = joRtn.ToString();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                outParam = "更新项目自费比例：" + ex.Message;
                return -1;
            }
        }
    }
}
