package com.awspaas.user.apps.donenow_crm.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.htmlframework.HtmlPageTemplate;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.donenow_crm.constant.CrmConstant;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    /**
     * 删除客户
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_DelAccount")
    public ResponseObject delAccount(UserContext uc, String ids) throws SQLException {
        if (StringUtils.isBlank(ids)) return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_ACCOUNT";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null)
            return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {
            //引用校验
            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {
                BO bo = SDK.getBOAPI().get(tableName, id);
                if (hasColumn(conn, tableName, "CLOSED")) {
                    bo.set("CLOSED", 1);
                    SDK.getBOAPI().update(tableName, bo, conn);
                } else {
                    SDK.getBOAPI().remove(tableName, id, conn);
                }

                List<BO> contacts = SDK.getBOAPI().query("BO_EU_DNCRM_CONTACT").addQuery("ACCOUNT_ID=", id).addQuery("CLOSED=", 0).list();
                for (BO contact : contacts) {
                    contact.set("CLOSED", 1);
                    SDK.getBOAPI().update("BO_EU_DNCRM_CONTACT", contact, conn);

                    //删除 组织中对应的用户
                    String userId = DBSql.getString(conn, "SELECT USERID FROM orguser WHERE ext5=? AND CLOSED=0 ", new Object[]{contact.getId()});
                    if (StringUtils.isNotBlank(userId)) SDK.getORGAPI().disabledUser(userId);//禁用组织中用户
                }

                List<BO> installedProducts = SDK.getBOAPI().query("BO_EU_DNCRM_INSTALLED_PRODUCT").addQuery("ACCOUNT_ID=", id).addQuery("CLOSED=", '0').list();
                for (BO installedProduct : installedProducts) {
                    installedProduct.set("CLOSED", '1');
                    SDK.getBOAPI().update("BO_EU_DNCRM_INSTALLED_PRODUCT", installedProduct, conn);
                }


                List<BO> address = SDK.getBOAPI().query("BO_EU_DNCRM_LOCATION").addQuery("ACCOUNT_ID=", id).addQuery("CLOSED=", 0).list();
                for (BO addressBO : address) {
                    addressBO.set("CLOSED", 1);
                    SDK.getBOAPI().update("BO_EU_DNCRM_LOCATION", addressBO, conn);
                }

            }
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null) DBSql.close(conn);
        }
        return ResponseObject.newOkResponse();
    }

    /**
     * 仅用于判断客户主表是否包含CLOSED字段（新增工具方法）
     */
    private boolean hasColumn(Connection conn, String tableName, String columnName) throws SQLException {
        try (ResultSet rs = conn.getMetaData().getColumns(null, null, tableName, columnName)) {
            return rs.next();
        }
    }


    /**
     * 删除联系人
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_DelContact")
    public ResponseObject delContact(UserContext uc, String ids) throws SQLException {
        if (StringUtils.isBlank(ids)) return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_CONTACT";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null) return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {

            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {
/*
            if (DBSql.getInt(conn,"SELECT COUNT(*) from BO_EU_DNSDK_TASK where contact_id=? and closed=0",new Object[]{id}) > 0)
            {
                return "该联系人是公司的外包联系人（工单中的外包人员）";
            }
*/
                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNSDK_TASK where contact_id=? and closed=0", new Object[]{id}) > 0) {
                    throw new Exception("该联系人有关联的工单或任务");
                }

                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNCOM_ACTIVITY where CREATEUSER=(SELECT USERID FROM orguser WHERE ext5=? ) ", new Object[]{id}) > 0) {
                    throw new Exception("该联系人在自助服务台创建过工单备注");
                }
/*

            if (_dal.FindSignleBySql<int>($"SELECT COUNT(*) from com_attachment where create_user_id={id} and delete_time=0") > 0)
            {
                return "该联系人在自助服务台创建过附件";
            }
*/

                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNCTT_CONTRACT where (contact_id=? OR bill_to_contact_id=?)  and closed=0", new Object[]{id, id}) > 0) {
                    throw new Exception("该联系人是客户的账单联系人");
                }

                if (DBSql.getInt(conn, "SELECT COUNT(*) from BO_EU_DNCRM_ACCOUNT_REFERENCE where email_to_contacts=? and closed=0", new Object[]{id}) > 0) {
                    throw new Exception("该联系人是客户的唯一的一个发票邮件接收人");
                }

                //Contacts联系人 删除
                BO contact = SDK.getBOAPI().get("BO_EU_DNCRM_CONTACT", id);
                contact.set("CLOSED", "1");
                SDK.getBOAPI().update("BO_EU_DNCRM_CONTACT", contact, conn);

                //删除 组织中对应的用户
                String userId = DBSql.getString(conn, "SELECT USERID FROM orguser WHERE ext5=? AND CLOSED=0 ", new Object[]{contact.getId()});
                if (StringUtils.isNotBlank(userId)) SDK.getORGAPI().disabledUser(userId);//禁用组织中用户

                //配置项逻辑删除
                List<BO> installedProducts = SDK.getBOAPI().query("BO_EU_DNCRM_INSTALLED_PRODUCT").addQuery("CONTACT_ID=", id).addQuery("CLOSED=", 0).list();
                for (BO installedProduct : installedProducts) {
                    installedProduct.set("CLOSED", "1");
                    SDK.getBOAPI().update("BO_EU_DNCRM_INSTALLED_PRODUCT", installedProduct, conn);
                }
            }


            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null) DBSql.close(conn);
        }
        return ResponseObject.newOkResponse();

    }

    /**
     * 删除配置项
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_DelInstallProd")
    public ResponseObject delInstallProd(UserContext uc, String ids) throws SQLException {

        if (StringUtils.isBlank(ids)) return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_INSTALLED_PRODUCT";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null) return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {

            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {

                BO installProd = SDK.getBOAPI().get(tableName, id);
                installProd.set("CLOSED", "1");
                SDK.getBOAPI().update(tableName, installProd, conn);

                //合同成本  修改项目成本
                String CONTRACT_COST_ID = installProd.getString("CONTRACT_COST_ID");
                if (StringUtils.isNotBlank(CONTRACT_COST_ID)) {
                    BO contractCost = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_COST", CONTRACT_COST_ID);
                    contractCost.set("CREATE_CI", "0");
                    SDK.getBOAPI().update("BO_EU_DNCRM_CONTRACT_COST", contractCost, conn);
                }

            }


            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null) DBSql.close(conn);
        }

        return ResponseObject.newOkResponse();
    }


    /**
     * 删除地址
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_delLocation")
    public ResponseObject delLocation(UserContext uc, String ids) throws SQLException {

        if (StringUtils.isBlank(ids)) return ResponseObject.newErrResponse("请选择要删除的数据");

        String tableName = "BO_EU_DNCRM_LOCATION";

        //引用校验
        String result = verifyDel(tableName, ids);
        if (result != null) return ResponseObject.newErrResponse(result);

        Connection conn = null;
        try {

            conn = DBSql.open();
            conn.setAutoCommit(false);

            for (String id : ids.split(",")) {

                BO contact = SDK.getBOAPI().get(tableName, id);
                contact.set("CLOSED", "1");
                SDK.getBOAPI().update(tableName, contact, conn);

            }

            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null) DBSql.close(conn);
        }

        return ResponseObject.newOkResponse();
    }


    private String verifyDel(String tableName, String ids) {
        RowMap verify = DBSql.getMap("select * from BO_EU_DNSYS_DELETE_VERIFY where CODE=?", new Object[]{tableName});
        String sql = null;
        if (verify != null && StringUtils.isNotBlank(verify.getString("SEL_SQL"))) {
            sql = verify.getString("SEL_SQL");
            for (String id : ids.split(",")) {
                id = DBSql.getString("select ID from " + tableName + " where ID=?", new Object[]{id});
                if (StringUtils.isBlank(id) || id.length() < 2) continue;

                //String sqlById = sql.replace("**id**", "'" + id + "'");
                String sqlById = sql.replaceAll("\\*\\*id\\*\\*", "'" + id + "'");

                logger.info("BO_EU_DNSYS_DELETE_VERIFY----" + sqlById);

                List<RowMap> list = DBSql.getMaps(sqlById);
                if (!list.isEmpty()) {
                    String errMsg = StringUtils.EMPTY;
                    for (RowMap rowMap : list) {
                        if (rowMap.containsKey("name")) rowMap.put("NAME", rowMap.get("name"));
                        if (rowMap.containsKey("num")) rowMap.put("NUM", rowMap.get("num"));

                        errMsg += rowMap.getString("NAME") + rowMap.getString("NUM") + "\r\n";
                    }
                    return "删除失败，被以下数据引用：\r\n" + errMsg;
                }
            }
        }
        return null;
    }

    @Mapping("com.awspaas.user.apps.donenow_crm.querydepartment")
    public String findPchSelect(String accountId, UserContext uc) {
        RowMap map = DBSql.getMap("SELECT * FROM orgdepartment WHERE EXT1=?", new Object[]{accountId});
        if (map == null) {
            return fail("���ȱ�����������");
        }
        return success("����ɹ�");

    }


    @Mapping("com.awspaas.user.apps.donenow_crm.queryhtml")
    public String queryhtml(String cateId, String objectId, UserContext uc) {
        System.out.println("cateId:" + cateId);
        System.out.println("objectId:" + objectId);

        Map<String, Object> map = new HashMap<>();
        map.put("uid", uc.getUID());
        map.put("sid", uc.getSessionId());
        map.put("cateId", cateId);
        map.put("objectId", objectId);

        String ORGID = uc.getCompanyModel().getId();
        System.out.println("ORGID:" + ORGID);
        //��ѯ����������
        BO detail = SDK.getBOAPI().query(CrmConstant.BO_EU_DNSYS_UDF_GROUP).detailById(cateId);
        if (null == detail) {
            return StringUtils.EMPTY;
        }
        //��ѯ�����������Զ����ֶΣ�����EXTTEXT5
        List<BO> fieldList = SDK.getBOAPI().query(CrmConstant.BO_EU_DNSYS_UDF_GROUP_FIELD).bindId(detail.getBindId()).list();
        List<String> list = new ArrayList<String>();
        for (BO bo : fieldList) {
            list.add("'" + bo.getString("UDF_FIELD_COL_NAME") + "'");
        }
        //����������Ϣȥ�Զ������Ա��в�ѯ�����ֶ���Ϣ������ǰ��ƴ�ӳ�ҳ��
        String fieldSql = "SELECT * FROM " + CrmConstant.BO_EU_DNSYS_UDF_FIELD + " WHERE COL_NAME IN (" + org.apache.commons.lang3.StringUtils.join(list, ",") + ") AND ORGID=? AND CATE_ID=" + CrmConstant.PZXID + "  ORDER BY SORT_ORDER";
        List<RowMap> udfList = DBSql.getMaps(fieldSql, new Object[]{ORGID});
        System.out.println("sql2:" + fieldSql);

        map.put("formTitle", "�������Զ����ֶ�");

        List<Map<String, Object>> colFields = new ArrayList<>();

        //��ѯ���ñ�洢����
        BO object = SDK.getBOAPI().query(CrmConstant.BO_EU_DNCRM_INSTALLED_PRODUCT).detailById(objectId);
        for (RowMap udf : udfList) {
            Map<String, Object> field = new HashMap<>();
            String COL_NAME = udf.getString("COL_NAME");

            field.put("name", COL_NAME);
            if (object != null) {
                field.put("value", object.getString(COL_NAME));
            } else {
                field.put("value", udf.getString("DEFAULT_VALUE"));
            }
            String DATA_TYPE_ID = udf.getString("DATA_TYPE_ID");

            field.put("type", DATA_TYPE_ID);
            if (DATA_TYPE_ID.equals("530")) {

                String sql = udf.getString("SQL_CONFIG");

                if (sql.contains("@")) {
                    sql = SDK.getRuleAPI().executeAtScript(sql, uc);
                }
                List<RowMap> list2 = DBSql.getMaps(sql, new Object[0]);

                field.put("list", list2);
            }

            field.put("comment", udf.getString("COL_COMMENT"));
            field.put("readonly", udf.getString("IS_PROTECTED"));
            field.put("required", udf.getString("IS_REQUIRED"));

            colFields.add(field);
        }

        map.put("colFields", JSON.toJSONString(colFields));

        return HtmlPageTemplate.merge("CONF.html", map);
    }

    /**
     * 配置项自定义字段保存
     * @param userContext
     * @param cateId
     * @param objectId
     * @param data
     * @return
     * @throws Exception
     */
    @Mapping("com.awspaas.user.apps.donenow_crm_save")
    public ResponseObject udfSave(UserContext userContext, String cateId, String objectId, String data) throws Exception {
        System.out.println("cateId=" + cateId + " objectId=" + objectId);
        System.out.println(data);
        JSONObject json = JSON.parseObject(data);
        String set = "";
        List<String> values = new ArrayList<>();
        for (String key : json.keySet()) {
            String value = json.getString(key);
            if (StringUtils.isBlank(value)) value = "";
            if (value.contains("[") && value.length() > 4) {
                value = value.substring(2, 3);
            }
            set = set + key + "=?,";
            values.add(value);
        }
        values.add(objectId);


        String sql = "update " + CrmConstant.BO_EU_DNCRM_INSTALLED_PRODUCT + " set " + set.substring(0, set.length() - 1) + " where id=?";
        System.out.println("updateBO_EU_DNCRM_INSTALLED_PRODUCTSql:" + sql);

        DBSql.update(sql, values.toArray());

        return ResponseObject.newOkResponse();
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_crm.getProductInfoByContractServiceId")
    public ResponseObject getProductInfoByContractServiceId(UserContext uc, String id) {
        try {
            // 1. 原有：查询订单产品关联表获取order_id，再查订单表获取VENDOR_ACCOUNT_ID
            String orderProductSql = "SELECT order_id FROM BO_EU_DNIVT_ORDER_PRODUCT WHERE CONTRACT_SERVICE_ID = ?";
            Map<String, Object> orderProductInfo = DBSql.getMap(orderProductSql, new Object[]{id});
            String vendorAccountId = null;
            if (orderProductInfo != null && orderProductInfo.get("order_id") != null) {
                String orderId = orderProductInfo.get("order_id").toString();
                String orderSql = "SELECT VENDOR_ACCOUNT_ID FROM BO_EU_DNIVT_ORDER WHERE id = ?";
                Map<String, Object> orderInfo = DBSql.getMap(orderSql, new Object[]{orderId});
                if (orderInfo != null && orderInfo.get("VENDOR_ACCOUNT_ID") != null) {
                    vendorAccountId = orderInfo.get("VENDOR_ACCOUNT_ID").toString();
                }
            }

            // 2. 新增：根据VENDOR_ACCOUNT_ID查询bo_eu_dncrm_account表获取name
            String vendorAccountName = null;
            if (vendorAccountId != null) { // 仅当有vendorAccountId时才查询
                String accountSql = "SELECT NAME FROM bo_eu_dncrm_account WHERE id = ?";
                Map<String, Object> accountInfo = DBSql.getMap(accountSql, new Object[]{vendorAccountId});
                if (accountInfo != null && accountInfo.get("NAME") != null) {
                    vendorAccountName = accountInfo.get("NAME").toString();
                }
            }

            // 3. 原有：查询合同服务、服务、产品信息（保持不变）
            String contractServiceSql = "SELECT OBJECT_ID FROM BO_EU_DNCTT_CONTRACT_SERVICE WHERE id = ?";
            Map<String, Object> contractServiceInfo = DBSql.getMap(contractServiceSql, new Object[]{id});
            Map<String, Object> result = new HashMap<>();

            if (contractServiceInfo == null || contractServiceInfo.get("OBJECT_ID") == null) {
                result.put("contractServiceExists", false);
                result.put("serviceExists", false);
                result.put("productExists", false);
                result.put("productId", null);
                result.put("productName", null);
            } else {
                result.put("contractServiceExists", true);
                result.put("contractServiceExists", true);
                String objectId = contractServiceInfo.get("OBJECT_ID").toString();
                String serviceSql = "SELECT PRODUCT_ID FROM BO_EU_DNIVT_SERVICE WHERE id = ?";
                Map<String, Object> serviceInfo = DBSql.getMap(serviceSql, new Object[]{objectId});

                if (serviceInfo == null || serviceInfo.get("PRODUCT_ID") == null) {
                    result.put("serviceExists", false);
                    result.put("productExists", false);
                    result.put("productId", null);
                    result.put("productName", null);
                } else {
                    result.put("serviceExists", true);
                    String productId = serviceInfo.get("PRODUCT_ID").toString();
                    String productSql = "SELECT id, NAME FROM bo_eu_dnivt_product WHERE id = ?";
                    Map<String, Object> productInfo = DBSql.getMap(productSql, new Object[]{productId});

                    result.put("productExists", productInfo != null);
                    result.put("productId", productInfo != null ? productInfo.get("id") : null);
                    result.put("productName", productInfo != null ? productInfo.get("NAME") : null);
                }
            }

            // 4. 新增返回字段：vendorAccountId（原有）和 vendorAccountName（新增）
            result.put("vendorAccountId", vendorAccountId);
            result.put("vendorAccountName", vendorAccountName); // 账户名称

            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.setData(result);
            return responseObject;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseObject.newErrResponse("查询产品信息失败：" + e.getMessage());
        }
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_crm.getProductByContractCostId")
    public ResponseObject getProductByContractCostId(UserContext uc, String id) {
        try {
            // 1. 第一步：根据传入的id查询bo_eu_dnctt_contract_cost表的PRODUCT_ID
            String contractCostSql = "SELECT PRODUCT_ID " +
                    "FROM bo_eu_dnctt_contract_cost " +
                    "WHERE id = ?";
            Map<String, Object> contractCostInfo = DBSql.getMap(contractCostSql, new Object[]{id});

            Map<String, Object> result = new HashMap<>();

            if (contractCostInfo == null || contractCostInfo.get("PRODUCT_ID") == null) {
                // 未查询到合同成本记录或PRODUCT_ID为空
                result.put("contractCostExists", false); // 合同成本记录是否存在
                result.put("productExists", false); // 产品记录是否存在
                result.put("productId", null);
                result.put("productName", null);
            } else {
                result.put("contractCostExists", true);
                String productId = contractCostInfo.get("PRODUCT_ID").toString();

                // 2. 第二步：用PRODUCT_ID查询bo_eu_dnivt_product表的id和name
                String productSql = "SELECT id, NAME " +
                        "FROM bo_eu_dnivt_product " +
                        "WHERE id = ?";
                Map<String, Object> productInfo = DBSql.getMap(productSql, new Object[]{productId});

                if (productInfo == null) {
                    // 未查询到产品记录
                    result.put("productExists", false);
                    result.put("productId", null);
                    result.put("productName", null);
                } else {
                    // 成功查询到产品信息
                    result.put("productExists", true);
                    result.put("productId", productInfo.get("id"));
                    result.put("productName", productInfo.get("NAME"));
                }
            }

            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.setData(result);
            return responseObject;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseObject.newErrResponse("查询产品信息失败：" + e.getMessage());
        }
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_crm.getUdfGroupByProductId")
    public ResponseObject getUdfGroupByProductId(UserContext uc, String productId) {
        try {
            // 1. 第一步：查询产品表的INSTALLED_PRODUCT_CATE_ID
            String productSql = "SELECT INSTALLED_PRODUCT_CATE_ID " +
                    "FROM BO_EU_DNIVT_PRODUCT " +
                    "WHERE id = ?";
            Map<String, Object> productInfo = DBSql.getMap(productSql, new Object[]{productId});

            Map<String, Object> result = new HashMap<>(2); // 仅存2个字段
            String udfGroupId = null;
            String udfGroupName = null;

            if (productInfo != null && productInfo.get("INSTALLED_PRODUCT_CATE_ID") != null) {
                String installedProductCateId = productInfo.get("INSTALLED_PRODUCT_CATE_ID").toString();

                // 2. 第二步：查询自定义组表的id和name
                String udfGroupSql = "SELECT id, NAME " +
                        "FROM BO_EU_DNSYS_UDF_GROUP " +
                        "WHERE is_active = 1 AND id = ?";
                Map<String, Object> udfGroupInfo = DBSql.getMap(udfGroupSql, new Object[]{installedProductCateId});

                if (udfGroupInfo != null) {
                    udfGroupId = udfGroupInfo.get("id").toString();
                    udfGroupName = udfGroupInfo.get("NAME").toString();
                }
            }

            // 仅返回两个字段：自定义组id和name（不存在则为null）
            result.put("udfGroupId", udfGroupId);
            result.put("udfGroupName", udfGroupName);

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

    @Mapping(value = "com.awspaas.user.apps.donenow_crm.saveOrUpdateBankAccount")
    public ResponseObject saveOrUpdateBankAccount(UserContext uc, String accountId, String bank, String bankAccount) {
        try {
            // 1. 查询是否存在该银行账号记录
            String checkSql = "SELECT id " +
                    "FROM BO_EU_DNCRM_ACCOUNT_BANK " +
                    "WHERE BANK_ACCOUNT = ?";
            Map<String, Object> existingAccount = DBSql.getMap(checkSql, new Object[]{bankAccount});

            Map<String, Object> result = new HashMap<>(2);
            boolean isCreated = false;
            String recordId = null;

            if (existingAccount == null) {
                ProcessInstance processInstance = SDK.getProcessAPI().createProcessInstance("obj_516bbf920a1c444eb35938fcfa1f70e2", uc.getUID(), "客户开户银行及账号");

                BO bankAccountBO = new BO();
                bankAccountBO.setBindId(processInstance.getId());

                bankAccountBO.set("ACCOUNT_ID", accountId);
                bankAccountBO.set("BANK", bank);
                bankAccountBO.set("BANK_ACCOUNT", bankAccount);

                SDK.getBOAPI().create("BO_EU_DNCRM_ACCOUNT_BANK", bankAccountBO,processInstance, uc);

                recordId = bankAccountBO.getId();
                isCreated = true;
            } else {
                // 3. 存在则用update语句更新记录
                recordId = existingAccount.get("id").toString();
                String updateSql = "UPDATE BO_EU_DNCRM_ACCOUNT_BANK " +
                        "SET ACCOUNT_ID = ?, BANK = ? " +
                        "WHERE id = ?";
                DBSql.update(updateSql, new Object[]{accountId, bank, recordId});
            }

            result.put("isCreated", isCreated);
            result.put("recordId", recordId);
            ResponseObject responseObject = ResponseObject.newOkResponse();
            responseObject.setData(result);
            return responseObject;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseObject.newErrResponse("银行账户操作失败：" + e.getMessage());
        }
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_crm.getContractServiceName")
    public ResponseObject getContractServiceName(UserContext uc, String contractServiceId) {
        try {
            // 1. 校验入参（可选，防止空指针）
            if (contractServiceId == null || contractServiceId.trim().isEmpty()) {
                return ResponseObject.newErrResponse("合同服务ID不能为空");
            }

            // 2. 查询bo_eu_dnctt_contract_service表的name字段
            String sql = "SELECT name " +
                    "FROM bo_eu_dnctt_contract_service " +
                    "WHERE id = ?"; // 假设ID字段名为id，若实际字段不同需调整

            Map<String, Object> contractServiceInfo = DBSql.getMap(sql, new Object[]{contractServiceId});

            // 3. 处理查询结果（不存在则返回null）
            String contractServiceName = null;
            if (contractServiceInfo != null && contractServiceInfo.get("name") != null) {
                contractServiceName = contractServiceInfo.get("name").toString();
            }

            // 4. 封装响应数据
            Map<String, Object> result = new HashMap<>(1);
            result.put("contractServiceName", contractServiceName);

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

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseObject.newErrResponse("查询合同服务名称失败：" + e.getMessage());
        }
    }

    @Mapping(value = "com.awspaas.user.apps.donenow_crm.getContactUserId")
    public ResponseObject getContactUserId(UserContext uc, String id) {
        try {
            if (id == null || id.trim().isEmpty()) {
                return ResponseObject.newErrResponse("联系人ID不能为空");
            }


            String sql = "SELECT USERID " +
                    "FROM BO_EU_DNCRM_CONTACT " +
                    "WHERE id = ?";

            Map<String, Object> contactInfo = DBSql.getMap(sql, new Object[]{id});

            String userId = null;
            if (contactInfo != null && contactInfo.get("USERID") != null) {
                userId = contactInfo.get("USERID").toString();
            }

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

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

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

}
