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.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.awspaas.user.apps.donenow_ivt.constant.IVTConstant;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@Controller
public class caiController {

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryCai")
    public ResponseObject queryOrderByOrderId(UserContext uc, String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }

        String sql = "select COST_TOTAL, ORDER_ID from bo_eu_dnivt_order_product where ORDER_ID = ?";
        List<RowMap> rowMaps = DBSql.getMaps(sql, new Object[]{orderId});
        System.out.println("采购项查询结果数量：" + (rowMaps != null ? rowMaps.size() : 0));

        List<Map<String, Object>> resultList = new ArrayList<>();
        if (rowMaps != null && !rowMaps.isEmpty()) {
            for (RowMap row : rowMaps) {
                Map<String, Object> orderItem = new HashMap<>();
                orderItem.put("COST_TOTAL", row.getDouble("COST_TOTAL"));
                orderItem.put("ORDER_ID", row.getString("ORDER_ID"));
                resultList.add(orderItem);
                System.out.println("已添加采购项数据：" + orderItem);
            }
        } else {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到ORDER_ID为【" + orderId + "】的采购项，可尝试检查订单ID或新建");
            responseObject.setData(Collections.emptyList());
            System.out.println("未查询到采购项数据，ORDER_ID：" + orderId);
            return responseObject;
        }

        System.out.println("采购项查询最终结果总数：" + resultList.size());

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(resultList);
        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryCount")
    public ResponseObject queryPurchaseItemCount(UserContext uc, String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }

        String sql = "select count(*) as item_count from bo_eu_dnivt_order_product where ORDER_ID = ?";
        int itemCount = DBSql.getInt(sql, new Object[]{orderId});

        Map<String, Object> result = new HashMap<>();
        result.put("orderId", orderId);
        result.put("itemCount", itemCount);
        result.put("isSingleItem", itemCount == 1);

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

        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryPaymentPlan")
    public ResponseObject queryPaymentPlan(UserContext uc, String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }

        String mainSql = "SELECT " +
                "a.order_id 采购订单id, " +
                "a.CONTRACT_SERVICE_ID 合同服务ID, " +
                "b.PERIOD_END_DATE 计划付款时间, " +
                "b.PERIOD_COST 计划付款金额 " +
                "FROM `BO_EU_DNIVT_ORDER_PRODUCT` a " +
                "JOIN `BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD` b " +
                "ON a.CONTRACT_SERVICE_ID = b.CONTRACT_SERVICE_ID " +
                "WHERE a.ORDER_ID = ?";
        List<RowMap> mainRowMaps = DBSql.getMaps(mainSql, new Object[]{orderId});
        System.out.println("主表查询结果数量：" + (mainRowMaps != null ? mainRowMaps.size() : 0));

        List<Map<String, Object>> resultList = new ArrayList<>();
        Set<String> processedServiceIds = new HashSet<>();

        if (mainRowMaps != null && !mainRowMaps.isEmpty()) {

            for (RowMap mainRow : mainRowMaps) {
                Map<String, Object> plan = new HashMap<>();
                plan.put("order_id", mainRow.getString("采购订单id"));
                plan.put("计划付款时间", mainRow.getString("计划付款时间"));
                plan.put("计划付款金额", mainRow.getDouble("计划付款金额"));
                resultList.add(plan);

                Object contractServiceObj = mainRow.get("合同服务ID");
                String contractServiceId = contractServiceObj != null ? contractServiceObj.toString() : null;
                System.out.println("当前行CONTRACT_SERVICE_ID：" + contractServiceId +
                        "（类型：" + (contractServiceObj != null ? contractServiceObj.getClass().getSimpleName() : "null") + "）");

                if (StringUtils.isNotBlank(contractServiceId) && !processedServiceIds.contains(contractServiceId)) {
                    processedServiceIds.add(contractServiceId);

                    String adjustSql = "SELECT " +
                            "effective_date 计划付款时间, " +
                            "prorated_cost_change 计划付款金额 " +
                            "FROM `BO_EU_DNCTT_CONTRACT_SERVICE_ADJUST` " +
                            "WHERE CAST(CONTRACT_SERVICE_ID AS CHAR) = ?";

                    System.out.println("执行服务调整表查询SQL：" + adjustSql + "，参数：" + contractServiceId);
                    List<RowMap> adjustRowMaps = DBSql.getMaps(adjustSql, new Object[]{contractServiceId});
                    System.out.println("服务调整表查询结果数量：" + (adjustRowMaps != null ? adjustRowMaps.size() : 0));


                    if (adjustRowMaps != null && !adjustRowMaps.isEmpty()) {

                        for (RowMap adjustRow : adjustRowMaps) {
                            Map<String, Object> adjustPlan = new HashMap<>();
                            adjustPlan.put("order_id", orderId);
                            adjustPlan.put("计划付款时间", adjustRow.getString("计划付款时间"));
                            adjustPlan.put("计划付款金额", adjustRow.getDouble("计划付款金额"));
                            resultList.add(adjustPlan);
                            System.out.println("已添加服务调整数据：" + adjustPlan);
                        }
                    } else {
                        System.out.println("服务调整表无数据，CONTRACT_SERVICE_ID：" + contractServiceId);

                        String checkSql = "SELECT COUNT(1) AS cnt FROM `BO_EU_DNCTT_CONTRACT_SERVICE_ADJUST` WHERE CAST(CONTRACT_SERVICE_ID AS CHAR) = ?";
                        List<RowMap> checkMaps = DBSql.getMaps(checkSql, new Object[]{contractServiceId});
                        if (checkMaps != null && !checkMaps.isEmpty()) {
                            System.out.println("数据库中实际存在的记录数：" + checkMaps.get(0).getInt("cnt"));
                        }
                    }
                }
            }
        } else {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到ORDER_ID为【" + orderId + "】的计划付款信息，可尝试新建");
            responseObject.setData(Collections.emptyList());
            return responseObject;
        }

        System.out.println("最终结果总数：" + resultList.size() + "（主表" + mainRowMaps.size() + "条 + 服务调整" + (resultList.size() - mainRowMaps.size()) + "条）");
        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(resultList);
        return responseObject;
    }


    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryPayAmount")
    public ResponseObject queryPayAmount(UserContext uc, String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }

        String sql = "select " +
                "ORDER_ID 采购订单id, " +
                "PAY_AMOUNT 实际付款金额 " +
                "from `BO_EU_DNIVT_ORDER_PAYMENT_PLAN` " +
                "where ORDER_ID = ?";
        List<RowMap> rowMaps = DBSql.getMaps(sql, new Object[]{orderId});

        List<Map<String, Object>> resultList = new ArrayList<>();
        if (rowMaps != null && !rowMaps.isEmpty()) {
            for (RowMap row : rowMaps) {
                Map<String, Object> amountInfo = new HashMap<>();
                amountInfo.put("order_id", orderId);
                amountInfo.put("实际付款金额", row.getDouble("实际付款金额"));
                resultList.add(amountInfo);
            }
        } else {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到ORDER_ID为【" + orderId + "】的实际金额信息，可尝试新建");
            responseObject.setData(Collections.emptyList());
            return responseObject;
        }

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(resultList);
        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.deleteUnpaidPaymentPlan")
    public ResponseObject deleteUnpaidPaymentPlan(UserContext uc, String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }
        System.out.println("代码中接收到的 orderId：" + orderId);
        String sql = "delete from `BO_EU_DNIVT_ORDER_PAYMENT_PLAN` " +
                "where ORDER_ID = ? " +
                "and (PAY_AMOUNT is null or PAY_AMOUNT = 0)";
        int deletedRows = DBSql.update(sql, new Object[]{orderId});

        if (deletedRows <= 0) {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到ORDER_ID为【" + orderId + "】的删除信息，可尝试新建");
            responseObject.setData(Collections.emptyList());
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> deleteInfo = new HashMap<>();
        deleteInfo.put("order_id", orderId);
        deleteInfo.put("删除记录数", deletedRows);
        resultList.add(deleteInfo);

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

        return responseObject;
    }


    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.createPaymentPlan")
    public ResponseObject createPaymentPlan(UserContext uc,
                                            String orderId,
                                            String planDate,
                                            Double planAmount) {
        // 参数校验
        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }
        if (StringUtils.isBlank(planDate)) {
            return ResponseObject.newErrResponse("计划付款时间不能为空");
        }

        try {
            // 用原生SQL查询订单表，获取VENDOR_ACCOUNT_ID（与queryPayAmount风格一致）
            String querySql = "select VENDOR_ACCOUNT_ID from BO_EU_DNIVT_ORDER where ID = ?";
            List<RowMap> orderRows = DBSql.getMaps(querySql, new Object[]{orderId});

            if (orderRows == null || orderRows.isEmpty()) {
                return ResponseObject.newErrResponse("订单不存在，orderId=" + orderId);
            }
            String vendorAccountId = orderRows.get(0).getString("VENDOR_ACCOUNT_ID");
            if (StringUtils.isBlank(vendorAccountId)) {
                return ResponseObject.newErrResponse("订单对应的VENDOR_ACCOUNT_ID为空，orderId=" + orderId);
            }

            // 创建流程实例（保持原有逻辑不变）
            ProcessInstance processInstance = SDK.getProcessAPI()
                    .createProcessInstance("obj_5cb4ae4a42944fd0a9a284ff4c64c65d",
                            uc.getUID(),
                            "付款计划");
            String bindId = processInstance.getId();

            // 构建BO对象并创建业务数据（保持原有逻辑不变）
            BO bo = new BO();
            bo.setBindId(bindId);
            bo.set("ORDER_ID", orderId);
            bo.set("PLAN_DATE", planDate);
            bo.set("PLAN_AMOUNT", planAmount);
            bo.set("ACCOUNT_PAYEE", vendorAccountId);

            String orderProductNames = DBSql.getString("SELECT GROUP_CONCAT(NAME SEPARATOR '、') FROM BO_EU_DNIVT_ORDER_PRODUCT WHERE ORDER_ID=?", new Object[]{orderId});
            //最长300个字符，需要截取
            if (orderProductNames.length() > 300) {
                orderProductNames = orderProductNames.substring(0, 300);
            }
            //付款说明
            bo.set("PAY_DESC", orderProductNames);

            SDK.getBOAPI().createDataBO("BO_EU_DNIVT_ORDER_PAYMENT_PLAN", bo, uc);

            // 组装返回结果（与queryPayAmount风格一致）
            List<Map<String, Object>> resultList = new ArrayList<>();
            Map<String, Object> plan = new HashMap<>();
            plan.put("order_id", orderId);
            plan.put("计划付款时间", planDate);
            plan.put("计划付款金额", planAmount);
            plan.put("bindId", bindId);
            plan.put("ACCOUNT_PAYEE", vendorAccountId);
            resultList.add(plan);

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

            return responseObject;

        } catch (Exception e) {
            return ResponseObject.newErrResponse("创建失败：" + e.getMessage());
        }
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryNonServiceOrderDate")
    public ResponseObject queryNonServiceOrderDate(UserContext uc, String orderId) {

        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }

        // 2. 查询BO_EU_DNIVT_ORDER表的EXPECTED_SHIP_DATE字段（条件：id=order_id）
        String sql = "select EXPECTED_SHIP_DATE " +
                "from `BO_EU_DNIVT_ORDER` " +
                "where id = ? ";
        String expectedShipDate = DBSql.getString(sql, new Object[]{orderId});

        if (StringUtils.isBlank(expectedShipDate)) {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到ORDER_ID为【" + orderId + "】的预期发货日期（EXPECTED_SHIP_DATE）");
            responseObject.setData(Collections.emptyList());
            return responseObject;
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> dateInfo = new HashMap<>();
        dateInfo.put("order_id", orderId);
        dateInfo.put("EXPECTED_SHIP_DATE", expectedShipDate);
        resultList.add(dateInfo);

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(resultList);
        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryNonServiceOrderPrice")
    public ResponseObject queryNonServiceOrderPrice(UserContext uc, String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }

        String sql = "select sum(COST_TOTAL) " +
                "from `bo_eu_dnivt_order_product` " +
                "where order_id = ? ";

        String priceStr = DBSql.getString(sql, new Object[]{orderId});

        if (StringUtils.isBlank(priceStr)) {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到ORDER_ID为【" + orderId + "】的总金额（COST_TOTAL）");
            responseObject.setData(Collections.emptyList());
            return responseObject;
        }

        Double costTotal = null;
        try {
            costTotal = Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            return ResponseObject.newErrResponse("总金额格式错误：" + priceStr);
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> priceInfo = new HashMap<>();
        priceInfo.put("order_id", orderId);
        priceInfo.put("COST_TOTAL", costTotal);
        resultList.add(priceInfo);

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(resultList);
        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryNonServicePaymentPlan")
    public ResponseObject queryNonServicePaymentPlan(UserContext uc, String orderId) {

        if (StringUtils.isBlank(orderId)) {
            return ResponseObject.newErrResponse("订单ID不能为空");
        }

        String sql = "select * from bo_eu_dnivt_order_payment_plan where ORDER_ID = ?";

        try {
            List<RowMap> rowMapList = DBSql.getMaps(sql, new Object[]{orderId});

//            if (rowMapList == null || rowMapList.isEmpty()) {
//                return ResponseObject.newErrResponse("未找到ORDER_ID为【" + orderId + "】的付款计划数据");
//            }

            List<Map<String, Object>> resultList = new ArrayList<>();
            for (RowMap map : rowMapList) {
                Map<String, Object> result = new HashMap<>();
                result.put("ORDER_ID", map.getString("ORDER_ID"));
                result.put("PLAN_DATE", map.getString("PLAN_DATE"));
                result.put("PLAN_AMOUNT", map.getDouble("PLAN_AMOUNT"));
                resultList.add(result);
            }

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

            return responseObject;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseObject.newErrResponse("查询失败：" + e.getMessage());
        }
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryContractByDes")
    public ResponseObject queryContractByDes(UserContext uc, String des) {
        if (StringUtils.isBlank(des)) {
            return ResponseObject.newErrResponse("des（合同ID）不能为空");
        }

        String sql = "select description " +
                "from `BO_EU_DNCTT_CONTRACT` " +
                "where id = ? ";

        String contractName = DBSql.getString(sql, new Object[]{des});

        if (StringUtils.isBlank(contractName)) {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到id为【" + des + "】的合同信息");
            responseObject.setData(Collections.emptyList());
            return responseObject;
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> contractInfo = new HashMap<>();
        contractInfo.put("id", des);
        contractInfo.put("CONTRACT_NAME", contractName);
        resultList.add(contractInfo);

        ResponseObject responseObject = ResponseObject.newOkResponse();
        responseObject.setData(resultList);
        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.checkDeliveryTimeRequired")
    public ResponseObject checkDeliveryTimeRequired(UserContext uc, String purchaseOrderId) {
        if (StringUtils.isBlank(purchaseOrderId)) {
            return ResponseObject.newErrResponse("采购订单ID不能为空");
        }

        String countSql = "select count(1) from `bo_eu_dnivt_order_product` where order_id = ?";
        String countStr = DBSql.getString(countSql, new Object[]{purchaseOrderId});
        if (StringUtils.isBlank(countStr) || "0".equals(countStr.trim())) {
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.put("message", "未找到ORDER_ID为【" + purchaseOrderId + "】的采购项信息");
            responseObject.put("deliveryTimeRequired", false);
            responseObject.setData(Collections.emptyList());
            return responseObject;
        }

        boolean deliveryTimeRequired = false;
        String errorMsg = "";

        String productSql = "select CONTRACT_COST_ID from `bo_eu_dnivt_order_product` where order_id = ?";
        List<String> contractCostIdList = new ArrayList<>();
        String costIdSql = "select GROUP_CONCAT(CONTRACT_COST_ID) from `bo_eu_dnivt_order_product` where order_id = ?";
        String costIdsStr = DBSql.getString(costIdSql, new Object[]{purchaseOrderId});
        if (StringUtils.isNotBlank(costIdsStr)) {
            String[] costIdArray = costIdsStr.split(",");
            for (String costId : costIdArray) {
                if (StringUtils.isNotBlank(costId)) {
                    contractCostIdList.add(costId.trim());
                }
            }
        }

        for (String contractCostId : contractCostIdList) {
            if (StringUtils.isBlank(contractCostId)) {
                deliveryTimeRequired = true;
                errorMsg = "存在成本ID为空的采购项，配送日期必填";
                break;
            }

            String serviceSql = "select IS_SERVICE_PRODUCT from `bo_eu_dnctt_contract_cost` where ID = ?";
            String isServiceProduct = DBSql.getString(serviceSql, new Object[]{contractCostId});

            if (StringUtils.isBlank(isServiceProduct)) {
                deliveryTimeRequired = true;
                errorMsg = "成本ID【" + contractCostId + "】无对应合同产品，配送日期必填";
                break;
            }

            if (!"1".equals(isServiceProduct.trim())) {
                deliveryTimeRequired = true;
                errorMsg = "存在非服务创建的合同产品（成本ID：" + contractCostId + "），配送日期必填";
                break;
            }
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> checkInfo = new HashMap<>();
        checkInfo.put("purchaseOrderId", purchaseOrderId);
        checkInfo.put("deliveryTimeRequired", deliveryTimeRequired);
        checkInfo.put("message", deliveryTimeRequired ? errorMsg : "所有采购项均符合要求，配送日期非必填");
        resultList.add(checkInfo);

        ResponseObject responseObject = ResponseObject.newOkResponse();
        if (deliveryTimeRequired) {
            responseObject.put("message", errorMsg);
        } else {
            responseObject.put("message", "未找到需要必填配送日期的场景，配送日期非必填");
        }
        responseObject.setData(resultList);
        return responseObject;
    }



}
