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.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.awspaas.user.apps.donenow_ctt.service.wareHouseProductService;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;

/**
 * 库存转移修改相关库存
 */
public class costTransferProFromAfterSave extends ExecuteListener {
    public String getDescription() {
        return "合同产品库存转移修改相关库存";
    }

    /**
     *
     * @param processExecutionContext
     * @throws Exception
     */
    @Override
    public void execute(ProcessExecutionContext processExecutionContext) throws Exception {
        BO transferProBO = SDK.getBOAPI().getByProcess("BO_EU_CTT_CONTRACT_PRODUCT_TRANSFER", processExecutionContext.getProcessInstance().getId());
        int transferQUANTITY = ObjToInt(transferProBO.get("QUANTITY"));//拣货数量

        Connection conn = null;
        try {
            conn = DBSql.open();
            conn.setAutoCommit(false);
            //获取成本产品
            BO costProductBO = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_COST_PRODUCT").connection(conn).detailById(transferProBO.getString("COST_PRODUCT_ID"));

            int QUANTITY = ObjToInt(costProductBO.get("QUANTITY"));

            if (transferQUANTITY > QUANTITY) {
                throw new Exception("移库数量不能大于已拣货数量");
            }
            String FROM_WAREHOUSE_ID = costProductBO.getString("WAREHOUSE_ID");

            String TO_WAREHOUSE_ID = transferProBO.getString("TO_WAREHOUSE_ID");//转移到仓库


            if (transferProBO.getString("TYPE").equals("1"))//库存转移给我
            {
                String resWareId = DBSql.getString(conn, "SELECT ID FROM BO_EU_DNIVT_WAREHOUSE WHERE RESOURCE_ID=? AND CLOSED=0 ", new Object[]{processExecutionContext.getUserContext().getUID()});
                if (StringUtils.isNotBlank(resWareId)) {
                    TO_WAREHOUSE_ID = resWareId;
                } else {
                    //创建员工个人仓库
                    BO resWare = new BO();
                    resWare.set("NAME", "员工：" + processExecutionContext.getUserContext().getUserName());
                    ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_e10413dd6e034d22aac787a35917814c", processExecutionContext.getUserContext().getUID(), "创建员工仓库" + resWare.getString("NAME"));
                    resWare.setBindId(processInstance.getId());
                    resWare.set("IS_DEFAULT", 0);
                    resWare.set("IS_ACTIVE", 1);
                    resWare.set("RESOURCE_ID", processExecutionContext.getUserContext().getUID());
                    SDK.getBOAPI().create("BO_EU_DNIVT_WAREHOUSE", resWare, processInstance, processExecutionContext.getUserContext(), conn);
                    TO_WAREHOUSE_ID = resWare.getId();
                }
            }
            String SERIAL_NUMBERS = transferProBO.getString("SERIAL_NUMBERS");

            //库存转移
            wareHouseProductService.getInstance().transfer(processExecutionContext.getUserContext(), conn, transferProBO.getString("PRODUCT_ID"), FROM_WAREHOUSE_ID, TO_WAREHOUSE_ID, transferQUANTITY, SERIAL_NUMBERS, 1481, null); // 仓库间转移

            //全部转移
            if (transferQUANTITY == QUANTITY) {
                costProductBO.set("WAREHOUSE_ID", TO_WAREHOUSE_ID);
                SDK.getBOAPI().update("BO_EU_DNIVT_COST_PRODUCT", costProductBO, conn);
            } else {
                //部分转移
                costProductBO.set("QUANTITY", ObjToInt(costProductBO.get("QUANTITY")) - transferQUANTITY);
                if (StringUtils.isNotBlank(SERIAL_NUMBERS)) {
                    String[] serialNumbers = SERIAL_NUMBERS.split(",");
                    String sns = costProductBO.getString("SN");//产品序列号
                    sns = "," + sns + ",";
                    for (int i = 0; i < serialNumbers.length; i++) {
                        sns = sns.replace("," + serialNumbers[i] + ",", ",");
                    }
                    costProductBO.set("SN", sns.substring(1, sns.length() - 1));
                }
                costProductBO.set("OLD_QUANTITY", costProductBO.get("QUANTITY"));//配送数量
                SDK.getBOAPI().update("BO_EU_DNIVT_COST_PRODUCT", costProductBO, conn);

                //移出的产品创建一个新的合同产品记录
                BO toCostProductBO = new BO();
                ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_6bc913271069455abbd516c556b26d31", processExecutionContext.getUserContext().getUID(), "合同产品物流管理");
                toCostProductBO.setBindId(processInstance.getId());
                toCostProductBO.set("WAREHOUSE_ID", TO_WAREHOUSE_ID);
                toCostProductBO.set("CONTRACT_COST_ID", costProductBO.get("CONTRACT_COST_ID"));
                toCostProductBO.set("QUANTITY", transferQUANTITY);
                toCostProductBO.set("SN", SERIAL_NUMBERS);
                toCostProductBO.set("STATUS_ID", 2157);//待出库
                toCostProductBO.set("OLD_QUANTITY", toCostProductBO.get("QUANTITY"));//配送数量
                SDK.getBOAPI().createDataBO("BO_EU_DNCTT_CONTRACT_COST_PRODUCT", toCostProductBO, processExecutionContext.getUserContext(), conn);
            }
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            throw e;
        } finally {
            DBSql.close(conn);
        }

    }

    /**
     * 将Object转换为int
     * @param obj
     * @return
     */
    private int ObjToInt(Object obj) {
        if (obj == null)
            return 0;

        String objStr = obj.toString();
        if (objStr.equals(""))
            return 0;
        //如果有小数点，只取整数
        if (objStr.contains(".")) {
            objStr = objStr.substring(0, objStr.indexOf("."));
        }
        return Integer.parseInt(objStr);
    }
}
