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

import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

@Controller
public class testController {
    private static final Logger logger = LoggerFactory.getLogger(testController.class);
    private static final String RICH_TEXT_FIELD = "RESOLUTION";
    private static final String BO_TABLE = "BO_EU_DNSDK_TASK";
    private static final String CONTENT_SEPARATOR = "<br/><br/>";
    private static final String PARAGRAPH_START = "<p>";
    private static final String PARAGRAPH_END = "</p>";

    /**
     * 富文本字段更新接口：先获取原有内容，再拼接新内容
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_tst_updatex")
    public ResponseObject updateResolution(UserContext uc, String id, String newSolution) {
        if (StringUtils.isBlank(id)) {
            return ResponseObject.newErrResponse("ID不能为空");
        }
        if (StringUtils.isBlank(newSolution)) {
            return ResponseObject.newErrResponse("newSolution不能为空");
        }

        try {
            BO bo = SDK.getBOAPI().get(BO_TABLE, id);
            if (bo == null) {
                logger.warn("未找到ID为【{}】的记录，无法获取富文本内容", id);
                return ResponseObject.newErrResponse("未找到ID为【" + id + "】的记录");
            }

            String currentContent = bo.getString(RICH_TEXT_FIELD);
            currentContent = StringUtils.defaultString(currentContent).trim();
            logger.debug("获取到ID为【{}】的富文本原始内容：{}", id, currentContent);

            String formattedNewContent = formatNewContent(newSolution);

            String finalContent =拼接内容(currentContent, formattedNewContent);

            bo.set(RICH_TEXT_FIELD, finalContent);
            int updateCount = SDK.getBOAPI().update(BO_TABLE, bo);

            if (updateCount <= 0) {
                logger.warn("ID为【{}】的富文本更新失败", id);
                return ResponseObject.newErrResponse("富文本更新失败，无有效变更");
            }

            Map<String, Object> result = new HashMap<>(4);
            result.put("id", id);
            result.put("originalContent", currentContent);
            result.put("updatedContent", finalContent);
            result.put("updateTime", System.currentTimeMillis());

            ResponseObject response = ResponseObject.newOkResponse();
            response.setData(result);
            return response;

        } catch (Exception e) {
            logger.error("富文本更新异常，ID:{}", id, e);
            return ResponseObject.newErrResponse("更新失败：" + e.getMessage());
        }
    }

    /**
     * 拼接新旧富文本内容
     * @param currentContent 现有内容
     * @param newContent 新内容
     * @return 拼接后的完整内容
     */
    private String 拼接内容(String currentContent, String newContent) {
        // 如果现有内容为空，直接返回新内容
        if (currentContent.isEmpty()) {
            return newContent;
        }

        // 如果现有内容以段落结束标签结尾，在其前面插入新内容
        if (currentContent.endsWith(PARAGRAPH_END)) {
            int endIndex = currentContent.lastIndexOf(PARAGRAPH_END);
            return currentContent.substring(0, endIndex) +
                    newContent +
                    PARAGRAPH_END;
        } else {
            // 其他情况直接拼接
            return currentContent + CONTENT_SEPARATOR + newContent;
        }
    }

    /**
     * 格式化新内容，确保富文本格式正确
     */
    private String formatNewContent(String newContent) {
        String trimmedContent = newContent.trim();
        // 如果新内容已经包含段落标签，直接返回
        if (trimmedContent.startsWith(PARAGRAPH_START) && trimmedContent.endsWith(PARAGRAPH_END)) {
            return trimmedContent;
        }
        // 否则添加段落标签
        return PARAGRAPH_START + trimmedContent + PARAGRAPH_END;
    }

    // 状态更新方法（建议也统一使用BOAPI风格）
    @Mapping(value = "com.awspaas.user.apps.donenow_tst_updatestatus")
    public ResponseObject updateStatus(UserContext uc, String id, String status) {
        if (StringUtils.isBlank(id)) {
            return ResponseObject.newErrResponse("工单ID不能为空");
        }
        if (StringUtils.isBlank(status)) {
            return ResponseObject.newErrResponse("状态值不能为空");
        }

        try {
            // 使用BOAPI更新状态（仅修改STATUS_ID字段）
            BO bo = SDK.getBOAPI().get("BO_EU_DNSDK_TASK", id);
            if (bo == null) {
                return ResponseObject.newErrResponse("未找到ID为【" + id + "】的记录");
            }
            bo.set("STATUS_ID", status); // 仅更新状态字段
            int updateCount = SDK.getBOAPI().update("BO_EU_DNSDK_TASK", bo);

            if (updateCount <= 0) {
                return ResponseObject.newErrResponse("ID为【" + id + "】的状态更新失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("id", id);
            result.put("updatedStatus", status);

            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.setData(result);
            return responseObject;
        } catch (Exception e) {
            return ResponseObject.newErrResponse("状态更新失败：" + e.getMessage());
        }
    }

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

        if (StringUtils.isBlank(accountId)) {
            return ResponseObject.newErrResponse("账户ID不能为空");
        }

        // 1. 查询账户基本信息（包含DISTRICT_ID）
        String accountSql = "select ADDRESS, DISTRICT_ID from BO_EU_DNCRM_ACCOUNT where id = ?";
        RowMap accountMap = DBSql.getMap(accountSql, new Object[]{accountId});

        if (accountMap == null) {
            return ResponseObject.newErrResponse("未找到ID为【" + accountId + "】的账户信息");
        }

        // 2. 根据DISTRICT_ID查询地区名称
        String districtId = accountMap.getString("DISTRICT_ID");
        String districtName = "";
        if (StringUtils.isNotBlank(districtId)) {
            String dictSql = "select CNNAME from bo_act_dict_kv_item where ITEMNO = ? and DICTKEY = 'GB.ADDR'";
            RowMap dictMap = DBSql.getMap(dictSql, new Object[]{districtId});
            districtName = dictMap != null ? dictMap.getString("CNNAME") : "";
        }

        // 3. 封装结果（包含原始地区ID和查询到的地区名称）
        Map<String, Object> result = new HashMap<>();
        result.put("ADDRESS", accountMap.getString("ADDRESS"));
        result.put("DISTRICT_ID", districtId);
        result.put("DISTRICT_NAME", districtName); // 新增地区名称字段

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

        return responseObject;
    }



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

        if (StringUtils.isBlank(accountId)) {
            return ResponseObject.newErrResponse("账户ID不能为空");
        }

        String sql = "select count(*) as task_count from BO_EU_DNSDK_TASK where account_id = ? and type_id=1809";
        RowMap map = DBSql.getMap(sql, new Object[]{accountId});

        int taskCount = map.getInt("task_count");

        Map<String, Object> result = new HashMap<>();
        result.put("task_count", taskCount);
        result.put("account_id", accountId);

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

        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryTaskCountByContactId") public ResponseObject queryTaskCountByContactId(UserContext uc, String contactId) {
        if (StringUtils.isBlank (contactId)) {
            return ResponseObject.newErrResponse ("联系人 ID 不能为空");
        }

        String sql = "select count(*) as task_count from BO_EU_DNSDK_TASK where contact_id = ? and type_id=1809";
        RowMap map = DBSql.getMap(sql, new Object[]{contactId});

        int taskCount = map.getInt("task_count");

        Map<String, Object> result = new HashMap<>();
        result.put("task_count", taskCount);
        result.put("contact_id", contactId);

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

        return responseObject;
    }

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

        if (StringUtils.isBlank(installedProductId)) {
            return ResponseObject.newErrResponse("配置项ID不能为空");
        }

        String sql = "select count(*) as task_count from BO_EU_DNSDK_TASK where INSTALLED_PRODUCT_ID = ?";
        RowMap map = DBSql.getMap(sql, new Object[]{installedProductId});

        int taskCount = map.getInt("task_count");

        Map<String, Object> result = new HashMap<>();
        result.put("task_count", taskCount);
        result.put("installed_product_id", installedProductId);

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

        return responseObject;
    }


    @Mapping(value = "com.awspaas.user.apps.donenow_ivt.queryProductInfoByBindid")
    public ResponseObject queryProductInfoByBindid(UserContext uc, String bindid) {
        // 参数校验
        if (StringUtils.isBlank(bindid)) {
            return ResponseObject.newErrResponse("bindid不能为空");
        }

        // 1. 查询产品基础信息
        String productSql = "SELECT " +
                "LOCATION, " +
                "CONTACT_ID, " +
                "START_DATE, " +
                "THROUGH_DATE, " +
                "VENDOR_ACCOUNT_ID " +
                "FROM BO_EU_DNCRM_INSTALLED_PRODUCT " +
                "WHERE bindid = ?";
        RowMap productMap = DBSql.getMap(productSql, new Object[]{bindid});

        if (productMap == null) {
            return ResponseObject.newErrResponse("未找到bindid为【" + bindid + "】的产品数据");
        }

        // 2. 计算保修期（保持原有逻辑）
        Date startDate = productMap.getDate("START_DATE");
        Date throughDate = productMap.getDate("THROUGH_DATE");
        long warrantyDays = 0;
        String warrantyDesc = "";

        if (startDate == null || throughDate == null) {
            warrantyDesc = "日期信息不完整";
        } else if (throughDate.before(startDate)) {
            warrantyDesc = "日期范围异常";
        } else {
            warrantyDays = (throughDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000);
            warrantyDesc = warrantyDays + "天";
        }

        // 3. 查询联系人名称（与之前逻辑一致）
        String contactId = productMap.getString("CONTACT_ID");
        String contactName = "";
        if (StringUtils.isNotBlank(contactId)) {
            String contactSql = "SELECT NAME FROM BO_EU_DNCRM_CONTACT WHERE id = ?";
            RowMap contactMap = DBSql.getMap(contactSql, new Object[]{contactId});
            contactName = contactMap != null ? contactMap.getString("NAME") : "未知联系人";
        }

        // 4. 新增：查询供应商名称（与联系人逻辑相同）
        String vendorAccountId = productMap.getString("VENDOR_ACCOUNT_ID");
        String vendorName = "";
        if (StringUtils.isNotBlank(vendorAccountId)) {
            String vendorSql = "SELECT NAME FROM bo_eu_dncrm_account WHERE id = ?";
            RowMap vendorMap = DBSql.getMap(vendorSql, new Object[]{vendorAccountId});
            vendorName = vendorMap != null ? vendorMap.getString("NAME") : "未知供应商";
        }

        // 5. 封装结果（包含联系人和供应商名称）
        Map<String, Object> result = new HashMap<>();
        result.put("LOCATION", productMap.getString("LOCATION"));
        result.put("CONTACT_ID", contactId);
        result.put("CONTACT_NAME", contactName); // 联系人名称
        result.put("VENDOR_ACCOUNT_ID", vendorAccountId);
        result.put("VENDOR_NAME", vendorName);   // 新增：供应商名称
        result.put("WARRANTY_DAYS", warrantyDays);
        result.put("WARRANTY_DESC", warrantyDesc);

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

        return responseObject;
    }


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

        if (StringUtils.isBlank(taskId)) {
            return ResponseObject.newErrResponse("任务ID不能为空");
        }

        // 使用 SUM 函数直接在 SQL 中计算总工时
        String sql = "SELECT SUM(hours_worked) AS total_hours FROM BO_EU_DNSDK_WORK_ENTRY WHERE task_id = ?";
        RowMap map = DBSql.getMap(sql, new Object[]{taskId});

        // 处理总工时获取，若为null或非数值类型则设为0.0
        double totalHours;
        if (map != null) {
            Object hoursObj = map.get("total_hours");
            if (hoursObj != null && hoursObj instanceof Number) {
                totalHours = ((Number) hoursObj).doubleValue();
            } else {
                totalHours = 0.0;
            }
        } else {
            totalHours = 0.0;
        }

        Map<String, Object> result = new HashMap<>();
        result.put("total_hours", totalHours);
        result.put("task_id", taskId);

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

        return responseObject;
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_crm.batchUpdateExpenseReportIds")
    public ResponseObject batchUpdateExpenseReportIds(UserContext uc, String idsJson, String oid) {
        try {
            // 1. 校验入参
            if (idsJson == null || idsJson.trim().isEmpty()) {
                return ResponseObject.newErrResponse("idsJson 参数不能为空");
            }
            if (oid == null || oid.trim().isEmpty()) {
                return ResponseObject.newErrResponse("oid 参数不能为空");
            }

            // 2. 将 JSON 字符串转换为 List<String>
            List<String> ids;
            try {
                ids = JSON.parseObject(idsJson, new TypeReference<List<String>>() {});
            } catch (Exception e) {
                return ResponseObject.newErrResponse("idsJson 格式错误，请传入合法的JSON数组字符串。");
            }

            if (ids.isEmpty()) {
                return ResponseObject.newErrResponse("ids 数组不能为空");
            }

            // 3. 构建批量更新的 SQL 语句
            StringBuilder sql = new StringBuilder();
            sql.append("UPDATE BO_EU_DNSDK_EXPENSE ");
            sql.append("SET EXPENSE_REPORT_ID = ? "); // 假设更新EXPENSE_REPORT_ID字段为oid
            sql.append("WHERE id IN (");

            List<Object> paramList = new ArrayList<>();
            paramList.add(oid); // 先添加要更新的值

            for (int i = 0; i < ids.size(); i++) {
                sql.append("?");
                if (i < ids.size() - 1) {
                    sql.append(", ");
                }
                paramList.add(ids.get(i));
            }
            sql.append(")");

            // 4. 执行批量更新
            int affectedRows = DBSql.update(sql.toString(), paramList.toArray());

            // 5. 封装并返回响应数据
            Map<String, Object> result = new HashMap<>(1);
            result.put("affectedRows", affectedRows); // 返回受影响的行数wsm

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

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseObject.newErrResponse("批量更新失败：" + e.getMessage());
        }
    }
}
