using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PTMedicalInsurance.Business.Core.SelfServiceMachine.Process.ReadCard
{
    class FilterPatInfo : AbstractProcess
    {
        public override CallResult Process(JObject input)
        {
            JObject joOutput = JObject.Parse(JsonHelper.getDestValue(input, "output"));

            // 日期处理
            JObject joBaseInfo = JObject.Parse(JsonHelper.getDestValue(joOutput, "baseinfo"));
            JArray joInsuInfo = JArray.Parse(JsonHelper.getDestValue(joOutput, "insuinfo"));
            joOutput["baseinfo"] = joBaseInfo;
            joOutput["insuinfo"] = joInsuInfo;
            JObject joOutparam = (JObject)input.DeepClone();
            joOutparam["output"] = joOutput;

            if (joOutput["idetinfo"] == null)
            {
                joOutput["idetinfo"] = new JArray();
            }
            // insuinfo保持转换之前的
            JArray jaInsuInfo = JArray.Parse(JsonHelper.getDestValue(joOutput, "insuinfo"));
            JObject joSelectedInsuInfo = new JObject();
            foreach (JObject jo in jaInsuInfo)
            {
                if (jo["psn_insu_stas"].ToString() != "1")
                {
                    continue;
                }

                if ((jo["insutype"].ToString() == "310") || (jo["insutype"].ToString() == "390"))
                {
                    joSelectedInsuInfo = jo;
                }
            }

            if (joSelectedInsuInfo.Count == 0)
            {
                outParam = "未获取到有效的参保信息，请到人工窗口办理相关业务！";
                return Exception(-1,"",outParam);
            }
            joSelectedInsuInfo.Add("med_type", Global.pat.medType);
            joOutparam.Property("output").AddBeforeSelf(new JProperty("selectedInsuInfo", joSelectedInsuInfo));
            joOutparam.Property("output").AddBeforeSelf(new JProperty("selectedIdInfo", new JObject()));
            //Global.writeLog($"joOutparam:{joOutparam}");
            outParam = joOutparam.ToString();

            return Success();
        }
    }
}
