package com.hotent.surveyinfo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.query.PageList;
import com.hotent.base.util.PinyinUtil;
import com.hotent.common.CrudService;
import com.hotent.resp.PageResp;
import com.hotent.surveyinfo.dao.CostSurveyTemplateDao;
import com.hotent.surveyinfo.dao.CostSurveyTemplateHeadersDao;
import com.hotent.surveyinfo.dao.CostSurveyTemplateItemsDao;
import com.hotent.surveyinfo.manager.*;
import com.hotent.surveyinfo.model.*;
import com.hotent.surveyinfo.req.ConstSurveyPageParam;
import com.hotent.surveyinfo.req.ConstSurveyPageReq;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.api.service.IUserService;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.User;
import com.hotent.uc.util.ContextUtil;
import io.swagger.annotations.Api;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.hotent.base.controller.BaseController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 成本调查表模板表 前端控制器
 *
 * @author 超级管理员
 * @company 山西清众科技股份有限公司
 * @since 2025-09-19
 */
@RestController
@RequestMapping("/costSurveyTemplate/v1/")
@Api(tags = "成本调查")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostSurveyTemplateController extends BaseController<CostSurveyTemplateManager, CostSurveyTemplate> {
    @Autowired
    CostSurveyTemplateManager constbaseService;

    @Autowired
    CostSurveyTemplateDao costSurveyTemplateDao;

    @Autowired
    CostSurveyTemplateVersionManager costSurveyTemplateVersionMapper;
    @Autowired
    CostSurveyTemplateHeadersDao costSurveyTemplateHeadersDao;
    @Autowired
    CostSurveyTemplateItemsDao costSurveyTemplateItemsDao;

    @Autowired
    private CostVerifyTemplateManager costVerifyTemplateManager;

    @Autowired
    private CostVerifyTemplateHeadersManager costVerifyTemplateHeadersManager;


    @Autowired
    private CostVerifyTemplateItemsManager costVerifyTemplateItemsManager;

    @Autowired
    private UserManager userService;
    // 创建通用服务实例
    private final CrudService crudService = new CrudService();

    /**
     * 获取所有成本调查表模板数据
     *
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/listPage")
    @ApiOperation(value = "获取成本调查表模板数据", httpMethod = "POST", notes = "获取所有成本调查表模板数据集合")
    public PageList<CostSurveyTemplate> listPage(
            @RequestBody ConstSurveyPageParam params) throws Exception {
        return constbaseService.getCostSurveyListPage(params);
    }

    /**
     * 获取所有现行版启用的成本调查表模板数据
     *
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getallCurrentCostSurveyList")
    @ApiOperation(value = "获取所有现行版启用的成本调查表模板数据", httpMethod = "GET", notes = "获取所有现行版启用的成本调查表模板数据")
    public PageResp<CostSurveyTemplate> allCurrentCostSurveyList(ConstSurveyPageReq req) throws Exception {
        return crudService.pageQuery(req, constbaseService::getallCurrentCostSurveyList);
    }


    /**
     * 根据id获取成本调查表模板表数据详情
     *
     * @param id
     * @return
     * @throws Exception ModelAndView
     */
    @GetMapping(value = "/getDetail")
    @ApiOperation(value = "根据id获取成本调查表模板表数据详情", httpMethod = "GET", notes = "根据id获取成本调查表模板表数据详情")
    public CommonResult<CostSurveyTemplate> getDetail(@ApiParam(name = "id", value = "业务对象主键", required = true) @RequestParam(required = true) String id) throws Exception {
        return CommonResult.<CostSurveyTemplate>ok().value(baseService.getDetail(id));
    }

    /**
     * 新增,更新成本调查表模板表
     *
     * @param costSurveyTemplate
     * @return
     * @throws Exception
     * @throws
     */
    @PostMapping(value = "/save")
    @ApiOperation(value = "新增,更新成本调查表模板表数据", httpMethod = "POST", notes = "新增,更新成本调查表模板表数据")
    public CommonResult<String> save(@ApiParam(name = "CostSurveyTemplate", value = "成本调查表模板表对象", required = true) @RequestBody CostSurveyTemplate costSurveyTemplate) throws Exception {
        String msg = StringUtil.isEmpty(costSurveyTemplate.getSurveyTemplateId()) ? "添加成本调查表模板表成功" : "更新成本调查表模板表成功";
        User currentUser = ContextUtil.getCurrentUser();
        currentUser = userService.get(currentUser.getUserId());
        Integer dataScope = currentUser.getDataScope();
        if (dataScope == 0) {
            costSurveyTemplate.setAreaLevel("0");
            costSurveyTemplate.setAreaCode(currentUser.getProvinceCode());
        } else if (dataScope == 1){
            costSurveyTemplate.setAreaLevel("1");
            costSurveyTemplate.setAreaCode(currentUser.getCityCode());
        }else{
            costSurveyTemplate.setAreaLevel("2");
            costSurveyTemplate.setAreaCode(currentUser.getCountyCode());
        }
        if (StringUtil.isEmpty(costSurveyTemplate.getSurveyTemplateId())) {
            IUser user = ContextUtil.getCurrentUser();
            costSurveyTemplate.setCreateBy(user.getAccount());
            costSurveyTemplate.setCreateTime(LocalDateTime.now());
            costSurveyTemplate.setIsDelete("0");
            costSurveyTemplate.setStatus("-1");
        } else {
            costSurveyTemplate.setUpdateBy(ContextUtil.getCurrentUser().getAccount());
            costSurveyTemplate.setUpdateTime(LocalDateTime.now());
        }

        baseService.createOrUpdate(costSurveyTemplate);
        return CommonResult.<String>ok().message(msg);
    }

    /**
     * 根据id删除成本调查表模板数据
     *
     * @param id
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据id删除成本调查表模板数据", httpMethod = "GET", notes = "根据id删除成本调查表模板数据")
    @GetMapping(value = "/remove")
    public CommonResult<String> remove(@ApiParam(name = "id", value = "业务对象主键", required = true) @RequestParam(required = true) String id) throws Exception {
        baseService.remove(id);
        return CommonResult.<String>ok().message("删除成本调查表模板成功");
    }


    /**
     * 批量删除成本调查表模板数据
     *
     * @param ids 要删除的ID列表
     * @return 操作结果
     * @throws Exception
     */
    @ApiOperation(value = "批量删除成本调查表模板数据", httpMethod = "POST", notes = "批量删除成本调查表模板数据")
    @PostMapping(value = "/batchRemove")
    public CommonResult<String> batchRemove(@ApiParam(name = "ids", value = "业务对象主键列表", required = true) @RequestBody List<String> ids) throws Exception {
        if (ids == null || ids.isEmpty()) {
            return CommonResult.<String>error().message("删除失败：未选择任何数据");
        }

        try {
            baseService.batchRemove(ids);
            return CommonResult.<String>ok().message("成功删除" + ids.size() + "条数据");
        } catch (Exception e) {
            return CommonResult.<String>error().message("删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取除去指定ID外的所有成本调查表模板列表
     *
     * @param surveyTemplateId 要排除的模板ID
     * @return 成本调查表模板列表
     * @throws Exception
     */
    @GetMapping(value = "/listExcludeId")
    @ApiOperation(value = "计算公式-选择成本调查表", httpMethod = "GET", notes = "获取除去指定ID外的所有成本调查表模板列表")
    public CommonResult<List<CostSurveyTemplate>> listExcludeId(
            @ApiParam(name = "surveyTemplateId", value = "要排除的模板ID", required = false)
            @RequestParam(required = false) String surveyTemplateId) throws Exception {

        CostSurveyTemplate queryCondition = new CostSurveyTemplate();
        queryCondition.setStatus("0");//启用状态的成本调查表模板
        queryCondition.setTemplateType("2"); // 模板类型为固定表
//		IUser user = ContextUtil.getCurrentUser();
//		queryCondition.setCreateBy(user.getAccount());
        // 这里可以根据业务需要设置其他查询条件
        List<CostSurveyTemplate> allTemplates = costSurveyTemplateDao.selectByCondition(queryCondition);

        // 如果提供了excludeId，则过滤掉该ID的记录
        if (surveyTemplateId != null && !surveyTemplateId.isEmpty()) {
            allTemplates = allTemplates.stream()
                    .filter(template -> !surveyTemplateId.equals(template.getSurveyTemplateId()))
                    .collect(Collectors.toList());
        }

        return CommonResult.<List<CostSurveyTemplate>>ok().value(allTemplates);
    }

    /**
     * 获取所有模板类型为固定表的所有启用成本调查表数据
     *
     * @return 启用的固定表类型成本调查表列表
     * @throws Exception
     */
    @GetMapping(value = "/listFixedEnabled")
    @ApiOperation(value = "获取所有模板类型为固定表的所有启用成本调查表数据", httpMethod = "GET", notes = "获取所有模板类型为固定表的所有启用成本调查表数据")
    public CommonResult<List<CostSurveyTemplate>> listFixedEnabled() throws Exception {
        CostSurveyTemplate queryCondition = new CostSurveyTemplate();
        queryCondition.setStatus("0"); // 启用状态
        queryCondition.setTemplateType("2"); // 模板类型为固定表

        List<CostSurveyTemplate> templates = costSurveyTemplateDao.selectByCondition(queryCondition);
        return CommonResult.<List<CostSurveyTemplate>>ok().value(templates);
    }

    /**
     * 生成核定模板数据（通过templateId，状态为启用）
     *
     * @param templateId 模板ID
     * @return 核定模板数据
     * @throws Exception
     */
    @GetMapping(value = "/generateVerifyTemplateData")
    @ApiOperation(value = "生成核定模板数据", httpMethod = "GET", notes = "通过templateId获取启用状态的核定模板数据")
    public CommonResult<CostVerifyTemplate> generateVerifyTemplateData(
            @ApiParam(name = "templateId", value = "模板ID", required = true)
            @RequestParam String templateId, @ApiParam(name = "templatename", value = "模板名称", required = true)
            @RequestParam String templatename, @ApiParam(name = "catalogId", value = "监审id", required = true)
            String taskId, @ApiParam(name = "taskId", value = "任务id", required = false)
            @RequestParam String catalogId) throws Exception {

        if (taskId!=null){
            //先删
            costVerifyTemplateManager.remove(
                    new QueryWrapper<CostVerifyTemplate>()
                            .eq("task_id", taskId)
            );
        }
        CostSurveyTemplate queryCondition = new CostSurveyTemplate();
        queryCondition.setSurveyTemplateId(templateId);
        queryCondition.setStatus("0"); // 启用状态
        IUser user = ContextUtil.getCurrentUser();
        List<CostSurveyTemplate> templates = costSurveyTemplateDao.selectByCondition(queryCondition);
        CostSurveyTemplateVersion currentVersion = costSurveyTemplateVersionMapper.selectCurrentVersion(templateId);
        List<CostSurveyTemplateItems> updateites = new ArrayList<>();
        String ttemplateId = "";
        CostVerifyTemplate costVerifyTemplate = new CostVerifyTemplate();
        if (currentVersion != null) {
            CostSurveyTemplate sourceTemplate = templates.get(0);

            List<CostSurveyTemplateHeaders> headersList = costSurveyTemplateHeadersDao.selectBySurveyTemplateIdAndVersion(templateId, currentVersion.getId());
            List<CostSurveyTemplateItems> itemsList = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersion(templateId, currentVersion.getId());

            // 1. 开始将模板数据写入 CostVerifyTemplate 表中

            // 复制源模板的基本属性
            ttemplateId = UUID.randomUUID().toString();
            costVerifyTemplate.setSurveyTemplateId(ttemplateId);
            costVerifyTemplate.setSurveyTemplateName(sourceTemplate.getSurveyTemplateName());
            costVerifyTemplate.setTemplateType(sourceTemplate.getTemplateType());
            costVerifyTemplate.setCreatemode("1");
            costVerifyTemplate.setSurveyTemplateNameYw(PinyinUtil.getPinyin(sourceTemplate.getSurveyTemplateName()));
            costVerifyTemplate.setCreatetemplateid(sourceTemplate.getSurveyTemplateId());
            costVerifyTemplate.setStatus(taskId==null?"-1":"0");
            costVerifyTemplate.setCatalogId(catalogId);
            costVerifyTemplate.setCreateBy(user.getAccount());
            costVerifyTemplate.setCreateTime(LocalDateTime.now());
            costVerifyTemplate.setType(sourceTemplate.getType());
            costVerifyTemplate.setIsDelete("0");
            costVerifyTemplate.setTaskId(taskId);

            //			costVerifyTemplate.setCatalogId(sourceTemplate.getCatalogId());

            // 设置与源模板的关联关系

            costVerifyTemplate.setVersionNo(costVerifyTemplateManager.generateVersionNumber());

            // 保存成本核定模板
            costVerifyTemplateManager.createOrUpdate(costVerifyTemplate);

            // 2. 将headersList数据写入 CostVerifyTemplateHeaders 表中（批量保存）
            if (headersList != null && !headersList.isEmpty()) {
                List<CostVerifyTemplateHeaders> verifyHeadersList = new ArrayList<>();
                for (CostSurveyTemplateHeaders header : headersList) {
                    CostVerifyTemplateHeaders verifyHeader = new CostVerifyTemplateHeaders();
                    // 复制表头属性
                    String headid = UUID.randomUUID().toString();
                    verifyHeader.setId(headid);
                    verifyHeader.setFieldName(header.getFieldName());
                    verifyHeader.setFieldEname(header.getFieldEname());
                    verifyHeader.setFieldType(header.getFieldType());

                    // 关键：复制字段验证相关属性
                    verifyHeader.setFieldTypelen(header.getFieldTypelen());           // 字段类型长度
                    verifyHeader.setFieldTypenointlen(header.getFieldTypenointlen()); // 字段类型小数位长度
                    verifyHeader.setFormat(header.getFormat());                       // 格式
                    verifyHeader.setIsDict(header.getIsDict());                       // 是否绑定字典
                    verifyHeader.setIsAuditPeriod(header.getIsAuditPeriod());         // 是否绑定监审期间
                    verifyHeader.setShowVisible(header.getShowVisible());             // 隐藏字段显示

                    verifyHeader.setTabtype(header.getTabtype());
                    verifyHeader.setIsRequired(header.getIsRequired());
                    verifyHeader.setOrderNum(header.getOrderNum());
                    verifyHeader.setDictid(header.getDictid());
                    verifyHeader.setDictCode(header.getDictCode());
                    verifyHeader.setColumnComment(header.getColumnComment());
                    verifyHeader.setColumnType(header.getColumnType());

                    // 区域相关属性
                    verifyHeader.setAreaCode(header.getAreaCode());
                    verifyHeader.setAreaLevel(header.getAreaLevel());

                    // 系统字段
                    verifyHeader.setCreateBy(user.getAccount());
                    verifyHeader.setCreateTime(LocalDateTime.now());


                    // 设置关联关系
                    verifyHeader.setSurveyTemplateId(ttemplateId);
                    verifyHeader.setVersionId(currentVersion.getId());

                    //修改items 指标项中的headersid
                    if (itemsList != null && !itemsList.isEmpty()) {
                        for (CostSurveyTemplateItems items : itemsList) {
                            if (items.getHeadersId().equals(header.getId())) {
                                items.setHeadersId(headid);
                                updateites.add(items);
                            }

                        }
                    }
                    // 添加到批量保存列表
                    verifyHeadersList.add(verifyHeader);
                }
                // 批量保存成本核定表头
                costVerifyTemplateHeadersManager.batchCreate(verifyHeadersList);
            }

            // 3. 将itemsList数据写入 CostVerifyTemplateItems 表中（批量保存）
            if (updateites != null && !updateites.isEmpty()) {
                List<CostVerifyTemplateItems> verifyItemsList = new ArrayList<>();
                for (CostSurveyTemplateItems item : updateites) {
                    CostVerifyTemplateItems verifyItem = new CostVerifyTemplateItems();
                    // 复制数据项属性
                    String itemid = UUID.randomUUID().toString();
                    verifyItem.setId(itemid);
                    verifyItem.setRowid(item.getRowid());
                    verifyItem.setParentid(item.getParentid());
                    verifyItem.setRkey(item.getRkey());
                    verifyItem.setRvalue(item.getRvalue());
                    verifyItem.setCellCode(item.getCellCode());
                    verifyItem.setCalculationFormula(item.getCalculationFormula());
                    verifyItem.setUnit(item.getUnit());
                    verifyItem.setOrderNum(item.getOrderNum());
                    verifyItem.setJsonStr(item.getJsonStr());
                    verifyItem.setCreateBy(user.getAccount());
                    verifyItem.setCreateTime(LocalDateTime.now());
                    verifyItem.setProjectId(item.getProjectId());
                    verifyItem.setOrderText(item.getOrderText());
                    verifyItem.setSurveyTemplateId(ttemplateId);
                    verifyItem.setVersionId(currentVersion.getId());
                    verifyItem.setHeadersId(item.getHeadersId());

                    // 添加到批量保存列表
                    verifyItemsList.add(verifyItem);
                }
                // 批量保存成本核定数据项
                costVerifyTemplateItemsManager.saveBatch(verifyItemsList);
            }
        }

        if (templates != null && !templates.isEmpty()) {
            return CommonResult.<CostVerifyTemplate>ok().value(costVerifyTemplate);
        } else {
            return CommonResult.<CostVerifyTemplate>error().message("未找到启用状态的模板数据");
        }
    }

    /**
     * 生成版本号，格式为：yyyyMMdd + 4位流水号（如：202509270001）
     *
     * @return 生成的版本号
     */
    public String generateVersionNumber() {
        // 1. 获取当前日期字符串
        String dateStr = new java.text.SimpleDateFormat("yyyyMMdd").format(new java.util.Date());

        // 2. 查询当日最大版本号
        String maxVersion = costSurveyTemplateVersionMapper.selectMaxVersionByDate(dateStr);

        int sequence = 1;
        if (maxVersion != null && maxVersion.startsWith(dateStr)) {
            // 3. 提取流水号部分并加1
            String sequenceStr = maxVersion.substring(8); // 取后4位
            sequence = Integer.parseInt(sequenceStr) + 1;
        }

        // 4. 格式化生成版本号
        return String.format("%s%04d", dateStr, sequence);
    }


    /**
     * 导出成本调查表Excel模板
     *
     * @param templateId 模板ID
     * @return Excel文件
     * @throws Exception
     */
    @GetMapping(value = "/exportExcelTemplate")
    @ApiOperation(value = "导出成本调查表Excel模板", httpMethod = "GET", notes = "导出Excel模板并填充内容")
    public void exportExcelTemplate(
            @ApiParam(name = "templateId", value = "模板ID", required = true)
            @RequestParam String templateId,
            HttpServletResponse response) throws Exception {

        // 获取当前启用版本
        CostSurveyTemplateVersion currentVersion = costSurveyTemplateVersionMapper.selectCurrentVersion(templateId);

        if (currentVersion == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "未找到启用的模板版本");
            return;
        }

        // 获取表头信息
        List<CostSurveyTemplateHeaders> headersList = costSurveyTemplateHeadersDao.selectBySurveyTemplateIdAndVersion(templateId, currentVersion.getId());

        // 获取数据项信息
        List<CostSurveyTemplateItems> itemsList = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersion(templateId, currentVersion.getId());

        // 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(currentVersion.getSurveyTemplateName());

        // 创建表头行
        Row headerRow = sheet.createRow(0);

        // 根据表头信息创建Excel列标题
        for (int i = 0; i < headersList.size(); i++) {
            CostSurveyTemplateHeaders header = headersList.get(i);
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(header.getFieldName());
        }

        // 按照orderNum排序表头
        headersList.sort(Comparator.comparing(CostSurveyTemplateHeaders::getOrderNum,
                Comparator.nullsLast(Comparator.naturalOrder())));

        // 填充数据行（示例数据）
        if (!itemsList.isEmpty()) {
            // 按orderNum排序数据项
            itemsList.sort(Comparator.comparing(CostSurveyTemplateItems::getOrderNum,
                    Comparator.nullsLast(Comparator.naturalOrder())));

            // 创建示例行
            Row dataRow = sheet.createRow(1);
            for (int i = 0; i < headersList.size(); i++) {
                CostSurveyTemplateHeaders header = headersList.get(i);
                Cell cell = dataRow.createCell(i);

                // 查找对应的数据项
                for (CostSurveyTemplateItems item : itemsList) {
                    if (item.getHeadersId().equals(header.getId())) {
                        cell.setCellValue(item.getRvalue() != null ? item.getRvalue() : "");
                        break;
                    }
                }
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" +
                URLEncoder.encode(currentVersion.getSurveyTemplateName() + ".xlsx", "UTF-8"));

        // 写入响应输出流
        workbook.write(response.getOutputStream());
        workbook.close();
    }


    /**
     * 根据监管目录ID查询所有现行版本的所有成本调查表模板信息
     *
     * @param catalogId 监管目录ID
     * @return 成本调查表模板列表
     * @throws Exception
     */
    @GetMapping(value = "/listByCatalogId")
    @ApiOperation(value = "根据监管目录ID查询所有现行版本的成本调查表模板", httpMethod = "GET", notes = "根据监管目录ID查询所有现行版本的成本调查表模板信息")
    public CommonResult<List<CostSurveyTemplate>> listByCatalogId(
            @ApiParam(name = "catalogId", value = "监管目录ID", required = true)
            @RequestParam String catalogId) throws Exception {

        // 查询指定目录下的所有启用状态的模板
        CostSurveyTemplate queryCondition = new CostSurveyTemplate();
        queryCondition.setCatalogId(catalogId);
        queryCondition.setStatus("0"); // 启用状态

        List<CostSurveyTemplate> templates = costSurveyTemplateDao.selectByCondition(queryCondition);


        return CommonResult.<List<CostSurveyTemplate>>ok().value(templates);
    }


    /**
     * 状态切换方法
     * 当状态为-1(草稿)时启用为0(启用)
     * 当状态为0(启用)或1(停用)时可以相互切换
     *
     * @param id 成本调查表模板ID
     * @return 操作结果
     * @throws Exception
     */
    @ApiOperation(value = "状态切换", httpMethod = "GET", notes = "根据当前状态进行切换：草稿(-1)可启用为启用(0)，启用(0)和停用(1)可相互切换")
    @GetMapping(value = "/enable")
    public CommonResult<String> enable(
            @ApiParam(name = "id", value = "成本调查表模板ID", required = true)
            @RequestParam String id) throws Exception {

        CostSurveyTemplate template = baseService.get(id);
        if (template == null) {
            return CommonResult.<String>error().message("未找到指定的成本调查表模板");
        }

        String currentStatus = template.getStatus();
        String newStatus = null;
        String message = null;

        // 根据当前状态决定切换到什么状态
        if ("-1".equals(currentStatus)) {
            // 草稿状态切换到启用状态
            newStatus = "0";
            message = "成本调查表模板启用成功";

            // 检查是否已经有现行版本
            CostSurveyTemplateVersion currentVersion = costSurveyTemplateVersionMapper.selectCurrentVersion(id);
            if (currentVersion == null) {
                return CommonResult.<String>error().message("启用失败：该模板没有现行版本");
            }
        } else if ("0".equals(currentStatus)) {
            // 启用状态切换到停用状态
            newStatus = "1";
            message = "成本调查表模板停用成功";
        } else if ("1".equals(currentStatus)) {
            // 停用状态切换到启用状态
            newStatus = "0";
            message = "成本调查表模板启用成功";
        } else {
            return CommonResult.<String>error().message("不支持的状态切换操作");
        }

        // 更新状态
        template.setStatus(newStatus);
        template.setUpdateTime(LocalDateTime.now());
        template.setUpdateBy(ContextUtil.getCurrentUser().getAccount());

        baseService.createOrUpdate(template);

        return CommonResult.<String>ok().message(message);
    }


}
