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

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.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 org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class contractCostController {
    private static final Logger logger = SDK.getLogAPI().getLogger(contractCostController.class);//记录日志

    /**
     * 合同产品拣货单
     * @param uc
     * @param contractCostId
     * @param warehouseProductId
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_ctt.costpick")
    public ResponseObject costPick(UserContext uc, String contractCostId, String warehouseProductId) throws SQLException {
        //创建拣货单

        BO newBO = new BO();

        newBO.set("CONTRACT_COST_ID", contractCostId);
        newBO.set("WAREHOUSE_PRODUCT_ID", warehouseProductId);

        BO warhouseProductBO = SDK.getBOAPI().get("BO_EU_DNIVT_WAREHOUSE_PRODUCT", warehouseProductId);

        newBO.set("PRODUCT_ID", warhouseProductBO.get("PRODUCT_ID"));
        newBO.set("WAREHOUSE_ID", warhouseProductBO.get("WAREHOUSE_ID"));

        int warehouseProductQuantity = ObjToInt(warhouseProductBO.getString("QUANTITY"));//库存数量
        logger.info("库存数量:" + warehouseProductQuantity);

        //可用库存
        int warehouseProductAvailableQuantity = ObjToInt(DBSql.getString("SELECT SUM(AVAILABLE) FROM VIEW_EU_DNINVT_PRODUCT_INVENTORY where ID=?", new Object[]{warehouseProductId}));
        logger.info("可用库存数量:" + warehouseProductAvailableQuantity);

        if (warehouseProductAvailableQuantity <= 0)
            return ResponseObject.newErrResponse("库存数量不足");

        if (warehouseProductQuantity <= 0)
            return ResponseObject.newErrResponse("库存数量不足");

        if (warehouseProductAvailableQuantity <= warehouseProductQuantity)//可用库存数量
            warehouseProductQuantity = warehouseProductAvailableQuantity;

        //全部拣货数量
        int contractCostQuantity = ObjToInt(SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_COST", contractCostId, "QUANTITY"));
        logger.info("合同产品数量:" + contractCostQuantity);

        //已拣货数量
        int contractProductPickQuantity = ObjToInt(DBSql.getString("SELECT SUM(QUANTITY) FROM BO_EU_DNCTT_CONTRACT_COST_PRODUCT WHERE CONTRACT_COST_ID=?  AND CLOSED=0", new Object[]{contractCostId}));
        logger.info("已拣货数量:" + contractProductPickQuantity);

        ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_5670df3b3d164682a9aded38bae2e1be", uc.getUID(), "合同产品拣货单");
        String binidid = processInstance.getId();
        newBO.setBindId(processInstance.getId());
        int quantity = contractCostQuantity - contractProductPickQuantity;//待拣货数量
        if (quantity > warehouseProductQuantity) {
            newBO.set("PICK_QUANTITY", warehouseProductQuantity);
        } else {
            newBO.set("PICK_QUANTITY", quantity);
        }

        SDK.getBOAPI().create("BO_EU_DNCTT_CONTRACT_PRODUCT_PICK", newBO, processInstance, uc);

        String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), binidid, "", 1, "", "", "");

        url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(url);

        return responseObject;
    }

    /**
     * 将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);
    }


    /**
     * 取消拣货
     * @param uc
     * @param costProductId
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_ctt.costcanclepick")
    public ResponseObject costCanclePick(UserContext uc, String costProductId) throws SQLException {

        BO bo = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_COST_PRODUCT", costProductId);

        BO newBO = new BO();
        ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_a10ee583a11045d3b0f82f29b81ea1cd", uc.getUID(), "合同产品取消拣货单");

        String binidid = processInstance.getId();
        newBO.setBindId(processInstance.getId());
        newBO.set("PICK_QUANTITY", bo.get("QUANTITY"));
        newBO.set("CONTRACT_COST_ID", bo.get("CONTRACT_COST_ID"));
        newBO.set("WAREHOUSE_ID", bo.get("WAREHOUSE_ID"));
        newBO.set("PRODUCT_ID", DBSql.getString("SELECT PRODUCT_ID FROM BO_EU_DNCTT_CONTRACT_COST WHERE ID=?", new Object[]{bo.get("CONTRACT_COST_ID")}));
        newBO.set("COST_PRODUCT_ID", bo.getId());

        SDK.getBOAPI().create("BO_EU_DNCTT_CONTRACT_PRODUCT_CANCLEPICK", newBO, processInstance, uc);

        String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), binidid, "", 1, "", "", "");

        url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(url);

        return responseObject;
    }

    /**
     * 移库
     * @param uc
     * @param costProductId
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_ctt.TransferPro")
    public ResponseObject transferPro(UserContext uc, String costProductId) throws SQLException {

        BO bo = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_COST_PRODUCT", costProductId);

        BO newBO = new BO();
        ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_855e0ecd2a0e42dfaf45b3d1fff0c710", uc.getUID(), "合同产品移库单");

        String binidid = processInstance.getId();
        newBO.setBindId(processInstance.getId());
        newBO.set("QUANTITY", bo.get("QUANTITY"));
        newBO.set("CONTRACT_COST_ID", bo.get("CONTRACT_COST_ID"));
        newBO.set("WAREHOUSE_ID", bo.get("WAREHOUSE_ID"));
        newBO.set("PRODUCT_ID", DBSql.getString("SELECT PRODUCT_ID FROM BO_EU_DNCTT_CONTRACT_COST WHERE ID=?", new Object[]{bo.get("CONTRACT_COST_ID")}));
        newBO.set("COST_PRODUCT_ID", bo.getId());

        SDK.getBOAPI().create("BO_EU_CTT_CONTRACT_PRODUCT_TRANSFER", newBO, processInstance, uc);

        String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), binidid, "", 1, "", "", "");

        url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(url);

        return responseObject;
    }

    /**
     * 获取拣货单序列号
     * @param uc
     * @param bindid
     * @param warehouseProductId
     * @param quantity
     * @return
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_ctt.getPickSNList")
    public ResponseObject getPickSNList(UserContext uc, String bindid, String warehouseProductId, Integer quantity) {
        //库存数量
        RowMap stockMap = DBSql.getMap("SELECT * FROM BO_EU_DNIVT_WAREHOUSE_PRODUCT WHERE ID=?", new Object[]{warehouseProductId});
        //库存产品
        List<RowMap> lotList = DBSql.getMaps("SELECT b.* FROM bo_eu_dnivt_warehouse_product a JOIN BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT b ON a.BINDID=b.BINDID WHERE b.QUANTITY>0 AND a.ID=? ORDER BY b.IN_DATE", new Object[]{warehouseProductId});
        //已被拣货数量
        List<RowMap> pickList = DBSql.getMaps("SELECT a.* from BO_EU_DNCTT_CONTRACT_COST_PRODUCT a JOIN BO_EU_DNCTT_CONTRACT_COST b ON a.BINDID=b.BINDID WHERE a.WAREHOUSE_ID=? AND b.PRODUCT_ID=?", new Object[]{stockMap.getString("WAREHOUSE_ID"), stockMap.getString("PRODUCT_ID")});

        List<String> selectedSns = new ArrayList<>();//默认选择
        for (RowMap lotMap : lotList) {
            String lotSNs = lotMap.getString("SN");
            List<String> lotsns = new ArrayList<>();//本批次允许拣货数量
            for (String SN : lotSNs.split(",")) {
                boolean isPicked = false;
                for (RowMap pickMap : pickList) {
                    String pickSNs = pickMap.getString("SN");
                    for (String pickSN : pickSNs.split(",")) {
                        if (SN.equals(pickSN)) {
                            //已被拣货
                            isPicked = true;
                            break;
                        }
                    }
                    if (isPicked)
                        break;
                }

                //还要排除取消接收的sn


                if (!isPicked) {
                    lotsns.add(SN);
                }
            }
            if (lotsns.size() > quantity)//允许挑选
            {
                for (String sn : lotsns) {
                    BO bo = new BO();
                    bo.set("SN", sn);
                    bo.setBindId(bindid);
                    SDK.getBOAPI().createDataBO("BO_EU_DNCTT_CONTRACT_PRODUCT_PICKSN", bo, null);
                }
            } else {
                //全部拣货，不允许挑选
                quantity -= lotsns.size();
                selectedSns.addAll(lotsns);
            }
        }
        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(StringUtils.join(selectedSns, ","));
        return responseObject;
    }
}
