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.OutPat
{
    class Settlement : AbstractProcess
    {
        public override CallResult Process(JObject input)
        {
            #region【门诊正式结算前调用社保卡验密】
            if ((Global.pat.mdtrtcertType == "03") && (Global.pat.insuplc_admdvs.Substring(0, 2) == "62"))
            {
                CardReader_GS CardRead_GS = new CardReader_GS();
                if (CardRead_GS.VerifyPIN(out outParam) != 0)
                {
                    outParam = JsonHelper.setExceptionJson(-1, "社保卡验密异常iVerifyPIN失败 ", outParam).ToString();
                    return Exception(-1, "", outParam);
                }
            }
            #endregion

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

                    return Exception(-1, "", outParam);
                }

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

            
        }
    }
}
