package com.engine.htsc.branchpayment.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.branchpayment.enums.OperateMsg;
import com.engine.htsc.branchpayment.pojo.UfCash;
import com.engine.htsc.branchpayment.service.BranchPaymentService;
import com.engine.htsc.branchpayment.utils.BranchBizUtil;
import com.engine.htsc.payment.pojo.CostAccountDto;
import com.engine.htsc.payment.service.BudgetCommand;
import com.engine.htsc.payment.util.BizUtils;
import com.engine.htsc.payment.util.PayUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.cus.HTUtil;

import java.text.SimpleDateFormat;
import java.util.*;

public class BranchPaymentServiceImpl extends Service implements BranchPaymentService {

  @Override
  public Map<String, String> doPaymentByBatchId(String ids) throws Exception {
    Assert.notBlank(ids, "同步预算数据id为空");

    RecordSet rs = new RecordSet();
    rs.writeLog(String.format("同步付款数据， ids: %s", ids));

    BranchBizUtil biz = new BranchBizUtil();
    HTUtil ht = new HTUtil();
    List<UfCash> ufCashList = biz.getUfCashList(ids, BranchBizUtil.FZJG);

    Map<String, String> resp = new HashMap<>();
    for (UfCash cash : ufCashList) {
      if ("2".equals(cash.getFkzt())) {
        resp.put(cash.getrMark(), "流程已废弃,无法付款");
        continue;
      }

      //预算
      BudgetCommand command = BranchBudgetCommandFactory.getBudgetCommand(cash.getType());
      try {
        String finish = Objects.requireNonNull(command).finish(cash.getRid());
        resp.put(cash.getrMark(), OperateMsg.BUDGET_SUCCESS.getMsg("返回值：" + finish));
        //更新预算状态
        if ("F1001".equalsIgnoreCase(finish)) {
          biz.updateBudgetStatus(cash.getId(), "1", BranchBizUtil.FZJG);
        }
      } catch (Exception e) {
        rs.writeLog(e);
        resp.put(cash.getrMark(), String.join(",",
                OperateMsg.BUDGET_FAIL.getMsg("异常消息：" + e.getMessage()),
                OperateMsg.PAY_FAIL.getMsg()));
        throw new Exception("预算执行失败，抛出异常：" + e.getMessage());
      }

      //核算
      try {
        CostAccountDto costAccountDto = BranchCostDTOFactory.getCostDTOByType(cash.getRid(), cash.getType());
        //分支机构通用付款 0 ,分支机构通用报销 1,分支机构差旅报销 2 新增djsl,zzdjsl单据数量和纸质单据数量
        if ("0".equals(cash.getType())||"1".equals(cash.getType())||"2".equals(cash.getType())){
          BizUtils bizUtils = new BizUtils();
          String workFlowTableName = bizUtils.getTableNameByRequestId(cash.getRid());
          String sql = "select t1.djsl,t1.zzdjsl from "+workFlowTableName+" t1 where t1.requestid = ?";
          rs.executeQuery(sql, cash.getRid());
          if (rs.next()){
            String djsl = Util.null2String(rs.getString("djsl")); //单据数量
            String zzdjsl = Util.null2String(rs.getString("zzdjsl")); //纸质单据数量
            costAccountDto.setDjsl(djsl);
            costAccountDto.setZzdjsl(zzdjsl);
          }
        }
        String costAccountDtoJsonStr = JSON.toJSONString(costAccountDto);
        @SuppressWarnings("unchecked")
        Map<String, Object> costDtoMap = JSONObject.parseObject(costAccountDtoJsonStr);
        rs.writeLog(String.format("核算入参，%s", costDtoMap));
        String response = ht.saveFydj(costDtoMap);
        if ("success".equalsIgnoreCase(response)) {
          resp.put(cash.getrMark(), OperateMsg.PAY_SUCCESS.getMsg());
          //更新核算状态
          biz.updateCostStatus(cash.getId(), cash.getRid(), BranchBizUtil.FZJG);
          //更新合同信息
          if ("4".equals(cash.getType())){
            PayUtil.updatePaymentInfoListToHuaTai(cash.getRid());
          }else {
            PayUtil.updatePaymentInfoToHuaTai(cash.getRid());
          }
        } else {
          resp.put(cash.getrMark(), String.join(",", OperateMsg.BUDGET_SUCCESS.getMsg(),
                  OperateMsg.ACCOUNTING_FAIL.getMsg("返回值：" + response),
                  OperateMsg.PAY_FAIL.getMsg()));
        }
      } catch (Exception e) {
        rs.writeLog(e);
        resp.put(cash.getrMark(), String.join(",", OperateMsg.BUDGET_SUCCESS.getMsg(),
                OperateMsg.ACCOUNTING_FAIL.getMsg("异常消息：" + e.getMessage()),
                OperateMsg.PAY_FAIL.getMsg()));
      }

    }

    return resp;
  }

  @Override
  public Map<String, String> doBudgetByBatchId(String ids, String isDiscard) throws Exception {
    Assert.notBlank(ids, "同步预算数据id为空");
    Assert.notBlank(isDiscard, "同步预算状态为空");

    RecordSet rs = new RecordSet();
    rs.writeLog(String.format("同步预算数据，ids: %s; discard:%s, (-1为废弃)", ids, isDiscard));

    BranchBizUtil biz = new BranchBizUtil();
    List<UfCash> ufCashList = biz.getUfCashList(ids, BranchBizUtil.FZJG);

    Map<String, String> resp = new HashMap<>();
    for (UfCash uf : ufCashList) {
      if ("2".equals(uf.getFkzt())) {
        resp.put(uf.getrMark(), "流程已废弃,无法付款");
        continue;
      }
      if ("0".equals(uf.getTbdlcyszt())) {
        resp.put(uf.getrMark(), "预算已经同步，禁止再次提交");
        continue;
      }
      BudgetCommand command = BranchBudgetCommandFactory.getBudgetCommand(uf.getType());
      try {
        String finish = "";
        if ("1".equals(isDiscard)) {
          finish = Objects.requireNonNull(command).finish(uf.getRid());
          resp.put(uf.getrMark(), OperateMsg.BUDGET_SUCCESS.getMsg("返回值：" + finish));
        } else if ("-1".equals(isDiscard)) {
          finish = Objects.requireNonNull(command).reject(uf.getRid());
          resp.put(uf.getrMark(), OperateMsg.BUDGET_CANCEL_SUCCESS.getMsg("返回值：" + finish));
          //废弃后更新发票关联关系: uf_pjxxgl 浪潮
          BizUtils bizUtils = new BizUtils();
          bizUtils.cancelInvLink(uf.getRid());
        }
        //更新预算状态
        if ("F1001".equalsIgnoreCase(finish)) {
          biz.updateBudgetStatus(uf.getId(), isDiscard, BranchBizUtil.FZJG);
        }
      } catch (Exception e) {
        rs.writeLog(e);
        resp.put(uf.getrMark(), OperateMsg.BUDGET_FAIL.getMsg("异常消息：" + e.getMessage()));
      }

    }
    return resp;
  }

  @Override
  public Map<String, String> doAccountByBatchId(String ids) throws Exception {
    Assert.notBlank(ids, "同步核算id为空");

    RecordSet rs = new RecordSet();
    HTUtil ht = new HTUtil();
    rs.writeLog(String.format("同步核算数据ids：%s", ids));

    BranchBizUtil biz = new BranchBizUtil();
    List<UfCash> ufCashList = biz.getUfCashList(ids, BranchBizUtil.FZJG);

    Map<String, String> resp = new HashMap<>();
    for (UfCash uf : ufCashList) {
      if ("2".equals(uf.getFkzt())) {
        resp.put(uf.getrMark(), "流程已废弃,无法付款");
        continue;
      }
      try {
        CostAccountDto costAccountDto = BranchCostDTOFactory.getCostDTOByType(uf.getRid(), uf.getType());
        //分支机构通用付款 0 ,分支机构通用报销 1,分支机构差旅报销 2 新增djsl,zzdjsl单据数量和纸质单据数量
        if ("0".equals(uf.getType())||"1".equals(uf.getType())||"2".equals(uf.getType())){
          BizUtils bizUtils = new BizUtils();
          String workFlowTableName = bizUtils.getTableNameByRequestId(uf.getRid());
          String sql = "select t1.djsl,t1.zzdjsl from "+workFlowTableName+" t1 where t1.requestid = ?";
          rs.executeQuery(sql, uf.getRid());
          if (rs.next()){
            String djsl = Util.null2String(rs.getString("djsl")); //单据数量
            String zzdjsl = Util.null2String(rs.getString("zzdjsl")); //纸质单据数量
            costAccountDto.setDjsl(djsl);
            costAccountDto.setZzdjsl(zzdjsl);
          }
        }
        String costAccountDtoJsonStr = JSON.toJSONString(costAccountDto);
        @SuppressWarnings("unchecked")
        Map<String, Object> costDtoMap = JSONObject.parseObject(costAccountDtoJsonStr);
        rs.writeLog(String.format("核算入参，%s", costDtoMap));
        String response = ht.saveFydj(costDtoMap);
        if ("success".equalsIgnoreCase(response)) {
          resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_SUCCESS.getMsg());
          //更新核算状态
          biz.updateCostStatus(uf.getId(), uf.getRid(), BranchBizUtil.FZJG);
          //更新入账时间字段
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
          String rzsj = sdf.format(new Date());
          rs.executeUpdate("update uf_fzjgfk set rzsj = '"+rzsj+"' where id=" + uf.getId());
          //更新合同信息
          if ("4".equals(uf.getType())){
            PayUtil.updatePaymentInfoListToHuaTai(uf.getRid());
          }else {
            PayUtil.updatePaymentInfoToHuaTai(uf.getRid());
          }
        } else {
          resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_FAIL.getMsg("返回值：" + response));
        }
      } catch (Exception e) {
        rs.writeLog(e);
        resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_FAIL.getMsg("异常消息：" + e.getMessage()));
      }
    }
    return resp;
  }

  @Override
  public String updateManualPaymentStatus(String rids) {
    BranchBizUtil bizUtil = new BranchBizUtil();
    return bizUtil.updateManualPaymentStatus(rids, BranchBizUtil.FZJG);
  }


}
