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

import com.alibaba.fastjson.JSON;
import com.engine.htsc.payment.enums.BudgetWF;
import com.engine.htsc.payment.pojo.BxBudgetDTO;
import com.engine.htsc.payment.pojo.WbLog;
import com.engine.htsc.payment.service.BudgetCommand;
import com.engine.htsc.payment.service.BudgetStrategy;
import com.engine.htsc.payment.service.ClBxBudgetService;
import com.engine.htsc.payment.util.AssertUtil;
import com.engine.htsc.payment.util.BizUtils;
import com.engine.htsc.payment.util.BudgetStrategyFactory;
import com.engine.htsc.payment.util.IpUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.util.Arrays;
import java.util.Map;

public class HeadClBxBudgetCommand implements BudgetCommand {
    private final Log log = LogFactory.getLog(HeadClBxBudgetCommand.class);

    private final BudgetStrategy<BxBudgetDTO> bg = BudgetStrategyFactory.getClBxBudgetStrategyForPayment(
            BudgetWF.CLBXBUDGET.getCode());

    ClBxBudgetService clBxBudgetService = new ClBxBudgetServiceImpl();

    @Override
    public String submit(String requestNo, String billStatus) throws Exception {
        assert bg != null;
        BizUtils bizUtils = new BizUtils();
        BxBudgetDTO budgetDTO = bg.buildNewBudgetParamFromWorkflowDB(requestNo, billStatus);
        Map<String, Object> stringObjectMap = bizUtils.convertDtoToMap(budgetDTO);
        String table = bizUtils.getTableNameByRequestId(requestNo);
//        String yskmTable = table + "_dt8";
        String wbYskmTable = table + "_dt9";
        log.info("\n 执行总部差旅报销预算 >>> 当前状态submit");
        log.info("\n 调用预算参数(状态:" + billStatus + ") >>> \n " + JSON.toJSONString(stringObjectMap));
        //记录日志信息
        WbLog wbLog = new WbLog();
        DateTime today = new DateTime();
        wbLog.setRequestNo(requestNo);
        wbLog.setTime(today.toString("yyyy-MM-dd HH:mm:ss"));
        wbLog.setUrl(String.format("%s/cwbase/JTGL/BudgetProcess.asmx?wsdl",
                Util.null2String(new PropBean().getPropName("budgetIp"))));
        wbLog.setMethod("weaver.interfaces.htsc.cus.HTUtil.budgetCommit");
        wbLog.setIp(IpUtils.getHostIp());
        try {
            String resp = new HTUtil().budgetCommit(stringObjectMap);
            log.info("\n 调用预算返回(状态:" + billStatus + ") >>> \n " + resp);
            //更新预算记录表,记录入参
            bizUtils.refreshBudgetRecord(requestNo, billStatus, JSON.toJSONString(budgetDTO), "0");

//            boolean b = bizUtils.updateBudgetMidTable(requestNo, billStatus);
            boolean isUpdate = clBxBudgetService.doBudgetMiddleTable(budgetDTO.getBillName(), billStatus,null, Arrays.asList(wbYskmTable), table);
            log.info("\n 调用预算更新中间表返回 >>> \n " + isUpdate);
            //记录日志
            wbLog.setResponse(resp);
            if ("F1001".equals(resp)) {
                wbLog.setResult("预算成功");
            } else {
                wbLog.setResult("预算失败,返回值:" + resp);
            }
            wbLog.setRequest(JSON.toJSONString(stringObjectMap));
            return resp; //F1001
        } catch (Exception e) {
            //记录日志
            wbLog.setResponse("");
            wbLog.setResult("预算失败");
            wbLog.setRequest(JSON.toJSONString(stringObjectMap));
            throw new Exception("预算失败");
        } finally {
            BizUtils.saveLog(wbLog);
        }
    }

    @Override
    public String reSubmit(String requestNo) throws Exception {
        String reject = reject(requestNo);
        if ("F1001".equalsIgnoreCase(reject)) {
            return submit(requestNo, "3"); //重新预占
        } else {
            return reject;
        }
    }

    @Override
    public String reject(String requestNo) throws Exception {
        assert bg != null;
        BizUtils bizUtils = new BizUtils();
        BxBudgetDTO lastBudgetDTO = bg.getLastBudgetParamFromModeDB(requestNo, "0");
        if (AssertUtil.isEmpty(lastBudgetDTO)) {
            // 为不影响后面的逻辑,默认返回成功F1001
            log.info(String.format("UF_YSJLB无requestno=%s的预算数据", requestNo));
            return "F1001";
        }
        String table = bizUtils.getTableNameByRequestId(requestNo);
        //总部差旅报销，只用到明细表9
//        String yskmTable = table + "_dt8";
        String wbYskmTable = table + "_dt9";
        log.info("\n 从建模表中获取的参数@ \n" + JSON.toJSONString(lastBudgetDTO));
        lastBudgetDTO.setBillStatus("2"); //回退
        Map<String, Object> stringObjectMap = bizUtils.convertDtoToMap(lastBudgetDTO);
        log.info("\n 执行总部通用付款预算 >>> 当前状态reject");
        log.info("\n 调用预算参数(回退) >>> \n " + JSON.toJSONString(stringObjectMap));
        //记录日志信息
        WbLog wbLog = new WbLog();
        DateTime today = new DateTime();
        wbLog.setRequestNo(requestNo);
        wbLog.setTime(today.toString("yyyy-MM-dd HH:mm:ss"));
        wbLog.setUrl(String.format("%s/cwbase/JTGL/BudgetProcess.asmx?wsdl",
                Util.null2String(new PropBean().getPropName("budgetIp"))));
        wbLog.setMethod("weaver.interfaces.htsc.cus.HTUtil.budgetCommit");
        wbLog.setIp(IpUtils.getHostIp());
        try {
            String resp = new HTUtil().budgetCommit(stringObjectMap);
            bizUtils.refreshBudgetRecord(requestNo, "2", JSON.toJSONString(lastBudgetDTO), "0");
            log.info("\n 调用预算返回(回退) >>> \n " + resp);
            //更新中间表 不是通用表
            boolean isUpdate = clBxBudgetService.doBudgetMiddleTable(lastBudgetDTO.getBillName(), "2",null, Arrays.asList(wbYskmTable), table);
//            boolean b = bizUtils.updateBudgetMidTable(requestNo, "2");
            log.info("\n 调用预算更新中间表返回(回退) >>> \n " + isUpdate);
            //记录日志
            wbLog.setResponse(resp);
            wbLog.setResult("预算成功");
            wbLog.setRequest(JSON.toJSONString(stringObjectMap));
            return resp;
        } catch (Exception e) {
            //记录日志
            wbLog.setResponse("");
            wbLog.setResult("预算失败");
            wbLog.setRequest(JSON.toJSONString(stringObjectMap));
            throw new Exception("预算失败");
        } finally {
            BizUtils.saveLog(wbLog);
        }

    }

    @Override
    public String finish(String requestNo) throws Exception {
        return submit(requestNo, "1");
    }
}
