using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common;
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
{
    class ProcessManager
    {
        private List<AbstractProcess> Processes { get; set; }

        public ProcessManager()
        {
            Processes = new List<AbstractProcess>();
        }

        public ProcessManager(List<AbstractProcess> processes)
        {
            Processes = processes;
        }

        /// <summary>
        /// 增加单个处理流程
        /// </summary>
        /// <param name="process"></param>
        public ProcessManager Add(AbstractProcess process)
        {
            Processes.Add(process);
            return this;
        }

        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string Run(JObject input)
        {
            JObject orginalInput = (JObject)input?.DeepClone();
            string data = "";
            int code = 0;

            // 按顺序执行业务
            foreach (var process in Processes)
            {
                if (process.UseOrginal) {
                    process.OrginalInput = orginalInput;
                    input = orginalInput;   //原始参数
                }

                if (process.MergeOrginal)
                {
                    //process.OrginalInput = orginalInput;
                    input.Add("orginalInput", orginalInput);   //原始参数
                }
                var ret = process.Process(input);

                data = ret.Data;
                code = ret.Code;
                if (code < 0)
                {
                    //异常
                    if (string.IsNullOrEmpty(data))
                    {
                        data = ret.ErrMsg;
                    }
                    break;
                }
                if (!string.IsNullOrEmpty(data))
                {
                    input = JObject.Parse(data);
                }
            }

            JObject rtn = JObject.Parse(data);
            //返回值检测(兼容）
            if (!rtn.ContainsKey("errorCode"))
            {
                rtn = JsonHelper.setIrisReturnValue(code, "",rtn);
                Global.writeLog("异常返回值检测", data, rtn.ToString());
            }

            return rtn.ToString();
        }

    }
}
