package com.awspaas.user.apps.donenow_ctt.controller;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.Logger;
import com.awspaas.user.apps.donenow_ctt.service.contractService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同创建时，使用的接口
 */
@Controller
public class contractCreateController {
    private static final Logger contractLogger = SDK.getLogAPI().getLogger(contractCreateController.class);//记录日志

    /**
     * 提交合同
     * @param uc
     * @param bindid
     * @return
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_ctt.contract_submit")
    public ResponseObject contractSubmit(UserContext uc, String bindid) {

        contractLogger.info("contractLogger.info 合同提交后---------------" + bindid);

        Map<String, Object> result = contractService.getInstance().SaveContract(uc, bindid, true);//保存合同


        if (result.getOrDefault("success", false).equals(true)) {


        } else {
            return ResponseObject.newErrResponse("保存失败！");
        }


        return ResponseObject.newOkResponse("保存成功！");
    }

    /**
     * 获取合同详情
     * @param uc
     * @param bindid
     * @return
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_ctt.get_contractapply")
    public ResponseObject getContractApply(UserContext uc, String bindid) {

        RowMap contractDetail = DBSql.getMap("SELECT ID,BINDID,PROCESSDEFID FROM BO_EU_DNCTT_CONTRACT WHERE BINDID=? ", new Object[]{bindid});
        if (contractDetail == null || contractDetail.isEmpty())
            contractDetail = DBSql.getMap("SELECT ID,BINDID,PROCESSDEFID FROM BO_EU_DNCTT_CONTRACT_APPLY WHERE BINDID=? ", new Object[]{bindid});

        ResponseObject responseObject = ResponseObject.newOkResponse();

        responseObject.setData(contractDetail);

        return responseObject;
    }

    /**
     * 删除合同
     * @param uc
     * @param bindid
     * @return
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_ctt.contract_delete")
    public ResponseObject contractDelete(UserContext uc, String bindid, String id) throws SQLException {

        int cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNPRO_PROJECT WHERE CONTRACT_ID=? AND CLOSED=0", new Object[]{id});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同关联了" + cnt + "个项目，无法删除！");
        }
        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNSDK_TASK WHERE CONTRACT_ID=? AND CLOSED=0", new Object[]{id});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同关联了" + cnt + "个任务，无法删除！");
        }
        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNCRM_INSTALLED_PRODUCT WHERE CONTRACT_ID=? AND CLOSED=0", new Object[]{id});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同关联了" + cnt + "个产品，无法删除！");
        }
        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNCTT_CONTRACT_COST WHERE CONTRACT_ID=? AND CLOSED=0", new Object[]{id});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同关联了" + cnt + "个合同成本，无法删除！");
        }
        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNCRM_ACCOUNT_DEDUCTION WHERE CONTRACT_ID=? AND CLOSED=0", new Object[]{id});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同关联了" + cnt + "个已计费条目，无法删除！");
        }
        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNSDK_WORK_ENTRY WHERE CONTRACT_ID=? AND CLOSED=0", new Object[]{id});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同关联了" + cnt + "个工时，无法删除！");
        }

        //如果服务已经审批并提交，则不能删除
        //合同初始费用审批
        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNCTT_CONTRACT WHERE (ID=? OR BINDID=?) AND SETUP_FEE!=0 AND SETUP_FEE IS NOT NULL AND CLOSED=0", new Object[]{id, bindid});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同合同初始费用已审批并提交，无法删除！");
        }

        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNCTT_CONTRACT_SERVICE_ADJUST WHERE (CONTRACT_ID=? OR BINDID=?) AND APPROVE_AND_POST_DATE IS NOT NULL AND CLOSED=0", new Object[]{id, bindid});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同服务已审批并提交，无法删除！");
        }

        cnt = DBSql.getInt("SELECT COUNT(0) FROM BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD WHERE (CONTRACT_ID=? OR BINDID=?) AND APPROVE_AND_POST_DATE IS NOT NULL AND CLOSED=0", new Object[]{id, bindid});
        if (cnt > 0) {
            return ResponseObject.newErrResponse("该合同服务已审批并提交，无法删除！");
        }


        Connection conn = null;
        try {
            conn = DBSql.open();
            conn.setAutoCommit(false);

            Map<String, Object> params = new HashMap<>();
            params.put("CONTRACT_ID", id);
            params.put("BINDID", bindid);
            //软删除
            updateContractCLOSED(uc, "BO_EU_DNCTT_CONTRACT_RATE", params, conn);
            updateContractCLOSED(uc, "BO_EU_DNCTT_CONTRACT_MILESTONE", params, conn);
            updateContractCLOSED(uc, "BO_EU_DNCTT_CONTRACT_SERVICE", params, conn);
            updateContractCLOSED(uc, "BO_EU_DNCTT_CONTRACT_COST_DEFAULT", params, conn);

            updateContractCLOSED(uc, "BO_EU_DNCTT_CONTRACT_SERVICE_ADJUST", params, conn);
            updateContractCLOSED(uc, "BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD", params, conn);

            List<BO> SBSboList = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_SERVICE_BUNDLE_SERVICE").addQuerySqlWhere(" CONTRACT_SERVICE_ID IN (SELECT ID FROM BO_EU_DNCTT_CONTRACT_SERVICE WHERE (CONTRACT_ID=:CONTRACT_ID OR BINDID=:BINDID))  AND CLOSED=0", params).list();
            for (BO bo : SBSboList) {
                bo.set("CLOSED", 1);
                SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_SERVICE_BUNDLE_SERVICE", bo, conn);
            }

            List<BO> SABSboList = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_SERVICE_ADJUST_BUNDLE_SERVICE").addQuerySqlWhere(" CONTRACT_SERVICE_ADJUST_ID IN (SELECT ID FROM BO_EU_DNCTT_CONTRACT_SERVICE_ADJUST WHERE (CONTRACT_ID=:CONTRACT_ID OR BINDID=:BINDID))  AND CLOSED=0", params).list();
            for (BO bo : SABSboList) {
                bo.set("CLOSED", 1);
                SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_SERVICE_ADJUST_BUNDLE_SERVICE", bo, conn);
            }

            List<BO> SPBSboList = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD_BUNDLE_SERVICE").addQuerySqlWhere(" CONTRACT_SERVICE_PERIOD_ID IN (SELECT ID FROM BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD WHERE (CONTRACT_ID=:CONTRACT_ID OR BINDID=:BINDID))  AND CLOSED=0", params).list();
            for (BO bo : SPBSboList) {
                bo.set("CLOSED", 1);
                SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_SERVICE_BUNDLE_SERVICE", bo, conn);
            }

            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            if (conn != null && !conn.isClosed())
                conn.rollback();
        } finally {
            if (conn != null)
                DBSql.close(conn);
        }
        return ResponseObject.newOkResponse();
    }


    /**
     * 关闭合同相关
     * @param uc
     * @param boName
     * @param params
     * @param conn
     */
    private void updateContractCLOSED(UserContext uc, String boName, Map<String, Object> params, Connection conn) {
        List<BO> boList = SDK.getBOAPI().query(boName).addQuerySqlWhere(" (CONTRACT_ID=:CONTRACT_ID OR BINDID=:BINDID) AND CLOSED=0", params).list();
        for (BO bo : boList) {
            bo.set("CLOSED", 1);//关闭
            SDK.getBOAPI().update(boName, bo, conn);
        }
    }


}
