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

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
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.util.DBSql;
import com.actionsoft.bpms.util.TypeUtil;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.Logger;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 合同佣金服务
 */
public class contractCommissionService {
    private static final Logger serviceLogger = SDK.getLogAPI().getLogger(contractCommissionService.class);//记录日志
    private final String[] excludesArray = new String[]{"ID", "ORGID", "BINDID", "CREATEDATE", "CREATEUSER", "UPDATEDATE", "UPDATEUSER", "PROCESSDEFID", "ISEND"};


    private static volatile contractCommissionService instance;

    private contractCommissionService() {
        // Constructor logic here, if any.
    }

    public static contractCommissionService getInstance() {
        if (instance == null) {
            synchronized (contractCommissionService.class) {
                if (instance == null) {
                    instance = new contractCommissionService();
                }
            }
        }
        return instance;
    }

    /**
     * 生成合同佣金
     * @param uc
     * @param commissionIds
     * @param contractId
     * @return
     */
    public ResponseObject generateCommissions(UserContext uc, String commissionIds, String contractId) {

        if (StringUtils.isBlank(commissionIds) && StringUtils.isBlank(contractId))
            return ResponseObject.newErrResponse("请选择合同佣金");

        List<RowMap> commissions = DBSql.getMaps("select * from BO_EU_DNCTT_SALES_COMMISSION where find_in_set(ID,?) OR CONTRACT_ID=?", new Object[]{commissionIds, contractId});
        int count = 0;
        StringBuilder errorMsg = new StringBuilder();

        Map<String, String> ccm = new java.util.HashMap<>();
        serviceLogger.info("佣金规则：" + commissions.size());

        for (RowMap commission : commissions) {
            String CONTRACT_ID = commission.getString("CONTRACT_ID");
            if (StringUtils.isBlank(CONTRACT_ID)) {
                String BINDID = commission.getString("BINDID");
                if (ccm.isEmpty() && ccm.containsKey(BINDID)) {
                    commission.put("CONTRACT_ID", ccm.get(BINDID));
                } else {
                    CONTRACT_ID = DBSql.getString("select ID from BO_EU_DNCTT_CONTRACT where BINDID=?", new Object[]{BINDID});
                    if (StringUtils.isBlank(CONTRACT_ID)) return ResponseObject.newErrResponse("请选择合同");
                    else {
                        ccm.put(BINDID, CONTRACT_ID);
                        commission.put("CONTRACT_ID", CONTRACT_ID);
                        DBSql.update("update BO_EU_DNCTT_SALES_COMMISSION set CONTRACT_ID=? where BINDID=?", new Object[]{CONTRACT_ID, BINDID});
                    }
                }
            }
            String RULE_CATE = commission.getString("RULE_CATE");//规则类别
            BO orgeriod = new BO();
            orgeriod.set("SALES_COMMISSION_ID", commission.getString("ID"));
            orgeriod.set("CONTRACT_ID", commission.getString("CONTRACT_ID"));
            orgeriod.set("ACCOUNT_ID", commission.getString("ACCOUNT_ID"));
            orgeriod.set("PAYEE", commission.get("PAYEE"));
            orgeriod.set("CATE_ID", commission.get("CATE_ID"));
            orgeriod.set("SALESPERSON", commission.get("SALESPERSON"));
            orgeriod.set("DEPARTMENTID", commission.get("DEPARTMENTID"));

            RowMap account = StringUtils.isBlank(commission.getString("PAYEE")) ? null : DBSql.getMap("select ID,NAME from bo_eu_dncrm_account where id=?", new Object[]{commission.getString("PAYEE")});

            orgeriod.set("RATIO", commission.getString("RATIO"));

            BigDecimal COMMISSION_DOLLARS = BigDecimal.ZERO;//佣金金额

            BigDecimal tax = BigDecimal.ZERO;//税率
            String TAX_DEDUCT = commission.getString("TAX_DEDUCT");//税率
            if (StringUtils.isNotBlank(TAX_DEDUCT)) {
                RowMap taxcate = DBSql.getMap("SELECT NAME,EXT1 FROM BO_EU_DND_GENERAL WHERE OID = ? AND ORGID=?", new Object[]{TAX_DEDUCT, uc.getCompanyModel().getId()});
                tax = TypeUtil.convert(taxcate.get("EXT1"), BigDecimal.class);
            }


            /**
             * 4646	一次性
             * 4647	销售额百分比
             * 4648	销售净利百分比
             * 4649	周期固定金额
             */

            if (RULE_CATE.equals("4646")) {
                //一次性：整个合同生成一条，如果已经生成，再未付款的情况下，可以重新生成
                if (DBSql.getInt("select count(1) from BO_EU_DNCTT_SALES_COMMISSION_PERIOD where SALES_COMMISSION_ID=? and PAY_AMOUNT>0 ", new Object[]{commission.getString("ID")}) > 0) {
                    errorMsg.append(account.getString("NAME") + "的一次性佣金已付款，不可重新生成！");
                    continue;
                }

                //删除旧数据
                String comssionperiodBindId = DBSql.getString("select BINDID from BO_EU_DNCTT_SALES_COMMISSION_PERIOD where SALES_COMMISSION_ID=? ", new Object[]{commission.getString("ID")});
                if (StringUtils.isNotBlank(comssionperiodBindId)) {
                    DBSql.update("delete from BO_EU_DNCTT_SALES_COMMISSION_PERIOD where SALES_COMMISSION_ID=?", new Object[]{commission.getString("ID")});
                    SDK.getProcessAPI().deleteById(comssionperiodBindId, uc.getUID());
                }


                RowMap contract = DBSql.getMap("select CONTRACT_START_DATE,CONTRACT_END_DATE from BO_EU_DNCTT_CONTRACT where ID=?", new Object[]{commission.getString("CONTRACT_ID")});

                BO period = new BO();
                period.setAll(orgeriod.asMap());
                // a) 周期：与合同相同。用户付款后开始一次性计提（可能没有全部付款）
                // b) 佣金金额=配置表的佣金金额/（1+配置表税率）
                period.set("PERIOD_BEGIN_DATE", contract.get("CONTRACT_START_DATE"));//周期开始时间
                period.set("PERIOD_END_DATE", contract.get("CONTRACT_END_DATE"));//周期结束时间

                COMMISSION_DOLLARS = TypeUtil.convert(commission.get("COMMISSION_DOLLARS"), BigDecimal.class);

                COMMISSION_DOLLARS = COMMISSION_DOLLARS.divide(BigDecimal.ONE.add(tax), 10, BigDecimal.ROUND_HALF_UP);

                period.set("COMMISSION_DOLLARS", COMMISSION_DOLLARS);//佣金金额


                if (period.containsKey("COMMISSION_DOLLARS")) {
                    count++;
                    ProcessInstance Instance = SDK.getProcessAPI().createBOProcessInstance("obj_bb54b127f0bd4b50802070fdaa42a9c3", uc.getUID(), "合同佣金");
                    period.setBindId(Instance.getId());
                    SDK.getBOAPI().create("BO_EU_DNCTT_SALES_COMMISSION_PERIOD", period, Instance, uc);
                    DBSql.update("UPDATE BO_EU_DNCTT_SALES_COMMISSION_PERIOD SET PERIOD_BEGIN_DATE = DATE(PERIOD_BEGIN_DATE), PERIOD_END_DATE = DATE(PERIOD_END_DATE) WHERE BINDID=? AND (PERIOD_BEGIN_DATE <> DATE(PERIOD_BEGIN_DATE) OR PERIOD_END_DATE <> DATE(PERIOD_END_DATE)) ", new Object[]{period.getBindId()});
                }

            } else {

                String CONTRACT_COST_ID = commission.getString("CONTRACT_COST_ID");
                String CONTRACT_SERVICE_ID = commission.getString("CONTRACT_SERVICE_ID");

                serviceLogger.info("CONTRACT_SERVICE_ID=" + CONTRACT_SERVICE_ID);
                serviceLogger.info("CONTRACT_COST_ID=" + CONTRACT_COST_ID);

                if (StringUtils.isBlank(CONTRACT_COST_ID) && StringUtils.isBlank(CONTRACT_SERVICE_ID))
                    continue;

                List<RowMap> bills = DBSql.getMaps("SELECT a.* FROM VIEW_EU_DNCTT_INVOICE_DETAIL a WHERE a.CONTRACT_ID =? AND a.RECEIVE_AMOUNT > 0 AND a.INVOICE_AMOUNT = 0 AND NOT EXISTS( SELECT 1 FROM BO_EU_DNCTT_SALES_COMMISSION_PERIOD b WHERE b.SALES_COMMISSION_ID =? AND b.CONTRACT_ID = a.CONTRACT_ID AND b.PAY_AMOUNT > 0 AND b.INVOICE_DETAIL_ID = a.ID) AND ( EXISTS ( SELECT 1 FROM BO_EU_DNCRM_ACCOUNT_DEDUCTION c WHERE c.ID = a.ACCOUNT_DEDUCTION_ID AND c.TYPE_ID = 1321 AND FIND_IN_SET( c.OBJECT_ID, ? ) ) OR EXISTS ( SELECT 1 FROM BO_EU_DNCRM_ACCOUNT_DEDUCTION c JOIN BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD d ON c.OBJECT_ID = d.ID WHERE c.ID = a.ACCOUNT_DEDUCTION_ID AND c.TYPE_ID = 1325 AND FIND_IN_SET( d.CONTRACT_SERVICE_ID, ? ) ))", new Object[]{commission.getString("CONTRACT_ID"), commission.getString("ID"), CONTRACT_COST_ID, CONTRACT_SERVICE_ID});

                serviceLogger.info("获取付款的收费条目：" + bills.size());

                for (RowMap bill : bills) {
                    BO period = new BO();
                    period.setAll(orgeriod.asMap());
                    period.set("ID", null);
                    String ACCOUNT_DEDUCTION_ID = bill.getString("ACCOUNT_DEDUCTION_ID");//计费条目ID

                    //FEE_DATE  费用账期
                    String FEE_DATE = DBSql.getString("SELECT MAX(c.RECEIVE_DATE) FROM BO_EU_DNCTT_INVOICE_PLAN a JOIN BO_EU_DNCTT_INVOICE_PLAN_DETAIL b ON a.BINDID=b.BINDID JOIN BO_EU_DNCTT_INVOICE_PLAN_RECEIVE c ON a.BINDID=c.BINDID WHERE a.ISEND=1 AND b.ACCOUNT_DEDUCTION_ID=?  ", new Object[]{ACCOUNT_DEDUCTION_ID});
                    if (StringUtils.isBlank(FEE_DATE))
                        continue;
                    serviceLogger.info("FEE_DATE=" + FEE_DATE);
                    FEE_DATE = FEE_DATE.substring(0, 10);
                    //获取 FEE_DATE 的下个月
                    FEE_DATE = contractService.getLocalDate(FEE_DATE).plusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
                    period.set("FEE_DATE", FEE_DATE);


                    BigDecimal shou_tax = BigDecimal.ZERO;//税率-收
                    BigDecimal fu_tax = BigDecimal.ZERO;//税率-付

                    period.set("INVOICE_DETAIL_ID", bill.getString("ID"));

                    //删除旧数据
                    String comssionperiodBindId = DBSql.getString("select BINDID from BO_EU_DNCTT_SALES_COMMISSION_PERIOD where SALES_COMMISSION_ID=? and CONTRACT_ID=? and INVOICE_DETAIL_ID=? ", new Object[]{commission.getString("ID"), commission.getString("CONTRACT_ID"), bill.getString("ID")});
                    if (StringUtils.isNotBlank(comssionperiodBindId)) {
                        DBSql.update("delete from BO_EU_DNCTT_SALES_COMMISSION_PERIOD where SALES_COMMISSION_ID=? and CONTRACT_ID=? and INVOICE_DETAIL_ID=? ", new Object[]{commission.getString("ID"), commission.getString("CONTRACT_ID"), bill.getString("ID")});

                        SDK.getProcessAPI().deleteById(comssionperiodBindId, uc.getUID());
                    }
                    //获取合同服务的周期
                    RowMap service = DBSql.getMap("SELECT b.PERIOD_BEGIN_DATE,b.PERIOD_END_DATE,b.PERIOD_COST,b.CONTRACT_SERVICE_ID,b.CONTRACT_ID,c.MINIMUM_PROFIT_MARGIN,c.ALLOW_COMMISSION_PAYMENT from BO_EU_DNCRM_ACCOUNT_DEDUCTION a JOIN BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD b ON a.OBJECT_ID=b.ID AND a.TYPE_ID=1325 JOIN BO_EU_DNCTT_CONTRACT c ON b.CONTRACT_ID=c.ID WHERE  a.ID=? ", new Object[]{ACCOUNT_DEDUCTION_ID});

                    RowMap ded = DBSql.getMap("select * from BO_EU_DNCRM_ACCOUNT_DEDUCTION where ID=?", new Object[]{ACCOUNT_DEDUCTION_ID});

                    if (service != null) {

                        //利润不达标，不需要计算佣金
                        if (RULE_CATE.equals("4648") && service.getDouble("MINIMUM_PROFIT_MARGIN") > 0 && service.getDouble("ALLOW_COMMISSION_PAYMENT") == 0) {
                            continue;
                        }

                        period.set("CONTRACT_SERVICE_ID", service.get("CONTRACT_SERVICE_ID"));
                        period.set("PERIOD_BEGIN_DATE", service.get("PERIOD_BEGIN_DATE"));//周期开始时间
                        period.set("PERIOD_END_DATE", service.get("PERIOD_END_DATE"));//周期结束
                        period.set("COST_INCLUDE_TAX", service.get("PERIOD_COST"));//本期成本（含税）

                        //period.set("COST_BF_INCLUDE_TAX", bill.get(""));//上期结转成本（含税）

                        //上期的成本-已收+上期结转成本（含税）
                        RowMap lastPeriod = DBSql.getMap("SELECT * FROM BO_EU_DNCTT_SALES_COMMISSION_PERIOD WHERE SALES_COMMISSION_ID=? AND CONTRACT_SERVICE_ID=? and INVOICE_DETAIL_ID=? ORDER BY PERIOD_BEGIN_DATE DESC", new Object[]{commission.getString("ID"), service.get("CONTRACT_SERVICE_ID"), bill.getString("ID")});
                        if (lastPeriod != null) {
                            BigDecimal RECEIVED_DOLLARS_INCLUDE_TAX = TypeUtil.convert(lastPeriod.get("RECEIVED_DOLLARS_INCLUDE_TAX"), BigDecimal.class);
                            BigDecimal COST_INCLUDE_TAX = TypeUtil.convert(lastPeriod.get("COST_INCLUDE_TAX"), BigDecimal.class);

                            COST_INCLUDE_TAX = COST_INCLUDE_TAX.subtract(RECEIVED_DOLLARS_INCLUDE_TAX);

                            if (lastPeriod.get("COST_BF_INCLUDE_TAX") != null) {
                                COST_INCLUDE_TAX = COST_INCLUDE_TAX.add(TypeUtil.convert(lastPeriod.get("COST_BF_INCLUDE_TAX"), BigDecimal.class));
                            }

                            //本次转结成本
                            if (COST_INCLUDE_TAX.compareTo(BigDecimal.ZERO) > 0) {
                                period.set("COST_BF_INCLUDE_TAX", COST_INCLUDE_TAX);
                            }
                        }

                        RowMap contractService = DBSql.getMap("SELECT IS_CTRTAX_APPLIED,TAX_CATEGORY_ID,VAT_TAX,PURCHASE_TAX_CATEGORY_ID,NAME FROM BO_EU_DNCTT_CONTRACT_SERVICE WHERE ID=?", new Object[]{service.get("CONTRACT_SERVICE_ID")});
                        if (contractService != null) {
                            period.set("CONTRACT_SERVICE_NAME", contractService.get("NAME"));
                            //应收用的税
                            RowMap taxcate = DBSql.getMap("SELECT NAME,EXT1 FROM BO_EU_DND_GENERAL WHERE OID = ? AND ORGID=?", new Object[]{contractService.getString("TAX_CATEGORY_ID"), uc.getCompanyModel().getId()});
                            shou_tax = TypeUtil.convert(taxcate.get("EXT1"), BigDecimal.class);

                            //付款用的税
                            if (contractService.getString("VAT_TAX").equals("1") && StringUtils.isNotBlank(contractService.getString("PURCHASE_TAX_CATEGORY_ID"))) {
                                RowMap fu_taxcate = DBSql.getMap("SELECT NAME,EXT1 FROM BO_EU_DND_GENERAL WHERE OID = ? AND ORGID=?", new Object[]{contractService.getString("PURCHASE_TAX_CATEGORY_ID"), uc.getCompanyModel().getId()});
                                if (fu_tax != null)
                                    fu_tax = TypeUtil.convert(fu_taxcate.get("EXT1"), BigDecimal.class);
                            }
                        }
                    } else {
                        period.set("PERIOD_BEGIN_DATE", bill.get("ITEM_DATE"));//计费日期
                        period.set("PERIOD_END_DATE", bill.get("ITEM_DATE"));//计费日期
                        period.set("EXTENDED_COST", ded.get("EXTENDED_COST"));//本期成本（含税）

                        //应收用的税
                        RowMap taxcate = DBSql.getMap("SELECT NAME,EXT1 FROM BO_EU_DND_GENERAL WHERE OID = ? AND ORGID=?", new Object[]{ded.getString("TAX_CATEGORY_ID"), uc.getCompanyModel().getId()});
                        shou_tax = TypeUtil.convert(taxcate.get("EXT1"), BigDecimal.class);

                    }

                    period.set("RECEIVABLE_DOLLARS_INCLUDE_TAX", bill.get("DOLLARS"));//本期应收款（含税）
                    period.set("RECEIVED_DOLLARS_INCLUDE_TAX", bill.get("RECEIVE_AMOUNT"));//本期已收款（含税）
                    //period.set("COST_INCLUDE_TAX", bill.get(""));//本期成本（含税）
                    //period.set("COST_BF_INCLUDE_TAX", bill.get(""));//上期结转成本（含税）

                    // if (shou_tax.compareTo(BigDecimal.ZERO) > 0) {
                    shou_tax = BigDecimal.ONE.add(shou_tax);
                    period.set("RECEIVABLE_DOLLARS", TypeUtil.convert(period.get("RECEIVABLE_DOLLARS_INCLUDE_TAX"), BigDecimal.class).divide(shou_tax, 10, BigDecimal.ROUND_HALF_UP));//本期应收款（不含税）

                    period.set("RECEIVED_DOLLARS", TypeUtil.convert(period.get("RECEIVED_DOLLARS_INCLUDE_TAX"), BigDecimal.class).divide(shou_tax, 10, BigDecimal.ROUND_HALF_UP));//本期已收款（不含税）
                    // }

                    // if (fu_tax.compareTo(BigDecimal.ZERO) > 0) {
                    fu_tax = BigDecimal.ONE.add(fu_tax);
                    if (period.containsKey("COST_INCLUDE_TAX") && period.get("COST_INCLUDE_TAX") != null)
                        period.set("COST", TypeUtil.convert(period.get("COST_INCLUDE_TAX"), BigDecimal.class).divide(fu_tax, 10, BigDecimal.ROUND_HALF_UP));//本期成本（不含税）
                    if (period.containsKey("COST_BF_INCLUDE_TAX") && period.get("COST_BF_INCLUDE_TAX") != null)
                        period.set("COST_BF", TypeUtil.convert(period.get("COST_BF_INCLUDE_TAX"), BigDecimal.class).divide(fu_tax, 10, BigDecimal.ROUND_HALF_UP));//上期结转成本（不含税）
                    // }

                    switch (RULE_CATE) {
                        case "4647": {
                            if (commission.getString("INCLUDE_TAX").equals("1")) {
                                //销售额百分比：针对已经全部收款的合同服务进行生成，创建一条合同佣金周期记录
                                //佣金金额：本期已收款（不含税）/（1+配置表税率），注意计费项必须是全部付款了，才能提佣金，已收款必须是完整支付的计费项的金额之和
                                COMMISSION_DOLLARS = TypeUtil.convert(bill.get("RECEIVE_AMOUNT"), BigDecimal.class);
                                BigDecimal RATIO = TypeUtil.convert(commission.get("RATIO"), BigDecimal.class);
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.multiply(RATIO).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_HALF_UP);
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.divide(BigDecimal.ONE.add(tax), 10, BigDecimal.ROUND_HALF_UP);
                                period.set("COMMISSION_DOLLARS", COMMISSION_DOLLARS);//佣金金额
                            } else {
                                //使用不含税 已收款
                                COMMISSION_DOLLARS = TypeUtil.convert(period.get("RECEIVED_DOLLARS"), BigDecimal.class);
                                BigDecimal RATIO = TypeUtil.convert(commission.get("RATIO"), BigDecimal.class);
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.multiply(RATIO).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_HALF_UP);
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.divide(BigDecimal.ONE.add(tax), 10, BigDecimal.ROUND_HALF_UP);
                                period.set("COMMISSION_DOLLARS", COMMISSION_DOLLARS);//佣金金额
                            }
                        }
                        break;
                        case "4648": {
                            //销售净利百分比：针对已经全部收款的合同服务进行生成，创建一条合同佣金周期记录
                            BigDecimal RATIO = TypeUtil.convert(commission.get("RATIO"), BigDecimal.class);
                            //使用含税价

                            if (commission.getString("INCLUDE_TAX").equals("1")) {
                                COMMISSION_DOLLARS = TypeUtil.convert(bill.get("RECEIVE_AMOUNT"), BigDecimal.class);

                                if (period.containsKey("COST_INCLUDE_TAX") && period.get("COST_INCLUDE_TAX") != null)
                                    COMMISSION_DOLLARS = COMMISSION_DOLLARS.subtract(TypeUtil.convert(period.get("COST_INCLUDE_TAX"), BigDecimal.class));

                                //上期结转成本（含税）
                                if (period.containsKey("COST_BF_INCLUDE_TAX") && period.get("COST_BF_INCLUDE_TAX") != null)
                                    COMMISSION_DOLLARS = COMMISSION_DOLLARS.subtract(TypeUtil.convert(period.get("COST_BF_INCLUDE_TAX"), BigDecimal.class));

                            } else {
                                //使用不含税价
                                COMMISSION_DOLLARS = TypeUtil.convert(period.get("RECEIVED_DOLLARS"), BigDecimal.class);//不含税已收

                                //本期成本（含税）
                                if (period.containsKey("COST") && period.get("COST") != null)
                                    COMMISSION_DOLLARS = COMMISSION_DOLLARS.subtract(TypeUtil.convert(period.get("COST"), BigDecimal.class));

                                //上期结转成本（含税）
                                if (period.containsKey("COST_BF") && period.get("COST_BF") != null)
                                    COMMISSION_DOLLARS = COMMISSION_DOLLARS.subtract(TypeUtil.convert(period.get("COST_BF"), BigDecimal.class));

                            }

                            if (COMMISSION_DOLLARS.compareTo(BigDecimal.ZERO) > 0) {
                                period.set("NET_PROFIT", COMMISSION_DOLLARS);//利润
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.multiply(RATIO).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_HALF_UP);
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.divide(BigDecimal.ONE.add(tax), 10, BigDecimal.ROUND_HALF_UP);
                                period.set("COMMISSION_DOLLARS", COMMISSION_DOLLARS);//佣金金额
                            } else {
                                period.set("NET_PROFIT", BigDecimal.ZERO);
                                period.set("COMMISSION_DOLLARS", BigDecimal.ZERO);
                            }

                        }
                        break;
                        case "4649": {
                            //周期固定金额：根据合同的计费周期生成每个周期的佣金

                            // a) 周期：上个月只要客户交费了，本月就要计提佣金。前提是某个或某些服务周期完整支付了，或者合同产品完整支付了
                            // b) 佣金金额：配置表的佣金金额/（1+配置表税率）

                            boolean is = false;
                            if (commission.get("COMMISSION_DOLLARS") != null) {
                                //固定佣金
                                COMMISSION_DOLLARS = TypeUtil.convert(commission.get("COMMISSION_DOLLARS"), BigDecimal.class);
                                if (COMMISSION_DOLLARS.compareTo(BigDecimal.ZERO) > 0) {
                                    is = true;
                                    COMMISSION_DOLLARS = COMMISSION_DOLLARS.divide(BigDecimal.ONE.add(tax), 10, BigDecimal.ROUND_HALF_UP);
                                    period.set("COMMISSION_DOLLARS", COMMISSION_DOLLARS);//佣金金额
                                }
                            }

                            if (is == false && commission.get("RATIO") != null) {
                                //百分比
                                BigDecimal RATIO = TypeUtil.convert(commission.get("RATIO"), BigDecimal.class);
                                COMMISSION_DOLLARS = TypeUtil.convert(bill.get("RECEIVE_AMOUNT"), BigDecimal.class);
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.multiply(RATIO).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_HALF_UP);
                                COMMISSION_DOLLARS = COMMISSION_DOLLARS.divide(BigDecimal.ONE.add(tax), 10, BigDecimal.ROUND_HALF_UP);
                                period.set("COMMISSION_DOLLARS", COMMISSION_DOLLARS);//佣金金额
                            }

                        }
                        break;
                    }

                    if (period.containsKey("COMMISSION_DOLLARS")) {
                        count++;
                        ProcessInstance Instance = SDK.getProcessAPI().createBOProcessInstance("obj_bb54b127f0bd4b50802070fdaa42a9c3", uc.getUID(), "合同佣金");
                        period.setBindId(Instance.getId());
                        SDK.getBOAPI().create("BO_EU_DNCTT_SALES_COMMISSION_PERIOD", period, Instance, uc);
                        DBSql.update("UPDATE BO_EU_DNCTT_SALES_COMMISSION_PERIOD SET PERIOD_BEGIN_DATE = DATE(PERIOD_BEGIN_DATE), PERIOD_END_DATE = DATE(PERIOD_END_DATE) WHERE BINDID=? AND (PERIOD_BEGIN_DATE <> DATE(PERIOD_BEGIN_DATE) OR PERIOD_END_DATE <> DATE(PERIOD_END_DATE)) ", new Object[]{period.getBindId()});
                    }

                }
            }


        }


        if (count == 0) {
            if (errorMsg.length() > 0)
                return ResponseObject.newErrResponse(errorMsg.toString());
            return ResponseObject.newErrResponse("没有符合条件的佣金生成！");
        }
        return ResponseObject.newOkResponse().put("count", count);
    }


}
