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

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.listener.ListenerConst;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.awspaas.user.apps.donenow_ctt.service.contractService;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class contractCreateFormAfterSave extends ExecuteListener {

    public String getDescription() {
        return "合同创建保存后事件";
    }

    public String getProvider() {
        return "";
    }

    public String getVersion() {
        return "1.0";
    }

    private final String[] excludesArray = new String[]{"ID", "ORGID", "BINDID", "CREATEDATE", "CREATEUSER", "UPDATEDATE", "UPDATEUSER", "PROCESSDEFID", "ISEND"};

    /**
     * 保存合同
     * @param processExecutionContext
     * @throws Exception
     */
    @Override
    public void execute(ProcessExecutionContext processExecutionContext) throws Exception {
        String bindid = processExecutionContext.getProcessInstance().getId();
        String boName = processExecutionContext.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_BONAME);
        if (boName.equals("BO_EU_DNCTT_CONTRACT") && processExecutionContext.getProcessInstance().getProcessDefId().equals("obj_4bac3fd23814406c8d224ef2094ac274"))
            contractService.getInstance().SaveContract(processExecutionContext.getUserContext(), bindid, false);//保存合同

        //合同上面服务子表
        if (boName.equals("BO_EU_DNCTT_CONTRACT_SERVICE") && processExecutionContext.getProcessInstance().getProcessDefId().equals("obj_4bac3fd23814406c8d224ef2094ac274")) {
            System.out.println("保存合同服务--BO_EU_DNCTT_CONTRACT_SERVICE");

            //2025年11月3日 去除服务保存后自动生成服务周期
            /*
            BO formData = (BO) processExecutionContext.getParameter(ListenerConst.FORM_EVENT_PARAM_FORMDATA);
            if (formData != null)
                formData = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_SERVICE", formData.getId());
            if (formData != null) {
                Connection conn = null;
                try {
                    conn = DBSql.open();
                    conn.setAutoCommit(false);
                    BO contractBO = SDK.getBOAPI().getByProcess("BO_EU_DNCTT_CONTRACT", bindid);
                    if (contractBO == null)
                        contractBO = SDK.getBOAPI().getByProcess("BO_EU_DNCTT_CONTRACT_APPLY", bindid);
                    RowMap dto = new RowMap(contractBO.asMap());

                    //2025年10月30日 修改新增服务
                    contractService.getInstance().AddService(processExecutionContext.getUserContext(), conn, dto, formData);

                    contractService.getInstance().AddContractServiceProduct(processExecutionContext.getUserContext(), dto, conn);//新增服务或者服务包--关联产品

                    conn.commit();
                } catch (SQLException e) {

                    e.printStackTrace();
                    conn.rollback();

                } finally {
                    if (conn != null)
                        DBSql.close(conn);
                }
            }

             */

        }


        //新增服务
        if (boName.equals("BO_EU_DNCTT_CONTRACT_SERVICE") && processExecutionContext.getProcessInstance().getProcessDefId().equals("obj_58693e03feac4879901430440b42efd9")) {
            System.out.println("保存合同服务--BO_EU_DNCTT_CONTRACT_SERVICE");
            //2025年11月3日 去除服务保存后自动生成服务周期
            /*

            BO formData = (BO) processExecutionContext.getParameter(ListenerConst.FORM_EVENT_PARAM_FORMDATA);
            if (formData != null)
                formData = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_SERVICE", formData.getId());
            if (formData != null) {
                Connection conn = null;
                try {
                    conn = DBSql.open();
                    conn.setAutoCommit(false);

                    BO contractBO = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT", formData.getString("CONTRACT_ID"));
                    // formData.set("BINDID", contractBO.getBindId());
                    // SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_SERVICE", formData);

                    RowMap dto = new RowMap(contractBO.asMap());

                   // contractService.getInstance().AddServiceServiceBundleOne(processExecutionContext.getUserContext(), conn, dto, formData);//保存合同

                    //2025年10月30日 修改新增服务
                   contractService.getInstance().AddService(processExecutionContext.getUserContext(), conn, dto, formData);//保存合同

                    contractService.getInstance().AddContractServiceProduct(processExecutionContext.getUserContext(), dto, conn);//新增服务或者服务包--关联产品


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


             */

            String CONTRACT_ID = DBSql.getString("select CONTRACT_ID from BO_EU_DNCTT_CONTRACT_SERVICE where BINDID=?", new Object[]{bindid});
            try {
                //新增服务后，根据服务的月成本、月收入 计算月利润
                String profit = DBSql.getString("SELECT (SUM(UNIT_PRICE_MONTH)-SUM(UNIT_COST_MONTH))/SUM(UNIT_COST_MONTH) FROM BO_EU_DNCTT_CONTRACT_SERVICE WHERE CONTRACT_ID=? ", new Object[]{CONTRACT_ID});
                RowMap contractBO = DBSql.getMap("select MINIMUM_PROFIT_MARGIN,ALLOW_COMMISSION_PAYMENT from BO_EU_DNCTT_CONTRACT where ID=?", new Object[]{CONTRACT_ID});
                Double profitMargin = contractBO.getDouble("MINIMUM_PROFIT_MARGIN");
                int ALLOW_COMMISSION_PAYMENT = 0;
                if (profitMargin == null && StringUtils.isNotBlank(profit)) {
                    if (Double.parseDouble(profit) * 100 >= profitMargin) {
                        ALLOW_COMMISSION_PAYMENT = 1;
                    }
                }
                DBSql.update("update BO_EU_DNCTT_CONTRACT set ALLOW_COMMISSION_PAYMENT=? where ID=?", new Object[]{ALLOW_COMMISSION_PAYMENT, CONTRACT_ID});
            } catch (Exception e) {
                e.printStackTrace();

                DBSql.update("update BO_EU_DNCTT_CONTRACT set ALLOW_COMMISSION_PAYMENT=0 where ID=?", new Object[]{CONTRACT_ID});
            }
        }

        //修改服务
        if (boName.equals("BO_EU_DNCTT_CONTRACT_SERVICE_EDIT") && processExecutionContext.getProcessInstance().getProcessDefId().equals("obj_e4b0c7ae587c406b808f3a4785f05e23")) {
            System.out.println("保存合同服务--BO_EU_DNCTT_CONTRACT_SERVICE");
            BO formData = (BO) processExecutionContext.getParameter(ListenerConst.FORM_EVENT_PARAM_FORMDATA);


            if (formData != null)
                formData = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_SERVICE_EDIT", formData.getId());

            String IS_EFFECTIVE = formData.getString("IS_EFFECTIVE");
            if (!IS_EFFECTIVE.equals("未执行"))
                return;

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

                    //  BO contractServiceBO = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_SERVICE", formData.getString("CONTRACT_SERVICE_ID"));
                    BO contractBO = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT", formData.getString("CONTRACT_ID"));
                    RowMap dto = new RowMap(contractBO.asMap());

                    /*
                    Map<String, Object> contractServiceMap = formData.asMap();

                    for (String key : excludesArray) {
                        contractServiceMap.remove(key);
                    }
                    contractServiceBO.setAll(contractServiceMap);

                    SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_SERVICE", contractServiceBO);

                    BO contractBO = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT", contractServiceBO.getString("CONTRACT_ID"));

                    RowMap dto = new RowMap(contractBO.asMap());

                    contractService.getInstance().AddServiceServiceBundleOne(processExecutionContext.getUserContext(), conn, dto, contractServiceBO);//保存合同
                     */
                    //2、服务调整:生效日期在合同开始日期和合同结束日期之间；已审批服务周期之后的日期；
                    // 3、服务周期分为调整前和调整后两个周期；生效日期之后按照新的数量、单价重新生成服务周期；
                    contractService.getInstance().EditServiceServiceBundle(processExecutionContext.getUserContext(), conn, dto, formData);//保存合同
                    contractService.getInstance().AddContractServiceProduct(processExecutionContext.getUserContext(), dto, conn);//新增服务或者服务包--关联产品

                    conn.commit();
                } catch (SQLException e) {

                    e.printStackTrace();
                    conn.rollback();

                } finally {
                    if (conn != null)
                        DBSql.close(conn);
                }
            }

        }


    }
}
