package org.example.ModuleApi.ModuleAjaxApi.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.Api.OptBaseHandler;
import org.example.Entity.Attributes.RequestCheck;
import org.example.Entity.CusException.CusException;
import org.example.Entity.System.BaseModule;
import org.example.Entity.System.BillModule;
import org.example.Entity.System.BillStateEn;
import org.example.Entity.System.ModuleBaseEntity;
import org.example.Enums.SystemEnums;
import org.example.Enums.SystemTypeEnums;
import org.example.Impl.BaseImpl;
import org.example.Impl.DataImpl;
import org.example.Impl.MapImpl;
import org.example.Impl.ModuleImpl;
import org.example.Service.ModuleImplService;
import org.example.Utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.*;

import static org.example.Utils.NativeExtensionUtils.*;

@RestController
@Scope("prototype")
@RequestMapping("/Api/ModuleAjaxApi")
public class ModuleAjaxController extends OptBaseHandler {
    @RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST})
    public void handleRequest(HttpServletRequest Request, HttpServletResponse response) throws Exception {
        // 调用 BaseHandler 的 processRequest 处理逻辑
        super.processRequest(Request);
    }

    @Autowired
    ModuleImplService moduleImplService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private IPublicUtil _util;

    @Autowired
    private ModuleImpl moduleImpl;

    public IPublicUtil getUtil() {
        return _util == null ? _util = new IPublicUtil(jdbcTemplate) : _util;
    }

    @Autowired
    private MapImpl _mapImpl;

    private MapImpl getMapImpl() {
        if (_mapImpl == null)
            _mapImpl = new MapImpl(jdbcTemplate);
        return _mapImpl;
    }

    @RequestCheck(CheckLogin = false, CheckParams = "ModuleId", Cache = true)
    public void GetModuleIniParams() {
        BaseImpl bImpl = getBImpl();
        String targetModuleId = bImpl.Request("targetModuleId");
        int sourceId = ToInt32(bImpl.Request("sourceId"));
        if (sourceId > 0) {
            response.setData(moduleImpl.GetBillSourceModule(ModuleId, sourceId + "", "").get(0));
        } else {
            response.setData(moduleImplService.getModuleIniParams(
                    bImpl.Request("ModuleId"),
                    bImpl.Request("MenuId"),
                    bImpl.Request("targetModuleId", ""),
                    bImpl.Request("detailId"),
                    toBoolean(bImpl.Request("isCard")),
                    toBoolean(bImpl.Request("isChart")),
                    bImpl.Request("mFields"),
                    toBoolean(bImpl.Request("atts")),
                    toBoolean(bImpl.Request("loadDetail", "1")),
                    toBoolean(bImpl.Request("loadLeft", "1")),
                    toBoolean(bImpl.Request("isAttc", "0"))
            ));
            if (Objects.equals(ModuleId, "2005_1")) {
                String idVal = bImpl.Request("idValue", "");
                response.setOther(moduleImpl.CheckAttcAuthoryInt(moduleImpl.GetModule(targetModuleId), idVal));
            }
        }
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "_fId|id")
    public void GetFieldData() {
        response = moduleImplService.getFieldDataPam();
    }

    @RequestCheck(CheckLogin = false, CheckParams = "ModuleId")
    public void GetModuleData() {
        response = moduleImplService.getModuleData();
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetBillIniParams() {
        response = moduleImplService.getBillIniParams();
    }

    @RequestCheck(CheckParams = "ModuleId")
    /// <summary>
    public void GetBaseAuditStepData() {
        response = moduleImplService.getBaseAuditStepData();
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetStepDataCounts() {
        response = moduleImplService.GetStepDataCounts();
    }

    public void GetAddOrUpdFields() {
        response = moduleImplService.GetAddOrUpdFields();
    }

    @RequestCheck(CheckParams = "moduleId")
    public void GetAttcData() throws UnsupportedEncodingException {
        response = moduleImplService.GetAttcData();
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void AddOrUpd() throws UnsupportedEncodingException, CusException {
        response = moduleImplService.AddOrUpd();
    }


    @RequestCheck(CheckParams = "ModuleId")
    public void Delete() {
        response = moduleImplService.Delete();
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetCondition() {

        response = moduleImplService.GetCondition();
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetBaseAuditIniParams() {
        var theRes = moduleImpl.GetAuditIniParams(ModuleId, true);
        response.setData(theRes);
        if (theRes.isSuccess()) {
            response.setSuccess(true);
        } else {
            response.setSuccess(false);
            response.setMsg(theRes.getMsg());
        }
//        response = moduleImplService.GetAuditIniParams();
    }

//    @RequestCheck(CheckParams = "ModuleId", Cache = true)
//    public void GetModuleCfg() {

    /// /        response.setData(moduleImpl.GetModule(ModuleId));
    /// /        response.setSuccess(true);
//        response = moduleImpl.GetModuleCfg();
//    }
    public void GetModulCfgs() {
        response.setData(moduleImpl.GetModuleCfgs(getBImpl().Request("ModuleId"), MenuId));
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "ModuleId", Cache = true)
    public void GetModuleCfg() {
        response.setData(moduleImpl.GetModule(ModuleId));
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "ModuleIds", Log = false)
    public void GetModuleCountData() {
        String pms = getBImpl().Request("pms"), modueids = getBImpl().Request("ModuleIds");
        Map<String, Object> datas = new HashMap<>();
        response.setData(moduleImpl.GetModuleCountData(modueids, pms, getBImpl().Request("w")).getData());
        response.setSuccess(true);
    }

    @RequestCheck(CheckLogin = false, CheckParams = "ModuleId")
    public void GetModuleRightMenu() {
        response = moduleImpl.GetModuleRightMenu();
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetModuleDetailsData() {
        String pms = getBImpl().Request("pms"), leftRecord = getBImpl().Request("leftRecord", pms), dids = getBImpl().Request("ids");
        //将参数放在pms中来判断是否要拼接Moduleimpl中的idwherekey查询
        if (!isNullOrEmpty(pms)) {
            leftRecord = leftRecord.trim();
            leftRecord = leftRecord.substring(0, leftRecord.length() - 1) + ",\"$isPms\":1}";
        }
        boolean isAuditAttc = toBoolean(getBImpl().Request("isAttc"));
        response = moduleImpl.GetModuleDetailsData(ModuleId, leftRecord, dids);
    }

    @RequestCheck(CheckParams = "ModuleId,detailId")
    public void GetModuleDetailData() {
        BaseImpl bImpl = getBImpl();
        String detailId = bImpl.Request("detailId") + "", pms = bImpl.Request("qrpms", bImpl.Request("pms")),
                leftRecord = bImpl.Request("leftRecord", pms);

        // 将参数放在pms中来判断是否要拼接Moduleimpl中的idwherekey查询
        if (pms != null && !pms.trim().replaceAll("[{}]", "").trim().isEmpty()) {
            leftRecord = leftRecord != null ? leftRecord.trim() : "";
            if (leftRecord.isEmpty() || leftRecord.trim().replaceAll("[{}]", "").trim().isEmpty()) {
                leftRecord = "{\"$isPms\":1}";
            } else {
                // 去除最后一个字符（假设是'}')并添加新属性
                leftRecord = leftRecord.substring(0, leftRecord.length() - 1) + ",\"$isPms\":1}";
            }
        }

        boolean isAuditAttc = NativeExtensionUtils.toBoolean(bImpl.Request("isAttc"));
        boolean isMulti = NativeExtensionUtils.toBoolean(bImpl.Request("multi"));
        boolean isGrid = NativeExtensionUtils.toBoolean(bImpl.Request("grid"));
        int detailIdInt = NativeExtensionUtils.parseInt(detailId);

        response = moduleImpl.GetModuleDetailData(ModuleId, detailIdInt, leftRecord, isMulti, isGrid, isAuditAttc, pms);
    }

    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void GetAuditHistory() {
        response = moduleImpl.GetAuditHistory(ModuleId, getBImpl().Request("idValue"), getBImpl().Request("isBase"));
    }

    public void GetAddOrUpdData() {
        BaseImpl bImpl = getBImpl();
        String idValue = bImpl.Request("idValue"),
                detailId = bImpl.Request("detailId"),
                contextMenuId = bImpl.Request("contextMenuId") + "",
                leftRecord = bImpl.Request("leftRecord");

        response = moduleImpl.GetAddOrUpdData(ModuleId, detailId, idValue, leftRecord, ToInt32(contextMenuId), toBoolean(bImpl.Request("isattc")));
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetModuleDetail() {
        response.setData(moduleImpl.GetModelDetails(moduleImpl.GetBaseModule(ModuleId, "")));
        response.setSuccess(response.getData() != null);

    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetMobileAttachModules() {
        response = moduleImpl.GetAttachModules(ModuleId, true);

    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetAttachModules() {
        response = moduleImpl.GetAttachModules(ModuleId, toBoolean(getBImpl().Request("iscard")));

    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetSpecificAttachModules() {
        response = moduleImpl.GetSpecificAttachModules(ModuleId);

    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetModuleCardGroup() {
        BaseImpl bImpl = getBImpl();
        String isMain = bImpl.Request("main"), isBase = bImpl.Request("isBase"), mxId = bImpl.Request("detailId");
        response.setData(moduleImpl.GetModuleCardGroup(ModuleId, isNullOrEmpty(isMain) ? null : toBoolean(isMain), isNullOrEmpty(isBase) ? null : toBoolean(isMain), ToInt32(mxId)));
        response.setSuccess(true);
    }


    @RequestCheck(CheckParams = "ModuleId")
    public void ModuleSchemes() {
        response.setData(moduleImpl.GetSchemesList(MenuId));
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "MenuId,name")
    public void DeleteSchemes() {
        response = moduleImpl.DeleteProject(MenuId, getBImpl().Request("name"));
    }

    @RequestCheck(CheckParams = "MenuId,name,vals")
    public void SaveSchemes() {
        response = moduleImpl.SaveProject(getBImpl().Request("name"), getBImpl().Request("vals"), MenuId);
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetTaskIniParams() {
        response = moduleImpl.GetTaskIniParams(ModuleId);
    }

    public void GetTaskData() {
        String record = getBImpl().Request("record") + "",
                leftRecord = getBImpl().Request("leftRecord"),
                pms = getBImpl().Request("pms"), taskModuleId = getBImpl().Request("TaskModuleId");
        int taskType = ToInt32(getBImpl().Request("tasktype"));
        if (isNullOrEmpty(taskModuleId)) {
            response.setData(null);
            response.setSuccess(true);
        } else {
            response = moduleImpl.GetTaskData(ModuleId, taskModuleId, leftRecord, pms, taskType);
        }
    }

    @RequestCheck(CheckParams = "ModuleId,TaskModuleId")
    public void GetTaskColumns() {
        response = moduleImpl.GetTaskColumns(ModuleId, getBImpl().Request("TaskModuleId"));
    }

    @RequestCheck(CheckParams = "id")
    public void GetFieldUnionData() {
        BaseImpl bImpl = getBImpl();
        int fieldId = ToInt32(bImpl.Request("id"));
        int fdtype = ToInt32(bImpl.Request("fdtype"));
        String record = Objects.toString(bImpl.Request("record"), ""),
                poppms = bImpl.Request("poppms"),
                leftRecord = bImpl.Request("leftRecord"),
                pms = bImpl.Request("pms");
        if (!isNullOrEmpty(poppms) && poppms.startsWith("{"))//右键调添加模块时候，要把右键参数传递过来，替换字段里面的{#p_n}的值
        {
            if (isNullOrEmpty(record) || !record.startsWith("{")) {
                record = poppms;
            } else {
                Map<String, Object> recordMap = (Map<String, Object>) JSON.Decode(record);
                // 合并poppmsMap到recordMap（覆盖相同key）
                if (recordMap != null) {
                    Map<String, Object> poppmsMap = (Map<String, Object>) JSON.Decode(poppms);
                    for (Map.Entry<String, Object> entry : poppmsMap.entrySet()) {
                        recordMap.put(entry.getKey(), entry.getValue());
                    }
                    // 将合并后的Map重新序列化为JSON字符串
                    record = JSON.Encode(recordMap);
                } else {
                    record = poppms;
                }
            }
        }

        response = moduleImpl.GetFieldUnionData(fieldId, record, leftRecord, pms, fdtype);
    }

    @RequestCheck(CheckParams = "mid")
    public void ContextMenuClick() throws CusException {
        BaseImpl bImpl = getBImpl();
        response = moduleImpl.ContextMenuClick(ToInt32(bImpl.Request("mid")),
                ModuleId, bImpl.Request("data") + "", bImpl.Request("leftRecord") + "");
    }

    public void ExcAuQuerySql() {
        BaseImpl bImpl = getBImpl();
        String ensql = bImpl.Request("s") + "",
                record = bImpl.Request("record") + "",
                leftRecord = bImpl.Request("leftRecord"),
                pms = bImpl.Request("pms"),
                keyField = bImpl.Request("textField"),
                keyValue = bImpl.Request(keyField);
        response = moduleImpl.ExcQuerySql(ensql, record, leftRecord, pms, keyField, keyValue);
    }

    public void GetDefaultVal() {
        BaseImpl bImpl = getBImpl();
        String val = bImpl.Request("val"), _record = bImpl.Request("record");
        Hashtable record = null;
        if (!isNullOrEmpty(_record)) {
            record = (Hashtable) JSON.Decode(_record);
        }
        response.setData(PublicUtil.ReqSqlPms(record, null, val, SystemTypeEnums.PmType.sql, null));
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void GetBillState() {
        ModuleBaseEntity module = null;
        String mTypeStr = getBImpl().Request("mtype");
        SystemEnums.ModuleType mType = null; // 默认值

        // 解析模块类型
        if (mTypeStr != null && !mTypeStr.isEmpty()) {
            try {
                mType = SystemEnums.ModuleType.valueOf(mTypeStr.toUpperCase());
            } catch (IllegalArgumentException e) {
                // 解析失败时使用默认值
                mType = SystemEnums.ModuleType.BaseModule;
            }
        }

        // 根据模块类型获取对应模块
        switch (mType) {
            case BillModule:
                module = moduleImpl.GetBillModule(ModuleId, MenuId);
                break;
            default: // 包括BaseModule和其他未定义类型
                module = moduleImpl.GetBaseModule(ModuleId, MenuId);
                break;
        }

        if (module == null) {
            return;
        }

        //response.success = true;
        //response.data = moduleImpl.GetBillState(module, bImpl.Request("idValue"));
    }

    @RequestCheck(CheckParams = "ModuleId,tpl")
    public void SaveModuleAddTpl() {
        String tpl = getBImpl().Request("tpl");
        int tplId = new DataImpl(jdbcTemplate).GetModuleAddTplId(ModuleId);
        Map<String, Object> dH = new HashMap<>();
        dH.put("modulecontent", tpl);
        dH.put("id", tplId);
        dH.put("tab", ModuleId);
        dH.put("ban", 1);
        moduleImpl.AddOrUpdTable(JSON.Encode(dH), "P_pubrpsettab", "id", tplId <= 0, null);
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetBillMasterFields() {
        BaseImpl bImpl = getBImpl();
        response.setData(moduleImpl.GetBillMasterFields(ModuleId, bImpl.Request("idValue"), bImpl.Request("leftRecord")));
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetBillAddOrUpdInfo() {
        BaseImpl bImpl = getBImpl();
        String leftRecord = bImpl.Request("leftRecord"), contextMenuId = bImpl.Request("contextMenuId") + "";
//        response.setData(moduleImpl.GetBillAddOrUpdInfo(bImpl.Request("idValue"), ModuleId, MenuId, contextMenuId, leftRecord));
        String menuid = getBImpl().Request("MenuId", getBImpl().Request("menuId"));
        response.setData(moduleImpl.GetBillAddOrUpdInfo(bImpl.Request("idValue"), ModuleId, menuid, contextMenuId, leftRecord));
        response.setSuccess(response.getData() != null);
        if (!response.isSuccess()) {
            response.setMsg("无效模块编号" + ModuleId);
        }
    }

    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void GetBillDetailData() {
        response = moduleImpl.GetBillDetailData(ModuleId, getBImpl().Request("idValue"));
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "ModuleId")
    public void GetBillSource() {
        var theData = moduleImpl.GetBillSourceModule(ModuleId, "", "0,1");
        response.setData(theData);
        response.setSuccess(true);
    }

    @RequestCheck(CheckParams = "ModuleId,sourceId")
    public void GetBillSourceData() {
        BaseImpl bImpl = getBImpl();
        response = moduleImpl.GetBillSourceData(ModuleId, bImpl.Request("sourceId"), bImpl.Request("pms"), bImpl.Request("w"), bImpl.Request("leftRecord"), toBoolean(bImpl.Request("detail")));
    }

    @RequestCheck(CheckParams = "ModuleId,master,detail")
    public void SaveBill() throws CusException {
        BaseImpl bImpl = getBImpl();
        boolean apply = toBoolean(bImpl.Request("apply"));//是否提交
        int applyType = ToInt32(bImpl.Request("applyType", "1"));//提交类型 1：提交 0：撤回
        int selectConfirmFlag = ToInt32(bImpl.Request("selectConfirmFlag"));
        String idValue = bImpl.Request("idValue");
        if (selectConfirmFlag == 0 || !apply || isNullOrEmpty(idValue)) {
            response = moduleImpl.SaveBill(ModuleId,
                    bImpl.Request("master"), //主表数据{}
                    bImpl.Request("detail"), //明细数据[]
                    //  bImpl.Request("del"),//被删掉的原有数据
                    bImpl.Request("leftRecord"), //左关联数据
                    toBoolean(bImpl.Request("add")), //是否为新增 0|1,true|false
                    ToInt32(bImpl.Request("rtagid")),//红蓝字标识 0：蓝字 1：红字
                    ToInt32(bImpl.Request("comfirm")), //The comfirm flag.0：默认保存 1：有提示，然后确认保存
                    ToInt32(bImpl.Request("auditFlag")),
                    bImpl.Request("remark"));//comfirm remark
        } else {
            response.setSuccess(true);
            response.setOther(idValue);
        }
        if (response.isSuccess() && apply && !isNullOrEmpty(response.getOther() + "")) {
            String nextSelectStepCode = bImpl.Request("nextSelectStepCode"),
                    nextSelectStepOper = bImpl.Request("nextSelectStepOper");

            BillStateEn stateEn = new BillStateEn();
            stateEn.setSelectConfirmFlag(selectConfirmFlag);
            stateEn.nextSelectStepCode = nextSelectStepCode;
            stateEn.nextSelectStepOper = nextSelectStepOper;
            response = moduleImpl.BillApply(ModuleId, response.getOther() + "", stateEn, applyType);
            if (response.getOther() + "" == "9") {
                response.setSuccess(true);
            }
        }
    }

    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void BillApply() throws CusException {
        BaseImpl bImpl = getBImpl();
        int applyType = ToInt32(bImpl.Request("applyType", "1"));//提交类型 1：提交 0：撤回
        String idVal = bImpl.Request("idValue"),
                nextSelectStepCode = bImpl.Request("nextSelectStepCode"),
                nextSelectStepOper = bImpl.Request("nextSelectStepOper");
        int selectConfirmFlag = ToInt32(bImpl.Request("selectConfirmFlag"));
        int comfirmFlag = ToInt32(bImpl.Request("comfirm"));
        BillStateEn stateEn = new BillStateEn();
        stateEn.setSelectConfirmFlag(selectConfirmFlag);
        stateEn.nextSelectStepCode = nextSelectStepCode;
        stateEn.nextSelectStepOper = nextSelectStepOper;
        stateEn.comfirmFlag = comfirmFlag;
        response = moduleImpl.BillApply(ModuleId, idVal, stateEn, applyType);
    }

    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void BillAudit() throws CusException {
        BaseImpl bImpl = getBImpl();
        String idVal = bImpl.Request("idValue"), master = bImpl.Request("master"), //主表数据{}
                detail = bImpl.Request("detail");//明细数据[]
        int comfirm = ToInt32(bImpl.Request("comfirm"));

        BillModule module = moduleImpl.GetBillModule(ModuleId, MenuId);
        module.IdValue = idVal;
        module.setComfirmFlag(comfirm);
        BillStateEn stateEn = GetAuditRequest(module);
        response = moduleImpl.BillAudit(module, master, detail, stateEn);
    }

    private BillStateEn GetAuditRequest(ModuleBaseEntity module) throws CusException {
        BaseImpl bImpl = getBImpl();
        String remark = bImpl.Request("remark"),
                stepCode = bImpl.Request("stepCode"),
                backStepCode = bImpl.Request("backStepCode"),
                nextSelectStepCode = bImpl.Request("nextSelectStepCode"),
                nextSelectStepOper = bImpl.Request("nextSelectStepOper"),
                comfirmOpers = bImpl.Request("comfirmOpers");

        int selectConfirmFlag = ToInt32(bImpl.Request("selectConfirmFlag"));

        int comfirmFlag = ToInt32(bImpl.Request("comfirm"));
        boolean back = toBoolean(ToInt32(bImpl.Request("back")));
        String audit = bImpl.Request("audit", "1") + "",//-1:关闭 0:回退 1：审核

                direction = "F";
        switch (audit) {
            case "-1":
                direction = "Q";
                break;//关闭
            case "0":
                direction = "R";
                break;//回退
            case "1":
                direction = "F";
                break;//审核
            case "2":
                direction = "C";
                break;//催办
            case "3":
                direction = "P";
                break;//暂停待办
            case "4":
                direction = "Z";
                break;//转发
            case "5":
                direction = "J";
                break;//转交
        }
        BillStateEn stateEn = moduleImpl.GetBillState(module, stepCode);
        if (stateEn != null) {
            stateEn.Direction = direction;
            stateEn.IsBack = back;
            stateEn.comfirmFlag = comfirmFlag;
            stateEn.Remark = remark;
            stateEn.BackStepCode = backStepCode;
            stateEn.setSelectConfirmFlag(selectConfirmFlag);
            stateEn.nextSelectStepCode = isNullOrEmpty(nextSelectStepCode) ? backStepCode : nextSelectStepCode;
            stateEn.nextSelectStepOper = nextSelectStepOper;
            stateEn.comfirmOpers = comfirmOpers;
        }
        return stateEn;
    }

    /// <summary>
    /// Gets the base audit information.
    /// </summary>
    /// <remarks>

    /// </remarks>
    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void GetBaseAuditInfo() throws CusException {
        BaseImpl bImpl = getBImpl();
        int stepId = ToInt32(bImpl.Request("stepId")),
                ver = ToInt32(bImpl.Request("ver"));
        String idValue = bImpl.Request("idValue"),
                leftRecord = bImpl.Request("leftRecord"),
                stepCode = bImpl.Request("stepCode");
        boolean tpl = toBoolean(bImpl.Request("tpl"));
        response = moduleImpl.GetAuditInfo(ModuleId, stepId, idValue, leftRecord, true, stepCode, ver, tpl);
    }

    /// <summary>
    /// Gets the base audit detail data.
    /// </summary>
    /// <remarks>

    /// </remarks>
    @RequestCheck(CheckParams = "detailId")
    public void GetAuditDetailData() {
        BaseImpl bImpl = getBImpl();
        int detailId = ToInt32(bImpl.Request("detailId"));
        String record = bImpl.Request("record"),
                leftRecord = bImpl.Request("leftRecord"),
                pams = bImpl.Request("pams");
        response = moduleImpl.GetAuditDetailData(detailId, record, leftRecord, pams);
    }

    @RequestCheck(CheckParams = "ModuleId,idValue,stepId|stepCode")
    public void BaseAudit() throws UnsupportedEncodingException, CusException {
        BaseImpl bImpl = getBImpl();
        String idValue = bImpl.Request("idValue") + "",
                datas = bImpl.Request("datas"), details = bImpl.Request("details") + "";
        BaseModule module = moduleImpl.GetBaseModule(ModuleId, MenuId);
        module.IdValue = idValue;
        BillStateEn stateEn = GetAuditRequest(module);
        response = moduleImpl.BaseAudit(module, datas, details, stateEn);
    }

    @RequestCheck(CheckParams = "ModuleId,idValue,stepCode")
    public void CommonAudit() throws UnsupportedEncodingException, CusException {
        BillModule billMD = moduleImpl.GetBillModule(ModuleId, "");
        if (billMD != null) {
            BillAudit();
        } else {
            BaseAudit();
        }
    }

    @RequestCheck(CheckParams = "ModuleId,datas")
    public void BatchAudit() throws UnsupportedEncodingException, CusException {
        String audit = getBImpl().Request("audit", "1") + "",//-1:关闭 0:回退 1：审核
                direction = "F";
        switch (audit) {
            case "-1":
                direction = "Q";
                break;//关闭
            case "0":
                direction = "R";
                break;//回退
            case "1":
                direction = "F";
                break;//审核
            case "2":
                direction = "C";
                break;//催办
            case "3":
                direction = "P";
                break;//暂停待办
            case "4":
                direction = "Z";
                break;//转发
            case "5":
                direction = "J";
                break;//转交
        }
        response = moduleImpl.BatchAudit(ModuleId, direction, getBImpl().Request("datas"));
    }
    /// <summary>
    ///  base audit.
    /// </summary>
    /// <remarks>

    /// </remarks>

    @RequestCheck(CheckParams = "ModuleId,stepCode,idValue")
    public void GetAuditBackSteps() throws CusException {
        BaseImpl bImpl = getBImpl();
        String stepCode = bImpl.Request("stepCode"), idValue = bImpl.Request("idValue") + "";
        boolean isBase = toBoolean(bImpl.Request("isBase"));
        response = moduleImpl.GetAuditBackSteps(ModuleId, idValue, stepCode, isBase);
    }
    /// <summary>
    /// 提交
    /// </summary>
    /// <returns>BaseResponse.</returns>
    /// <remarks>

    /// </remarks>
    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void BaseApply() throws CusException {
        BaseImpl bImpl = getBImpl();
        String nextSelectStepCode = bImpl.Request("nextSelectStepCode"),
                nextSelectStepOper = bImpl.Request("nextSelectStepOper");
        int selectConfirmFlag = ToInt32(bImpl.Request("selectConfirmFlag")),
                comfirmFlag = ToInt32(bImpl.Request("comfirm") + "");

        BillStateEn stateEn = new BillStateEn();
        stateEn.setSelectConfirmFlag(selectConfirmFlag);
        stateEn.nextSelectStepCode = nextSelectStepCode;
        stateEn.nextSelectStepOper = nextSelectStepOper;
        stateEn.comfirmFlag = comfirmFlag;
        response = moduleImpl.BaseApply(ModuleId, bImpl.Request("idValue") + "", stateEn, ToInt32(bImpl.Request("type", "1")));
    }
    /// <summary>
    /// Gets the bill audit ini parameters.
    /// </summary>
    /// <remarks>

    /// </remarks>
    @RequestCheck(CheckParams = "ModuleId")
    public void GetBillAuditIniParams() {
        var theRes = moduleImpl.GetAuditIniParams(ModuleId, false);
        response.setData(theRes);
        if (theRes.isSuccess()) {
            response.setSuccess(true);
        } else {
            response.setSuccess(false);
            response.setMsg(theRes.getMsg());
        }
    }

    /// <summary>
    /// Gets the bill audit step data.
    /// </summary>
    /// <remarks>

    /// </remarks>
    @RequestCheck(CheckParams = "ModuleId")
    public void GetBillAuditStepData() {
        BaseImpl bImpl = getBImpl();
        String record = bImpl.Request("record", ""),
                leftRecord = bImpl.Request("leftRecord"),
                pms = bImpl.Request("pms");
        int stepId = ToInt32(bImpl.Request("stepId"));
        response = moduleImpl.GetAuditStepData(ModuleId, stepId, record, leftRecord, pms, false);
    }


    /// <summary>
    /// Gets the bill audit information.
    /// </summary>
    /// <remarks>

    /// </remarks>
    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void GetBillAuditInfo() throws CusException {
        BaseImpl bImpl = getBImpl();
        int stepId = ToInt32(bImpl.Request("stepId"));
        String idValue = bImpl.Request("idValue"), leftRecord = bImpl.Request("leftRecord"), stepCode = bImpl.Request("stepCode");
        boolean tpl = toBoolean(bImpl.Request("tpl"));
        response = moduleImpl.GetAuditInfo(ModuleId, stepId, idValue, leftRecord, false, stepCode, 2, tpl);
    }

    @RequestCheck(CheckParams = "moduleId,idValue")
    public void GetAttcFiles() {
        String dot = getBImpl().Request("dot", "&");
        response = moduleImpl.GetAttcFilePaths(ModuleId, getBImpl().Request("idValue"),
                getBImpl().Request("specNo"),
                getBImpl().Request("stepCode"));

    }

    @RequestCheck(CheckParams = "moduleId")
    public void GetAttcTreeData() {
        response = moduleImpl.GetAcctTreeData(ModuleId, getBImpl().Request("specNo", ""));
    }

    @RequestCheck(CheckLogin = false, CheckParams = "ModuleId,ModuleType")
    public void GetFlowChartData() throws CusException {
        BaseImpl bImpl = getBImpl();
        int ModuleType = ToInt32(bImpl.Request("ModuleType"));
        String billType = bImpl.Request("billType") + "", idValue = bImpl.Request("idValue") + "";
        boolean autostep = toBoolean(bImpl.Request("autostep"));
        response = moduleImpl.GetFlowChartData(ModuleId, ModuleType, billType, idValue, autostep);
    }

    @RequestCheck(CheckLogin = false, CheckParams = "ModuleId,ModuleType,billType")
    public void GetFlowChartOption() {
        BaseImpl bImpl = getBImpl();
        int ModuleType = ToInt32(bImpl.Request("ModuleType"));
        String billType = bImpl.Request("billType") + "";
        response = moduleImpl.GetFlowChartOption(ModuleId, ModuleType, billType);
    }

    @RequestCheck(CheckLogin = false, CheckParams = "ModuleId,ModuleType,billType")
    public void UpdateFlowChartOption() {
        BaseImpl bImpl = getBImpl();
        int ModuleType = ToInt32(bImpl.Request("ModuleType"));
        String billType = bImpl.Request("billType") + "", options = bImpl.Request("options") + "";
        response = moduleImpl.UpdateFlowChartOption(ModuleId, ModuleType, billType, options);
    }

    @RequestCheck(CheckLogin = false, CheckParams = "ModuleId,ModuleType,billType")
    public void UpdatePartFlowChartOption() {
        BaseImpl bImpl = getBImpl();
        int ModuleType = ToInt32(bImpl.Request("ModuleType"));
        String billType = bImpl.Request("billType") + "", options = bImpl.Request("options") + "";
        response = moduleImpl.UpdatePartFlowChartOption(ModuleId, ModuleType, billType, options);
    }


    @RequestCheck(CheckLogin = false)
    public void GetUpdFlowChartList() {
        response = moduleImpl.GetUpdFlowChartList();
    }

    @RequestCheck(CheckLogin = false)
    public void GetTimeEvent() {
        response = moduleImpl.GetTimeEvent();
    }

    public void GanttGetModuleData() {
        BaseImpl bImpl = getBImpl();
        String record = bImpl.Request("record") + "",
                leftRecord = bImpl.Request("leftRecord"),
                pms = bImpl.Request("pms"),
                detailId = bImpl.Request("detailId") + "",
                contextMenuId = bImpl.Request("contextMenuId") + "",
                sourceId = bImpl.Request("sourceId") + "";
        response = moduleImpl.GanttGetModuleData(ModuleId, record, leftRecord, pms, "", toBoolean(bImpl.Request("multi")),
                toBoolean(bImpl.Request("grid")), ToInt32(contextMenuId));
    }


    @RequestCheck(CheckLogin = false)
    public void EvalCond() {
        String cond = getBImpl().Request("cond");
        response.setData(getUtil().evalCond(cond, null));//  new DataImpl(){UserSessionName = UserSessionName,dbOperator = dbOperator}.EvalCond(cond);
        response.setSuccess(true);
    }


    @RequestCheck(CheckLogin = false)
    public void GetTimeChangeList() {
        String sql = "select * from BI_TimeChangeList";
        response.setData(jdbcTemplate.queryForList(sql));
        response.setSuccess(true);
    }


    //region 打印相关

    @RequestCheck(CheckParams = "ModuleId,name")
    public void GetPrintInfo() {
        BaseImpl bImpl = getBImpl();
        String printName = bImpl.Request("name") + "", record = bImpl.Request("record") + "";
        boolean isBase = toBoolean(bImpl.Request("base"));
        response = moduleImpl.GetPrintInfo(ModuleId, printName, record);
    }

    public void GetPrintSta() {
        int printId = ToInt32(getBImpl().Request("pid"));
        response = moduleImpl.GetPrintSta(printId);
    }


    @RequestCheck(CheckParams = "ModuleId,name")
    public void GetWebPrintInfo() {
        BaseImpl bImpl = getBImpl();
        String printName = bImpl.Request("name") + "", record = bImpl.Request("record") + "";
        boolean isBase = toBoolean(bImpl.Request("base"));
        response = moduleImpl.GetWebPrintInfo(ModuleId, printName, record, isBase);
    }

    /// <summary>
    /// 添加或修改web打印模板
    /// </summary>
    /// <returns>System.String.</returns>
    /// <remarks>
    /// </remarks>

    @RequestCheck(CheckParams = "ModuleId")
    public void AddOrUpdWebPrint() {
        BaseImpl bImpl = getBImpl();
        String idValue = bImpl.Request("idValue"),
                content = bImpl.Request("content"),
                printName = bImpl.Request("name");
        response.setData(moduleImpl.AddOrUpdWebPrint(ModuleId, printName, content, idValue));
        response.setSuccess(!isNullOrEmpty(response.getData() + ""));
    }

    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void UpdDownLoadCount() {
        String idValue = getBImpl().Request("idValue");
        moduleImpl.AddDownloadCount(ModuleId, idValue);
        response.setSuccess(true);
    }


    /**
     * 获取导出数据（主表及明细数据）
     */
    @RequestCheck(CheckParams = "ModuleId")
    public void GetExportData() {
        // 获取请求参数
        BaseImpl bImpl = getBImpl();
        String record = bImpl.Request("record") + "";
        String leftRecord = bImpl.Request("leftRecord");
        String pms = bImpl.Request("pms");
        String detailId = bImpl.Request("detailId") + "";
        String contextMenuId = bImpl.Request("contextMenuId") + "";
        String sourceId = bImpl.Request("sourceId") + "";
        String midAnddids = bImpl.Request("midAnddids");

        // 查询主模块数据
        response = moduleImpl.GetModuleData(
                ModuleId,
                record,
                leftRecord,
                pms,
                bImpl.Request("w"),
                NativeExtensionUtils.toBoolean(bImpl.Request("multi")),
                NativeExtensionUtils.toBoolean(bImpl.Request("grid")),
                NativeExtensionUtils.parseInt(contextMenuId), 0
        );

        // 转换主数据列表（假设返回数据为List<Map>）
        List<Map<String, Object>> mainData = (List<Map<String, Object>>) response.getData();
        Map<String, Object> responseData = new HashMap<>();
        Map<String, Object> midAnddidtab = new HashMap<>();
        Map<String, Object> ht = new HashMap<>();
        Map<String, Object> mainDataMap = new HashMap<>();
        List<Map<String, Object>> dataList;

        // 解析midAnddids为哈希表（JSON转Map）
        try {
            midAnddidtab = (Map<String, Object>) JSON.Decode(midAnddids);
        } catch (Exception e) {
            // 处理JSON解析异常
            response.setSuccess(false);
            response.setMsg("解析midAnddids失败: " + e.getMessage());
            return;
        }

        // 处理主数据量大于2000且存在明细关联的情况（分批处理）
        if (mainData.size() > 2000 && midAnddidtab != null && !midAnddidtab.isEmpty()) {
            List<Map<String, Object>> newData = new ArrayList<>();
            int count = mainData.size() / 2000;
            int index = 1;

            // 定义外部循环标签
            outerLoop:
            for (int j = 0; j < mainData.size(); j++) {
                newData.add(mainData.get(j));

                // 达到分批阈值或最后一条数据时处理
                if (j == (index * 2000) - 1 || j == mainData.size() - 1) {
                    for (String mid : midAnddidtab.keySet()) {
                        // 获取明细ID并转换为整数
                        int did = NativeExtensionUtils.parseInt(midAnddidtab.get(mid).toString());

                        // 查询导出数据
                        response = moduleImpl.GetExportData(
                                mid,
                                did,
                                newData,
                                index,
                                NativeExtensionUtils.toBoolean(bImpl.Request("multi")),
                                NativeExtensionUtils.toBoolean(bImpl.Request("grid")),
                                NativeExtensionUtils.toBoolean(bImpl.Request("isAttc"))
                        );

                        if (response.getOther() != null) {
                            Map<String, Object> resData = (Map<String, Object>) response.getData();

                            // 检查是否需要中断导出
                            if (!resData.containsKey("detailData") || !resData.containsKey("mainData")) {
                                if (resData.containsKey("stopexport")) {
                                    break outerLoop; // 跳出最外层循环
                                }
                            }

                            // 合并主数据
                            dataList = (List<Map<String, Object>>) resData.get("detailData");
                            List<Map<String, Object>> hashtab = (List<Map<String, Object>>) resData.get("mainData");

                            if (mainDataMap.containsKey("main")) {
                                List<Map<String, Object>> existing = (List<Map<String, Object>>) mainDataMap.get("main");
                                existing.addAll(hashtab);
                                mainDataMap.put("main", existing);
                            } else {
                                mainDataMap.put("main", hashtab);
                            }
                        } else {
                            dataList = (List<Map<String, Object>>) response.getData();
                        }

                        // 合并明细数据
                        Object didKey = midAnddidtab.get(mid);
                        if (ht.containsKey(didKey)) {
                            List<Map<String, Object>> existingDetails = (List<Map<String, Object>>) ht.get(didKey);
                            existingDetails.addAll(dataList);
                            ht.put(didKey + "", existingDetails);
                        } else {
                            ht.put(didKey + "", new ArrayList<>(dataList));
                        }
                    }

                    newData.clear();
                    if (index < count) {
                        index++;
                    }
                }
            }
        }
        // 处理主数据量小于等于2000的情况
        else if (mainData.size() > 0 && midAnddidtab != null && !midAnddidtab.isEmpty()) {
            // 定义循环标签
            outerLoop:
            for (String mid : midAnddidtab.keySet()) {
                int did = NativeExtensionUtils.parseInt(midAnddidtab.get(mid).toString());

                response = moduleImpl.GetExportData(
                        mid,
                        did,
                        mainData,
                        0,
                        NativeExtensionUtils.toBoolean(bImpl.Request("multi")),
                        NativeExtensionUtils.toBoolean(bImpl.Request("grid")),
                        NativeExtensionUtils.toBoolean(bImpl.Request("isAttc"))
                );

                if (response.getOther() != null) {
                    Map<String, Object> resData = (Map<String, Object>) response.getData();

                    // 检查是否需要中断导出
                    if (!resData.containsKey("detailData") || !resData.containsKey("mainData")) {
                        if (resData.containsKey("stopexport")) {
                            break outerLoop; // 跳出当前循环
                        }
                    }

                    mainDataMap.put("main", resData.get("mainData"));
                    ht.put(midAnddidtab.get(mid) + "", resData.get("detailData"));
                } else {
                    ht.put(midAnddidtab.get(mid) + "", response.getData());
                }
            }
        }

        // 组装最终响应数据
        responseData.put("mainData", mainDataMap.containsKey("main") ? mainDataMap.get("main") : mainData);
        responseData.put("detailData", ht);
        response.setData(responseData);
        response.setSuccess(true);
    }

    /**
     * 将List<Hashtable<String, Object>>转换为模拟的DataTable
     *
     * @param list 输入的哈希表列表
     * @return 包含列名和行数据的DataTable对象
     */
    public static List<Map<String, Object>> ConvertToDataTable(List<Map<String, Object>> list) {
//        List<Map<String, Object>> dt = new ArrayList<>();
//        if (list.isEmpty())
//            return dt;
//
//        for (String name : list.get(0).Keys)
//            dt.Columns.Add(name);
//
//        foreach(Hashtable item in list)
//        dt.Rows.Add(new ArrayList(item.Values).ToArray());
//
//        return dt;
        return list;
    }


    //region 地图相关接口


    /// <summary>
    /// 获取区域城市
    /// </summary>
    /// <remarks>

    /// </remarks>


    @RequestCheck(CheckParams = "cityname")
    public void GetArea() {
        response = getMapImpl().getArea(getBImpl().Request("cityname"));
    }


    @RequestCheck(CheckParams = "cityname")
    public void GetAreas() {
        response = getMapImpl().getAreas(getBImpl().Request("cityname"));
    }
    /// <summary>
    /// 加载区域树
    /// </summary>
    /// <remarks>

    /// </remarks>


    @RequestCheck(CheckParams = "cityname")
    public void GetAreasToTree() {
        response = getMapImpl().getAreasToTree(getBImpl().Request("cityname"));
    }

    /// <summary>
    /// 加载区域列表
    /// </summary>
    /// <param>无</param>
    /// <exception cref="Exception"></exception>
    /// <returns>无</returns>
    /// <remarks>

    /// </remarks>


    @RequestCheck(CheckParams = "id")
    public void GetAreaChildren() {
        response = getMapImpl().getAreaChildren(getBImpl().Request("id"));
    }
    /// <summary>
    /// 更新区域
    /// </summary>
    /// <remarks>

    /// </remarks>


    @RequestCheck(CheckParams = "id,data")
    public void UpdateArea() {
        BaseImpl bImpl = getBImpl();
        response.setSuccess(getMapImpl().updateArea(bImpl.Request("id") + "", bImpl.Request("data") + ""));
    }


    // region 轮询有关
    //轮询审核信息
    //  [RequestCheck(CheckParams = "userid")]

    @RequestCheck(Log = false)
    public void GetAuditMsgTab() {
        //  string userid = bImpl.Request("userid") + "";
        response = moduleImpl.GetAuditMsgTab(getUser().UserId);
    }


    @RequestCheck(CheckParams = "ModuleId,idValue")
    public void SeeOneAuditMsg() {
        String idValue = getBImpl().Request("idValue"), remark = getBImpl().Request("remark");
        response.setData(moduleImpl.ComfirmMsg(ModuleId, idValue, remark));
        response.setSuccess(true);
    }
    //SeeOveOneMsg

    @RequestCheck(CheckParams = "record")
    public void SeeOveOneMsg() {
        String record = getBImpl().Request("record");
        Map<String, Object> recordHS = (Map<String, Object>) JSON.Decode(record);

        response = moduleImpl.SeeOneAuditMsg(getUser().UserId, recordHS);
    }

    public void SeeAllAuditMsg() {
        response = moduleImpl.SeeAllAuditMsg();
    }


    @RequestCheck(CheckLogin = false)
    public void GetMsg() {
        BaseImpl bImpl = getBImpl();
        int msgId = ToInt32(bImpl.Request("id", bImpl.Request("msgid"))),
                type = ToInt32(bImpl.Request("t", "4"));
        response = moduleImpl.GetMsg(msgId, type);
    }


    // 角色权限设置

    @RequestCheck(CheckLogin = true)
    public void GetRoles() {
        response.setData(moduleImpl.GetRoles());
        response.setSuccess(response.getData() != null);
    }


    @RequestCheck(CheckLogin = true, CheckParams = "roleId")
    public void GetRoleUsers() {
        response.setData(moduleImpl.GetRoleUsers(getBImpl().Request("roleId")));
        response.setSuccess(response.getData() != null);
    }


    @RequestCheck(CheckLogin = true)
    public void GetUsers() {
        BaseImpl bImpl = getBImpl();
        String name = bImpl.Request("name"), code = bImpl.Request("code");

        response.setData(moduleImpl.GetUsers(name, code));
        response.setSuccess(response.getData() != null);
    }


    @RequestCheck(CheckLogin = true, CheckParams = "userId")
    public void GetUserPrev() {
        String userId = getBImpl().Request("userid");
        response = moduleImpl.GetUserPrev(userId);
    }

    @RequestCheck(CheckLogin = true, CheckParams = "datas")
    public void SaveRoles() {
        boolean isAdd = toBoolean(getBImpl().Request("add"));
        if (!isAdd) {
            response = moduleImpl.SaveRolePrev(getBImpl().Request("datas") + "");
        } else {
            response = moduleImpl.AddOrUpdTable(getBImpl().Request("datas") + "", "p_systemRoleSetTab", "id", null, null);
        }
    }

    public void SaveUserPrev() {
        response = moduleImpl.SaveUserPrev(getBImpl().Request("datas") + "");
    }


    @RequestCheck(CheckLogin = true, CheckParams = "idValue")
    public void DelRole() {
        response = moduleImpl.DelRoles(getBImpl().Request("idValue"));
    }


    @RequestCheck(CheckLogin = true, CheckParams = "idValue")
    public void DelRoleUser() {
        response = moduleImpl.DelRoleUser(getBImpl().Request("idValue"));
    }


    @RequestCheck(CheckLogin = true, CheckParams = "datas")
    public void SaveRoleUser() {
        response = moduleImpl.SaveRoleUser(getBImpl().Request("datas"));
    }


    // 评论

    public void SaveComment() {
        response = moduleImpl.AddOrUpdTable(getBImpl().Request("record"), "P_SystemCheckCommentTab", "id", null, null);
    }

    public void GetCommentList() {
        response.setData(moduleImpl.GetCommentList(ModuleId, getBImpl().Request("idValue"), getBImpl().Request("stepCode")));
        response.setSuccess(true);
    }

    /**
     * 桌面应用APis
     */
    @RequestCheck(CheckLogin = true)
    public void GetBSDesktopData() {
        response = moduleImpl.GetBSDesktopData();
    }

    @RequestCheck(CheckLogin = true, CheckParams = "dllcoid")
    public void GetBSDesktopModuleData() {
        BaseImpl bImpl = getBImpl();
        String dllcoid = bImpl.Request("dllcoid"), queryVal = bImpl.Request("queryVal");
        response = moduleImpl.GetBSDesktopModuleData(dllcoid, queryVal);
    }

    @RequestCheck(CheckLogin = true)
    public void GetBSDesktopAdminBase() {
        if (!Objects.equals(getUser().UserName, "管理员")) {
            response.setMsg("没有权限访问！");
            response.setSuccess(false);
        } else {
            response = moduleImpl.GetBSDesktopAdminBase();
        }
    }

    @RequestCheck(CheckLogin = true)
    public void GetBSDesktopExtend() {
        response = moduleImpl.GetBSDesktopExtend();
    }


    @RequestCheck(CheckLogin = true, CheckParams = "dllcoid")
    public void GetDesktopModuleOper() {
        String dllcoid = getBImpl().Request("dllcoid");
        response = moduleImpl.GetDesktopModuleOper(dllcoid);
    }

    /// <summary>
    /// 更新BI表中配置项目
    /// </summary>

    @RequestCheck(CheckParams = "datas,table")
    public void UpdBSDesktop() {
        BaseImpl bImpl = getBImpl();
        String recsStr = bImpl.Request("datas");
        boolean isAdd = "1".equals(bImpl.Request("isAdd", "0"));
        String idField = bImpl.Request("idField");
        String table = bImpl.Request("table", "");

        // 定义表名映射字典
        Map<String, String> tables = new HashMap<>();
        tables.put("admin", "P_SystemFirstPageSetTab");
        tables.put("extend", "P_SystemOperFirstPageTab");
        tables.put("module", "P_SystemDllFirstPageTab");
        tables.put("moduleOper", "P_SystemDllOperFirstPageTab");

        if (tables.containsKey(table)) {
            // 处理extend和module类型的记录
            if ("extend".equals(table) || "module".equals(table)) {
                List<Map<String, Object>> tempList = (List<Map<String, Object>>) JSON.Decode(recsStr);
                for (Map<String, Object> rec : tempList) {
                    rec.put("deleted", false);
                }
                recsStr = JSON.Encode(tempList);
            }

            // 获取主键信息并处理
            List<String> idFieldsA = moduleImpl.GetPrimaryKeysArray(tables.get(table));
//            System.out.println("idFieldsA: " + idFieldsA);
            String idF = moduleImpl.GetIdentityField(tables.get(table));
//            System.out.println("idF: " + idF);
            if (!idFieldsA.contains(idF)) {
                idFieldsA.add(idF);
            }

            // 拼接主键字符串（小写）
            String idFieldsStr = String.join(",", idFieldsA).toLowerCase();
//            System.out.println("idFieldsStr: " + idFieldsStr);
            response = moduleImpl.AddOrUpdTable(recsStr, tables.get(table), idFieldsStr, isAdd, null);
        } else {
            response.setSuccess(false);
            response.setMsg("错误的table参数");
        }
    }

    /**
     * 删除BI表中配置项目
     */
    // 假设使用自定义注解实现参数校验
    @RequestCheck(CheckParams = "table,ids")
    public void DeleteBSDesktop() {
        BaseImpl bImpl = getBImpl();
        String ids = bImpl.Request("ids", "");
        String[] idsA = ids.split(",");
        // 拼接SQL用的ids字符串（带单引号）
        String idsStr = "'" + String.join("','", idsA) + "'";
        String table = bImpl.Request("table", "");

        // 定义表名映射字典
        Map<String, String> tables = new HashMap<>();
        tables.put("admin", "P_SystemFirstPageSetTab");
        tables.put("extend", "P_SystemOperFirstPageTab");
        tables.put("module", "P_SystemDllFirstPageTab");

        if (tables.containsKey(table)) {
            boolean result = false;
            String targetTable = tables.get(table);

            switch (table) {
                case "extend":
                    // 更新extend类型记录为删除状态
                    String updateSql = String.format("update %s set [deleted]='True' where id in (%s)", targetTable, idsStr);
                    result = jdbcTemplate.update(updateSql) > 0;
                    break;
                case "admin":
                    // 直接删除admin类型记录
                    String deleteAdminSql = String.format("delete from %s where id in (%s)", targetTable, idsStr);
                    result = jdbcTemplate.update(deleteAdminSql) > 0;
                    break;
                case "module":
                    // 直接删除module类型记录
                    String deleteModuleSql = String.format("delete from %s where dllcoid in (%s)", targetTable, idsStr);
                    result = jdbcTemplate.update(deleteModuleSql) > 0;
                    break;
                default:
                    response.setSuccess(false);
                    response.setMsg("不支持的table类型");
                    return;
            }

            response.setData(result);
            response.setSuccess(true);
            response.setMsg("删除成功");
        } else {
            response.setSuccess(false);
            response.setMsg("错误的table参数");
        }
    }

    /// <summary>
    /// 获得主页搜索的结果。
    /// </summary>
    public void GetDeskQueryResult() {
        BaseImpl bImpl = getBImpl();
        String keyField = bImpl.Request("textField"),
                queryText = bImpl.Request(keyField);
        response = moduleImpl.GetDeskQueryResult(queryText);
    }

    /// <summary>
    /// 检查点击origin模块是基础模块 还是 单据
    /// </summary>
    public void CheckModuleOrBill() {
        String moduleId = getBImpl().Request("moduleId");
        response = moduleImpl.CheckModuleOrBill(moduleId);
    }

    public void ConvertDllName() {
        String dllName = getBImpl().Request("dllName");
        response = moduleImpl.ConvertDllName(dllName);
    }

    /// <summary>
    /// 模板页管理数据
    /// </summary>

    @RequestCheck(CheckLogin = true)
    public void GetDesktopModuleLeft() {
        response = moduleImpl.GetDesktopModuleLeft();
    }

    @RequestCheck(CheckLogin = true)
    public void GetDesktopModuleMain() {
        String leftRecordStr = getBImpl().Request("leftRecord");
        if (!isNullOrEmpty(leftRecordStr)) {
            Map<String, Object> leftRecordHS = (Map<String, Object>) JSON.Decode(leftRecordStr);
            String dllcoid = leftRecordHS.get("dllcoid") + "";
            response = moduleImpl.GetDesktopModuleMain(dllcoid);
        } else {
            response.setData(new ArrayList<>());
            response.setSuccess(true);
        }
    }

    @RequestCheck(CheckLogin = true)
    public void GetDeskTopCommonUse() {
        String cardIds = getBImpl().Request("id") + "";

        if (cardIds.contains(",")) {
            Map<String, Object> datas = new HashMap<>();
            String[] idArray = cardIds.split(",");
            for (String strId : idArray) {
                int cardId = Integer.parseInt(strId);
                datas.put(strId, moduleImpl.GetDeskTopCommonUse(cardId));
            }
            response.setData(datas);
        } else {
            int cardId = Integer.parseInt(cardIds);
            response.setData(moduleImpl.GetDeskTopCommonUse(cardId));
        }
        response.setSuccess(response.getData() != null);
    }


    @RequestCheck(CheckLogin = true)
    public void UpdCommonUse() {
        BaseImpl bImpl = getBImpl();
        String adds = bImpl.Request("adds"), dels = bImpl.Request("dels");
        int cardId = ToInt32(bImpl.Request("id"));
        response = moduleImpl.UpdCommonUse(cardId, adds, dels);
    }


    @RequestCheck(CheckParams = "ModuleId")
    public void GetClientSaveConds() {
        response = moduleImpl.GetClientSaveConds(ModuleId);
    }
}

