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.Core.SelfServiceMachine.Process.InPat
{
    class Settlement : AbstractProcess
    {

        public Settlement()
        {
            MergeOrginal = true;
        }
        public override CallResult Process(JObject input)
        {

            Global.pat.admType = 2; //住院
            JObject  joInParam = JObject.Parse(JsonHelper.getDestValue(input, "orginalInput"));
            JArray jaParams = JArray.Parse(JsonHelper.getDestValue(joInParam, "params"));
            JObject joParam = JObject.FromObject(jaParams[0]);
            JObject joSettlement = JObject.Parse(JsonHelper.getDestValue(input, "Settlement"));

            //正式结算
            joSettlement.Add("data", joSettlement);
            JObject jo2304Rtn = invoker.invokeCenterService("2304", JsonHelper.setCenterInpar("2304", joSettlement));
            if (JsonHelper.parseCenterRtnValue(jo2304Rtn, out errMsg) != 0)
            {
                outParam = JsonHelper.setExceptionJson(-1, "结算失败", errMsg).ToString();
                cBus.cancleRegister("2405", out errMsg);
                return Exception();
            }
            else
            {
                //返回给云医保平台结算信息
                if (mIS.saveSettlement(jo2304Rtn, out errMsg) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-1, "结算成功，但云医保平台保存失败", errMsg).ToString();
                    return Exception();
                }
                //返回给云医保平台结算明细信息
                if (mIS.saveSettlementDetail(jo2304Rtn, out errMsg) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-1, "云医保平台保存结算明细失败", errMsg).ToString();

                }
                //返回给HIS
                JObject joSetlinfo = JObject.Parse(JsonHelper.getDestValue(jo2304Rtn, "output.setlinfo"));
                if (hIS.returnInpatSettlementInfo(joParam, joSetlinfo, out outParam) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-1, "返回结算信息给HIS", outParam).ToString();
                    return Exception();
                }
                else
                {
                    //返回给前端
                    JObject joHisServieRtn = JObject.Parse(outParam);
                    hBus.returnToFrontEndAfterSettlement(jo2304Rtn, joHisServieRtn, out outParam);
                    outParam = JsonHelper.setIrisReturnValue(0, "结算成功", JObject.Parse(outParam)).ToString();
                    return Success();
                }
            }
        }
    }
}
