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

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.database.RowMap;
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.bpms.util.TypeUtil;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.donenow_ivt.constant.IVTConstant;
import com.awspaas.user.apps.donenow_ivt.utils.BigDecimalUtil;
import me.chanjar.weixin.common.util.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

@Controller
public class IVTController extends BaseController {

    @Mapping("com.awspaas.user.apps.donenow_ivt.queryprice")
    public String queryprice(String ids, UserContext uc, String unitcost) {
        System.out.println("unitcost:" + unitcost);
        if (StringUtils.isBlank(ids)) {
            return "";
        }
        if (StringUtils.isBlank(unitcost)) {
            unitcost = "0";
        }
        String[] arr = ids.split(",");
        List<BO> list = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_SERVICE).addQuery("ID IN ('" + org.apache.commons.lang3.StringUtils.join(arr, "','") + "')", null).list();
        String unitPriceTotal = "0";
        String unitCostTotal = "0";

        for (BO bo : list) {
            unitPriceTotal = BigDecimalUtil.add(unitPriceTotal, bo.getString("UNIT_PRICE"));
            unitCostTotal = BigDecimalUtil.add(unitCostTotal, bo.getString("UNIT_COST"));
        }
        JSONObject json = new JSONObject();
        //String discount=BigDecimalUtil.sub(totalPrice, unitcost);
        json.put("unitPriceTotal", unitPriceTotal);
        json.put("unitCostTotal", unitCostTotal);
        //json.put("percent",BigDecimalUtil.div(discount, totalPrice));
        return success(json);

    }

    /**
     *
     * 根据产品ID查找对应的数据
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.queryproduct")
    public String queryproduct(String id, UserContext uc) {
        BO detail = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_PRODUCT).detailById(id);
        if (null == detail) {
            return fail("未找到对应的产品");
        }
        return success(detail.asMap());
    }

    /**
     *
     * 变更原因保存
     * 类型:手工修改库存1485
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.updatereason")
    public String updatereason(String commitmsg, UserContext uc, String productBindId) {
        //仓库产品
        System.out.println("updatereason bindId:" + productBindId);
        System.out.println("commitmsg:" + commitmsg);
        System.out.println("UserContext:" + uc.getUID());

        BO detail = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT).bindId(productBindId).detail();

        ProcessInstance createBOProcessInstance = SDK.getProcessAPI().createBOProcessInstance(IVTConstant.obj_e15a8fedeaeb43dc85aa258a7e1cffcf, uc.getUID(), "");

        //BO productDetail=SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_PRODUCT).detailById(productId);
        //产品移库1485
        BO bo = new BO();
        bo.set("PRODUCT_ID", detail.getString("PRODUCT_ID"));
        bo.set("NOTES", commitmsg);
        bo.set("QUANTITY", detail.getString("QUANTITY"));
        bo.set("TYPE_ID", 1485);
        bo.setBindId(createBOProcessInstance.getId());
        SDK.getBOAPI().create(IVTConstant.BO_EU_DNIVT_TRANSFER, bo, createBOProcessInstance, uc);

        return success("");
    }

    /**
     *
     * 产品复制并新增
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.productcopy")
    public String productcopy(String bindId, UserContext uc, String tableName) {
        BO detail = SDK.getBOAPI().query(tableName).detailByBindId(bindId);
        if (null == detail) {
            return fail("未找到对应的数据");
        }
        String processDefId = DBSql.getString("select processdefid from wfc_process where id=?", new Object[]{bindId});
        ProcessInstance createBOProcessInstance = SDK.getProcessAPI().createBOProcessInstance(processDefId, uc.getUID(), "");
        BO bo = new BO();

        bo.setAll(detail.asMap());
        bo.setId(UUIDGener.getUUID());
        bo.setBindId(createBOProcessInstance.getId());
        bo.set("SKU",detail.getString("SKU")+"_COPY");
        SDK.getBOAPI().create(tableName, bo, createBOProcessInstance, uc);
        //TaskInstance taskInst = SDK.getProcessAPI().start(createBOProcessInstance).fetchActiveTasks().get(0);
        String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), createBOProcessInstance.getId(), "", 1, "", "", "");
        url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);
        return url;
    }

    /**
     *
     * 采购审批通过
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.productcostapproval")
    public String productcostapproval(String ids, UserContext uc, String type) {
        if (StringUtils.isEmpty(ids)) {
            return fail("数据id不允许为空");

        }
        ids = "'" + ids.substring(0, ids.length() - 1).replace(",", "','") + "'";
        List<BO> list = SDK.getBOAPI().query(IVTConstant.BO_EU_DNCTT_CONTRACT_COST).addQuery(" ID IN (" + ids + ")", null).list();
        System.out.println("ids:" + ids);
        System.out.println("list.size:" + list.size());

        for (BO bo : list) {

            bo.set("STATUS_ID", type);
            SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST, bo);
        }
        return success("");
    }


    /**
     *
     * 采购接收打开选择数据的临时表单
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.receiveorder")
    public String receiveorder(String ids, UserContext uc, String type) {
        if (StringUtils.isEmpty(ids)) {
            return fail("数据id不允许为空");

        }
        ids = "'" + ids.substring(0, ids.length() - 1).replace(",", "','") + "'";
        List<BO> list = SDK.getBOAPI().query(IVTConstant.BO_EU_DNCTT_CONTRACT_COST).addQuery(" ID IN (" + ids + ")", null).list();
        System.out.println("ids:" + ids);
        System.out.println("list.size:" + list.size());

        for (BO bo : list) {

            bo.set("STATUS_ID", type);
            SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST, bo);
        }
        return success("");
    }

    @Mapping("com.awspaas.user.apps.donenow_ivt.queryExistPurchasereceive")
    public String queryExistPurchasereceive(String ids, String bindId, UserContext uc) {
        // 处理入参：优先用bindId查询采购项ID
        String pureIds = "";
        if (StringUtils.isNotBlank(bindId)) {
            // 核心：通过bindId获取关联的采购项ID（和创建接口逻辑一致）
            pureIds = DBSql.getString("SELECT GROUP_CONCAT(ID) from bo_eu_dnivt_order_product WHERE BINDID=?", new Object[]{bindId});
        } else if (StringUtils.isNotBlank(ids)) {
            pureIds = ids.trim();
            if (pureIds.endsWith(",")) {
                pureIds = pureIds.substring(0, pureIds.length() - 1);
            }
        } else {
            return "{\"code\":-1,\"msg\":\"请传入bindId或ids\"}";
        }

        if (StringUtils.isBlank(pureIds)) {
            return "{\"code\":-1,\"msg\":\"无已存在的待接收接收单\"}";
        }

        String quotedIds = "'" + pureIds.replace(",", "','") + "'";
        String checkSql = "SELECT DISTINCT s.BINDID FROM BO_EU_DNIVT_RECEIVE_SUB s " +
                "WHERE s.ORDER_PRODUCT_ID IN (" + quotedIds + ") ";
        String existBindId = DBSql.getString(checkSql, new Object[]{});

        if (StringUtils.isNotBlank(existBindId)) {
            String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), existBindId, "", 1, "", "", "");
            url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);
            return "{\"code\":0,\"msg\":\"操作成功\",\"data\":\"" + url + "\"}";
        } else {
            return "{\"code\":-1,\"msg\":\"无已存在的待接收接收单\"}";
        }
    }
    /**
     *
     *采购项接收
     */
    /**
     *
     *采购项接收
     */


    @Mapping("com.awspaas.user.apps.donenow_ivt.purchasereceive")
    public String purchasereceive(String ids, UserContext uc, String bindId) {
        System.out.print("idsids:" + ids);
        System.out.print("bindId:" + bindId);

        // ===== 1. 订单项ID预处理 + 非空校验 =====
        if (StringUtils.isNotBlank(ids)) {
            ids = ids.trim();
            if (ids.endsWith(",")) {
                ids = ids.substring(0, ids.length() - 1);
            }
        } else if (StringUtils.isNotBlank(bindId)) {
            ids = DBSql.getString("SELECT GROUP_CONCAT(ID) from bo_eu_dnivt_order_product WHERE BINDID=?", new Object[]{bindId});
        } else {
            return fail("采购订单ID不能为空");
        }
        ids = "'" + ids.replace(",", "','") + "'";
        System.out.print("idsids:" + ids);

        // ===== 2. 采购订单项及关联数据查询 =====
        String sql = "  select op.CONTRACT_COST_ID,a.IS_SERIALIZED,o.CREATEDATE,o.FREIGHT_COST,op.WAREHOUSE_ID,op.product_id,op.id,c.id as contract_id,p.id as project_id,t.id as task_id,op.product_id," +
                "   ifnull(c.account_id,ifnull(p.account_id,t.account_id))as account_id,b.opportunity_id," +
                "  o.vendor_account_id,if(c.name is not null,'contract',if(p.name is not null,'project'," +
                "  'ticket'))parent_type,op.name as product_name,(select name from bo_eu_dncrm_account where " +
                "  id=ifnull(c.account_id,ifnull(p.account_id,t.account_id))) account_name," +
                "  (select name from bo_eu_dncrm_opportunity where id=b.opportunity_id)oppo_name," +
                "  ifnull(c.name,ifnull(p.name,t.no))contrac_project_task_name," +
                "op.quantity," +
                "op.unit_cost*op.quantity as " +
                "  total_cost,ifnull((select sum(ifnull(quantity,0)) from bo_eu_dnivt_warehouse_product where " +
                "  product_id=op.product_Id ),0)as on_hand,ifnull((select sum(x.quantity) from bo_eu_dnivt_reserve x," +
                "  bo_eu_dncrm_quote_item y where   x.quote_item_id=y.id and y.object_id=op.product_id ),0)+" +
                "  ifnull((select sum(x.quantity) from bo_eu_dnctt_contract_cost_product x,bo_eu_dnctt_contract_cost y " +
                "  where   x.status_id=2157 and x.contract_cost_id=y.id and y.product_id=op.product_id),0) as reserve_pick_num," +
                "  ifnull((select sum(ifnull(quantity,0)) from bo_eu_dnivt_warehouse_product where product_id=op.product_Id  ),0) " +
                "  -ifnull((select sum(x.quantity) from bo_eu_dnivt_reserve x,bo_eu_dncrm_quote_item y where  x.quote_item_id=y.id and y.object_id=op.product_id ),0)" +
                "  -ifnull((select sum(x.quantity) from bo_eu_dnctt_contract_cost_product x,bo_eu_dnctt_contract_cost y " +
                "  where   x.status_id=2157 and x.contract_cost_id=y.id and y.product_id=op.product_id),0)  as aviable_num," +
                "  (select y.name from bo_eu_dncrm_account y where y.id=o.vendor_account_id)vendor, " +
                "  a.manu_product_no as manu_product_no,a.sku,location_id as ship_to, op.estimated_arrival_date," +
                "  o.purchase_order_no" +
                " from  bo_eu_dnivt_order_product op " +
                " left  join  bo_eu_dnivt_order o on op.order_id=o.id" +
                " left  join  bo_eu_dnivt_product a on op.product_id=a.id" +
                " left  join bo_eu_dnctt_contract_cost b on op.contract_cost_id=b.id " +
                " LEFT  join bo_eu_dnctt_contract c on c.id=b.contract_id  " +
                " LEFT  join bo_eu_dnpro_project p on p.id=b.project_id " +
                " LEFT  join bo_eu_dnsdk_task t on t.id=b.task_id " +
                " left  join bo_eu_dncrm_sales_order so on b.opportunity_id=so.opportunity_id " +
                " where   op.isend=1 and o.isend=1 AND op.id IN (" + ids + ")";
        System.out.print("SSSSQL:" + sql);
        List<RowMap> maps = DBSql.getMaps(sql, new Object[]{});
        if (maps.size() == 0) {
            return fail("请检查采购订单是否未审批！");
        }

        // ===== 3. 提取采购订单号 + 校验：单次只能处理同一个采购订单 =====
        String purchaseOrderNo = null;
        Set<String> set = new HashSet<String>();
        for (RowMap map : maps) {
            String poNo = map.getString("purchase_order_no");
            if (StringUtils.isNotBlank(poNo) && StringUtils.isNotBlank(poNo.trim())) {
                set.add(poNo);
                purchaseOrderNo = poNo;
            }
        }
        if (set.size() > 1) {
            System.out.println("setsetset:" + set);
            return fail("一次只能接收同一个采购订单的采购项");
        }

        // ===== 4. 核心修复：防重复创建【适配主表无STATUS字段】✅✅
        // 关键改动：主表仅按采购单号判断是否存在，彻底删除STATUS查询条件，杜绝报错
        BO existingMainBO = null;
        if (StringUtils.isNotBlank(purchaseOrderNo)) {
            long count = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_RECEIVE_MAIN)
                    .addQuery("PURCHASE_ORDER_NO=", purchaseOrderNo)
                    .count();
            // 只要存在同采购单号的主单，直接获取并返回，不区分状态
            if (count > 0) {
                existingMainBO = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_RECEIVE_MAIN)
                        .addQuery("PURCHASE_ORDER_NO=", purchaseOrderNo)
                        .detail();
            }
        }

        // ===== 5. 存在已有单据，直接返回URL，终止创建（重复打开不报错）✅✅
        if (existingMainBO != null) {
            String processInstanceId = existingMainBO.getBindId();
            String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), processInstanceId, "", 1, "", "", "");
            url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);
            return success(url);
        }

        // ===== 6. 初始化流程实例ID（主/子表绑定）=====
        ProcessInstance createBOProcessInstance = SDK.getProcessAPI().createBOProcessInstance(IVTConstant.obj_3121af9039dc454aa776f9bdadf6b239, uc.getUID(), "");

        // ===== 7. 构建采购接收子表数据（子表独有STATUS，初始待接收）✅✅
        List<BO> list = new ArrayList<BO>();
        for (RowMap orgMap : maps) {
            System.out.println("map:" + orgMap);
            // 原生RowMap取值，无方法歧义、零报错
            String opId = orgMap.getString("id");
            String productName = orgMap.getString("product_name");
            String warehouseId = orgMap.getString("warehouse_id");
            String accountName = orgMap.getString("account_name");
            String contracName = orgMap.getString("contrac_project_task_name");
            String productId = orgMap.getString("product_id");
            String contractCostId = orgMap.getString("contract_cost_id");
            String isSerialized = orgMap.getString("IS_SERIALIZED");
            Object quantityObj = orgMap.get("quantity");
            Object onHandObj = orgMap.get("on_hand");

            // 过滤无效项：采购数量为空/≤0 跳过
            if (quantityObj == null || StringUtils.isBlank(quantityObj.toString()) || Double.parseDouble(quantityObj.toString()) <= 0) {
                continue;
            }

            int totalQty = Integer.parseInt(quantityObj.toString());
            BO subBo = new BO();
            int historyReceive = 0;

            // 查询子表历史累计接收数（子表有数据统计能力）
            RowMap rowMap = DBSql.getMap(
                    "select sum(QUANTITY_RECEIVED) QUANTITY_RECEIVED from BO_EU_DNIVT_RECEIVE_SUB WHERE ORDER_PRODUCT_ID=? group by ORDER_PRODUCT_ID",
                    new Object[]{opId}
            );
            if (null != rowMap && rowMap.get("QUANTITY_RECEIVED") != null) {
                historyReceive = Integer.parseInt(rowMap.get("QUANTITY_RECEIVED").toString());
            }

            // 正确计算字段初始值
            int totalReceive = historyReceive;  // 累计接收数=历史数，初始0
            String unBack = String.valueOf(totalQty - totalReceive); // 未收货=采购数-历史数

            // ✅ 核心：子表设置STATUS，初始强制为【待接收】，手动填数后由业务端更新
            subBo.set("STATUS", "待接收");
            // ✅ 本次接收数初始0，必须手动输入保存后生效
            subBo.set("NOW_COUNT", 0);

            // 子表字段赋值（完整、无遗漏）
            subBo.set("QUANTITY_RECEIVED", totalReceive);
            subBo.set("QUANTITY_BACKORDERED", unBack);
            subBo.set("PRODUCT_NAME", productName);
            subBo.set("IS_SERIALIZED", isSerialized);
            subBo.set("WAREHOUSE_ID", warehouseId);
            subBo.set("ACCOUNT_NAME", accountName);
            subBo.set("CONTRAC_PROJECT_TASK_NAME", contracName);
            subBo.set("QUANTITY", totalQty);
            subBo.set("ON_HAND", onHandObj);
            subBo.set("PRODUCT_ID", productId);
            subBo.set("ORDER_PRODUCT_ID", opId);
            subBo.set("CONTRACT_COST_ID", contractCostId);

            // 查询WHOLE字段值
            int whole = DBSql.getInt("select count(1) AS CNT from BO_EU_DNCTT_CONTRACT_COST where ID=? AND IS_SERVICE_PRODUCT=1", new Object[]{contractCostId});
            subBo.set("WHOLE", whole);

            subBo.setBindId(createBOProcessInstance.getId());
            list.add(subBo);
        }

        // 无有效子表数据，返回失败
        if (list.size() == 0) {
            return fail("采购订单项都已经接收完毕");
        }

        // ===== 8. 创建采购接收主表数据（无STATUS字段，适配表结构）✅✅
        RowMap rowMap = maps.get(0);
        BO detail = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_ORDER).addQuery("PURCHASE_ORDER_NO=", rowMap.getString("purchase_order_no")).detail();
        if (null == detail) {
            return fail("未找到对应的订单");
        }

        BO bo = new BO();
        bo.setBindId(createBOProcessInstance.getId());
        bo.setId(UUID.randomUUID().toString().replace("-",""));
        bo.set("COMPANY", rowMap.getString("vendor"));
        bo.set("PURCHASE_ORDER_NO", rowMap.getString("purchase_order_no"));
        bo.set("SUBMIT_TIME", rowMap.get("CREATEDATE"));
        bo.set("FREIGHT_COST", rowMap.get("FREIGHT_COST"));
        SDK.getBOAPI().create(IVTConstant.BO_EU_DNIVT_RECEIVE_MAIN, bo, createBOProcessInstance, uc);

        // ===== 9. 创建采购接收子表数据（携带STATUS字段）=====
        SDK.getBOAPI().create(IVTConstant.BO_EU_DNIVT_RECEIVE_SUB, list, createBOProcessInstance, uc);

        // ===== 10. 生成单据URL并返回 =====
        String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), createBOProcessInstance.getId(), "", 1, "", "", "");
        url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);
        return success(url);
    }

    /**
     * 将Map中的所有key转换为大写
     * @param originalMap 原Map（key需为String类型）
     * @return 转换后的新Map
     */
    private static Map<String, Object> convertKeysToUppercase(RowMap originalMap) {
        // 创建新Map存储结果
        Map<String, Object> newMap = new HashMap<>();

        if (originalMap == null || originalMap.isEmpty()) {
            return newMap;
        }

        // 遍历原Map的键值对
        Set<Map.Entry<String, Object>> entrySet = originalMap.entrySet();
        for (Map.Entry<String, Object> entry : entrySet) {
            String originalKey = entry.getKey();
            Object value = entry.getValue();

            // 将key转换为大写（若原key为null，转换后仍为null）
            String upperKey = originalKey != null ? originalKey.toUpperCase() : null;

            // 存入新Map
            newMap.put(upperKey, value);
        }

        return newMap;
    }

    /**
     * 转string
     * @param map
     * @param var1
     * @return
     */
    public String getString(Map<String, Object> map, String var1) {
        Object var2;
        return (var2 = map.get(var1)) == null ? "" : TypeUtil.convert(var2, String.class);
    }

    public String getUnBack(String param1, String param2) {
        // TODO Auto-generated method stub
        if (StringUtils.isBlank(param1)) {
            return "0";
        }
        if (StringUtils.isBlank(param2)) {
            param2 = "0";
        }
        return BigDecimalUtil.sub(param1, param2);
    }

    /**
     *
     *   未接收数量复制给本次接收数量
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.copydata")
    public String receiveorder(String bindId, UserContext uc) {

        List<BO> list = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_RECEIVE_SUB).bindId(bindId).list();
        for (BO bo : list) {
            bo.set("BEN_RECEIVE", bo.get("QUANTITY_BACKORDERED"));
            SDK.getBOAPI().update(IVTConstant.BO_EU_DNIVT_RECEIVE_SUB, bo);
        }

        return success("");
    }


    /**
     *
     * 采购订单发起流程
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.purchaseorder")
    public String purchaseorder(String bindId, UserContext uc, String ids) {

        ids = "'" + ids.substring(0, ids.length() - 1).replace(",", "','") + "'";
        List<BO> list = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT).addQuery(" BINDID IN (" + ids + ")", null).list();

        ProcessInstance createBOProcessInstance = SDK.getProcessAPI().createBOProcessInstance(IVTConstant.obj_795cb3601f3a4b919b5896cf5b076a3a, uc.getUID(), "");
        //插入主表数据
        BO bo = new BO();
        bo.setId(UUIDGener.getUUID());
        bo.setBindId(createBOProcessInstance.getId());
        SDK.getBOAPI().create(IVTConstant.BO_EU_DNIVT_ORDER, bo, createBOProcessInstance, uc);
        //开始插入子表数据
        for (BO productBo : list) {
            BO subBo = new BO();
            subBo.set("WAREHOUSE_ID", productBo.get("WAREHOUSE_ID"));
            subBo.set("PRODUCT_ID", productBo.get("PRODUCT_ID"));

            //用最大库存数减去库存数
            double sub = BigDecimalUtil.sub(BigDecimalUtil.getDouble(productBo.getString("QUANTITY_MAXIMUM")), BigDecimalUtil.getDouble(productBo.getString("QUANTITY")));
            subBo.set("QUANTITY", sub > 0 ? sub : 0);
            subBo.setBindId(createBOProcessInstance.getId());
            SDK.getBOAPI().create(IVTConstant.BO_EU_DNIVT_ORDER_PRODUCT, subBo, createBOProcessInstance, uc);

        }
        TaskInstance taskInst = SDK.getProcessAPI().start(createBOProcessInstance).fetchActiveTasks().get(0);
        String url = SDK.getFormAPI().getFormURL("", uc.getSessionId(), createBOProcessInstance.getId(), "", 1, "", "", "");
        url = SDK.getPortalAPI().getPortalUrl() + "/r" + url.substring(1);
        return url;
    }

    /**
     * 删除库存
     * @param uc
     * @param bindId
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ivt.warehouse_product_del")
    public String warehouseProductDel(UserContext uc, String bindId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(bindId))
            return fail("请选择要删除的行");
        BO bo = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT).bindId(bindId).detail();
        if (null == bo)
            return fail("未找到对应的行");

        if (bo.getString("QUANTITY").equals("0") == false)
            return fail("库存数量不为零，不能删除！");

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

            //记录删除日志
            dn.recordFormChanges.deleteByBindidBeforeRecord(uc, IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT, bindId, "删除", conn);
            dn.recordFormChanges.deleteByBindidBeforeRecord(uc, IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT, bindId, "删除", conn);

            SDK.getBOAPI().removeByBindId(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT, bindId, conn);
            SDK.getBOAPI().removeByBindId(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT, bindId, conn);

            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                if (conn != null && !conn.isClosed())
                    conn.rollback();
            } catch (SQLException e1) {

            }
        } catch (Exception e) {

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

        return success("删除成功！");
    }


}
