package com.zt.plat.module.base.service.tmpltp;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.framework.tenant.core.context.CompanyContextHolder;
import com.zt.plat.module.base.controller.admin.templtp.vo.*;
import com.zt.plat.module.base.dal.dataobject.tmpltp.*;
import com.zt.plat.module.base.dal.mysql.tmpltp.*;
import com.zt.plat.module.system.api.dept.DeptApi;
import com.zt.plat.module.system.api.dept.dto.DeptRespDTO;
import com.zt.plat.module.tmpltp.enums.DeleteStatusEnum;
import com.zt.plat.module.tmpltp.enums.PublishStatusEnum;
import com.zt.plat.module.tmpltp.enums.TmplStsEnum;
import com.zt.plat.module.tmpltp.enums.UpdateStatusEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.tmpltp.enums.ErrorCodeConstants.*;


/**
 * 模板实例 Service 实现类
 *
 * @author 后台管理
 */
@Slf4j
@Service
@Validated
public class TemplateInstanceServiceImpl implements TemplateInstanceService {
    @Resource
    private DeptApi deptApi;
    @Resource
    private TemplateInstanceMapper templateInstanceMapper;
    @Resource
    private DepartmentInstanceRelativityMapper departmentInstanceRelativityMapper;
    @Resource
    private TemplateInstanceDataMapper templateInstanceDataMapper;
    @Resource
    private TemplateInstanceItemMapper templateInstanceItemMapper;
    @Resource
    private TmplItmService tmplItmService;
    @Resource
    private TmplTpFldService tmplTpFldService;
    @Resource
    private TmplTpService tmplTpService;

    @Override
    @Transactional
    public TemplateInstanceRespVO createTemplateInstance(TemplateInstanceSaveReqVO createReqVO) {
        // 插入
        TemplateInstanceDO templateInstance = BeanUtils.toBean(createReqVO, TemplateInstanceDO.class);
        templateInstance.setVer("v1.0"); //设置初始版本为v1.0
        templateInstance.setCdg(getCdg());//设置初始编码
        templateInstance.setSts(TmplStsEnum.DRAFT.getCode());//设置初始状态为草稿
        int insert = templateInstanceMapper.insert(templateInstance);
        if (insert <= 0) {
            throw exception(TEMPLATE_INSTANCE_CREATE_FAIL);
        }
        log.info("创建模板实例成功，模板实例：【{}】", templateInstance);

        //构建使用部门
        List<DepartmentInstanceRelativityDO> departmentInstanceRelativityDOS = new ArrayList<>();
        createReqVO.getDeptIds().forEach(deptId -> {
            DepartmentInstanceRelativityDO departmentInstanceRelativityDO = new DepartmentInstanceRelativityDO();
            departmentInstanceRelativityDO.setTemplateInstanceId(String.valueOf(templateInstance.getId()));
            departmentInstanceRelativityDO.setCompanyDepartmentId(deptId);
            departmentInstanceRelativityDOS.add(departmentInstanceRelativityDO);
        });
        departmentInstanceRelativityMapper.insertBatch(departmentInstanceRelativityDOS);
        log.info("创建模板实例成功，模板实例：【{}】", departmentInstanceRelativityDOS);
        // 插入使用范围
        TemplateInstanceRespVO templateInstanceRespVO = BeanUtils.toBean(templateInstance, TemplateInstanceRespVO.class);
        templateInstanceRespVO.setDeptIds(createReqVO.getDeptIds());
        return templateInstanceRespVO;
    }

    @Override
    public void updateTemplateInstance(TemplateInstanceSaveReqVO updateReqVO) {
        // 校验存在
        validateTemplateInstanceExists(updateReqVO.getId());
        //校验该记录能否被修改
        validateStatusCanUpdate(updateReqVO.getId());
        // 更新
        TemplateInstanceDO templateInstanceDO = templateInstanceMapper.selectById(updateReqVO.getId());
        TemplateInstanceDO updateObj = BeanUtils.toBean(updateReqVO, TemplateInstanceDO.class);
        //  updateObj.setVer(incrementVersion(templateInstanceDO.getVer()));
        templateInstanceMapper.updateById(updateObj);
        log.info("更新模板实例成功，模板实例：【{}】", templateInstanceDO);
    }

    @Override
    @Transactional
    public void deleteTemplateInstance(Long id) {
        // 校验存在
        validateTemplateInstanceExists(id);
        validateStatusCanDelete(id);
        // 删除
        //删除对应的字段和条款关系
        //1、删除合同的与字段的关系
        templateInstanceDataMapper.deleteByTemplateInstanceIds(List.of(id));
        log.info("删除模板实例字段成功，模板实例id：【{}】", id);
        //2、删除条款与和他的关系
        templateInstanceItemMapper.deleteByTemplateInstanceIds(List.of(id));
        log.info("删除模板实例条款成功，模板实例id：【{}】", id);
        templateInstanceMapper.deleteById(id);
        log.info("删除模板实例成功，模板实例id：【{}】", id);
    }

    @Override
    @Transactional
    public void deleteTemplateInstanceListByIds(List<Long> ids) {
        // 校验存在
        validateTemplateInstanceExists(ids);
        //校验当前模版能否被删除
        validateStatusCanDelete(ids);
        templateInstanceItemMapper.deleteByTemplateInstanceIds(ids);
        log.info("删除模板实例条款成功，模板实例ids：【{}】", ids);
        templateInstanceDataMapper.deleteByTemplateInstanceIds(ids);
        log.info("删除模板实例字段成功，模板实例ids：【{}】", ids);
        // 删除
        templateInstanceMapper.deleteByIds(ids);
        log.info("删除模板实例成功，模板实例id：【{}】", ids);
    }

    private void validateTemplateInstanceExists(List<Long> ids) {
        List<TemplateInstanceDO> list = templateInstanceMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(TEMPLATE_INSTANCE_NOT_EXISTS);
        }
    }

    private void validateTemplateInstanceExists(Long id) {
        if (templateInstanceMapper.selectById(id) == null) {
            throw exception(TEMPLATE_INSTANCE_NOT_EXISTS);
        }
    }

    @Override
    public TemplateInstanceDO getTemplateInstance(Long id) {
        return templateInstanceMapper.selectById(id);
    }

    @Override
    public PageResult<TemplateInstanceDO> getTemplateInstancePage(TemplateInstancePageReqVO pageReqVO) {
        return templateInstanceMapper.selectPage(pageReqVO);
    }

    @NotNull
    private String incrementVersion(String currentVersion) {
        // 处理空值或空字符串
        if (currentVersion == null || currentVersion.trim().isEmpty()) {
            return "v1";
        }

        String version = currentVersion.trim();
        // 正则模式：前缀(可选) + 数字部分 + 后缀(可选)
        // 数字部分匹配一个或多个数字
        Pattern VERSION_PATTERN = Pattern.compile("^([^0-9]*?)(\\d+)(.*)$");
        Matcher matcher = VERSION_PATTERN.matcher(version);

        if (!matcher.matches()) {
            // 没有找到数字部分，返回默认版本
            return version + "1";
        }

        String prefix = matcher.group(1);      // 前缀部分（如 "v", "version-" 等）
        String numberPart = matcher.group(2);  // 数字部分（如 "1", "123"）
        String suffix = matcher.group(3);      // 后缀部分

        try {
            // 将数字部分解析为整数并加1
            int number = Integer.parseInt(numberPart);
            number++;

            // 重新组合版本号
            return prefix + number + suffix;
        } catch (NumberFormatException e) {
            // 解析数字格式异常时的 fallback
            return prefix + "1" + suffix;
        }
    }


    @Override
    public List<String> getDeptByInstanId(Long instanId) {
        Long loginUserCompanyId = SecurityFrameworkUtils.getLoginUserCompanyId();
        return departmentInstanceRelativityMapper.selectList(new LambdaQueryWrapper<DepartmentInstanceRelativityDO>()
                        .eq(DepartmentInstanceRelativityDO::getTemplateInstanceId, instanId)
                        .eq(DepartmentInstanceRelativityDO::getCompanyId, loginUserCompanyId)
                )
                .stream()
                .map(DepartmentInstanceRelativityDO::getCompanyDepartmentId)
                .toList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publishTemplateInstance(List<PublishTemplateInstanceReqVO> publishReqVOS) {
        // 校验当前状态是否能够进行发布
        publishReqVOS.forEach(reqVO -> {
            TemplateInstanceDO templateInstanceDO = templateInstanceMapper.selectById(reqVO.getId());
            if (templateInstanceDO.getCntt() == null || templateInstanceDO.getCntt().isEmpty()) {
                throw exception(TEMPLATE_INSTANCE_FILE_NOT_EXISTS);
            }
            String currentStatus = reqVO.getCurrentStatus();
            if (currentStatus.isEmpty()) {
                currentStatus = templateInstanceDO.getSts();
            }
            PublishStatusEnum status = PublishStatusEnum.fromCode(currentStatus);
            boolean transitionAllowed = false;
            if (status != null) {
                transitionAllowed = status.isTransitionAllowed(TmplStsEnum.DRAFT.getCode());
                if (!transitionAllowed) {
                    transitionAllowed = status.isTransitionAllowed(TmplStsEnum.START.getCode());
                }
            }
            if (!transitionAllowed) {
                throw exception(STATUS_OPERATION_FAIL);
            }
        });
        log.info("发布模版实例【{}】", publishReqVOS.stream().map(PublishTemplateInstanceReqVO::getId));
        templateInstanceMapper.update(new LambdaUpdateWrapper<TemplateInstanceDO>()
                .in(TemplateInstanceDO::getId, publishReqVOS.stream()
                        .map(PublishTemplateInstanceReqVO::getId)
                        .collect(Collectors.toSet()))
                .set(TemplateInstanceDO::getSts, TmplStsEnum.PUBLISHED.getCode()).set(TemplateInstanceDO::getPublishTime, LocalDateTime.now()));
        log.info("更新模版实例状态成功【{}】", publishReqVOS.stream().map(PublishTemplateInstanceReqVO::getId));
    }

    @Override
    public PageResult<TemplateInstanceDO> listExcludingDisabled(TemplateInstancePageReqVO pageReqVO) {
        log.info("查询除了停用外的模版实例【{}】", pageReqVO);
        return templateInstanceMapper.listExcludingDisabled(pageReqVO);
    }

    @Override
    public void setDisableOrEnable(DisableEnableReqVO reqVO) {
        validateTemplateInstanceExists(reqVO.getIds().stream().map(Long::valueOf).toList());
        String code = "";
        if (reqVO.getType().equals("disable")) {
            // 禁用
            code = TmplStsEnum.STOPPED.getCode();
        } else if (reqVO.getType().equals("enable")) {
            // 启用
            code = TmplStsEnum.DRAFT.getCode();
        }
        if (code.isEmpty()) {
            throw exception(ILLEGAL_OPERATION_TYPE);
        }
        log.info("=============================当前操作记录为【{}】操作动作为:【{}】================================", reqVO.getIds(), reqVO.getType());
        templateInstanceMapper.update(new LambdaUpdateWrapper<TemplateInstanceDO>()
                .set(TemplateInstanceDO::getSts, code)
                .in(TemplateInstanceDO::getId, reqVO.getIds()));
    }

    @Override
    @Transactional
    public TemplateInstanceRespVO createVersion(String id) {
        validateTemplateInstanceExists(Long.valueOf(id));
        TemplateInstanceDO templateInstanceDO = templateInstanceMapper.selectById(id);
        //如果当前状态不是草稿或者是已启用则不能创建新版本
        log.info("当前状态【{}】", templateInstanceDO.getSts());
        if (!TmplStsEnum.DRAFT.getCode().equals(templateInstanceDO.getSts()) && !TmplStsEnum.START.getCode().equals(templateInstanceDO.getSts())) {
            throw exception(STATUS_OPERATION_FAIL);
        }
        TemplateInstanceDO newTpInstanceDO = BeanUtils.toBean(templateInstanceDO, TemplateInstanceDO.class);
        newTpInstanceDO.setId(null);
        newTpInstanceDO.setTenantId(templateInstanceDO.getTenantId());
        newTpInstanceDO.setVer(incrementVersion(templateInstanceDO.getVer()));
        newTpInstanceDO.setPublishTime(LocalDateTime.now());
        newTpInstanceDO.setOrigCntt(templateInstanceDO.getCntt() != null ? templateInstanceDO.getCntt() : templateInstanceDO.getOrigCntt());//模板实例内容,默认为上一个版本的当前文件内容
        newTpInstanceDO.setCreateTime(null);
        newTpInstanceDO.setUpdateTime(null);
        templateInstanceMapper.insert(newTpInstanceDO);
        log.info("创建模版实例【{}】成功", newTpInstanceDO);
        templateInstanceMapper.update(new LambdaUpdateWrapper<TemplateInstanceDO>()
                .set(TemplateInstanceDO::getSts, TmplStsEnum.STOPPED.getCode())
                .eq(TemplateInstanceDO::getId, id));
        log.info("更新模版实例【{}】状态状态为【STOP】成功", id);
        List<TemplateInstanceDataDO> templateInstanceDataDOS = new ArrayList<>();
        List<TemplateInstanceItemDO> templateInstanceItemDOS = new ArrayList<>();
        List<DepartmentInstanceRelativityDO> newDepartmentInstanceRelativityDOS = new ArrayList<>();
        //设置部门
        List<DepartmentInstanceRelativityDO> departmentInstanceRelativityDOS = departmentInstanceRelativityMapper
                .selectList(new LambdaQueryWrapper<DepartmentInstanceRelativityDO>()
                        .eq(DepartmentInstanceRelativityDO::getTemplateInstanceId, id));
        departmentInstanceRelativityDOS.forEach(departmentInstanceRelativityDO -> {
            DepartmentInstanceRelativityDO newDepartmentInstanceRelativityDO = new DepartmentInstanceRelativityDO();
            newDepartmentInstanceRelativityDO.setTemplateInstanceId(String.valueOf(newTpInstanceDO.getId()));
            newDepartmentInstanceRelativityDO.setCompanyDepartmentId(departmentInstanceRelativityDO.getCompanyDepartmentId());
            newDepartmentInstanceRelativityDOS.add(newDepartmentInstanceRelativityDO);
        });
        //设置条款
        templateInstanceItemMapper.selectList(new LambdaQueryWrapper<TemplateInstanceItemDO>()
                .eq(TemplateInstanceItemDO::getInscId, id)).forEach(templateInstanceItemDO -> {
            TemplateInstanceItemDO newTemplateInstanceItemDO = new TemplateInstanceItemDO();
            newTemplateInstanceItemDO.setInscId(String.valueOf(newTpInstanceDO.getId()));
            newTemplateInstanceItemDO.setItmId(templateInstanceItemDO.getItmId());
            newTemplateInstanceItemDO.setVal(templateInstanceItemDO.getVal());
            templateInstanceItemDOS.add(newTemplateInstanceItemDO);
        });
        //设置实例字段
        templateInstanceDataMapper.selectList(new LambdaQueryWrapper<TemplateInstanceDataDO>()
                .eq(TemplateInstanceDataDO::getInscId, id)).forEach(templateInstanceDataDO -> {
            TemplateInstanceDataDO newTemplateInstanceDataDO = new TemplateInstanceDataDO();
            newTemplateInstanceDataDO.setInscId(String.valueOf(newTpInstanceDO.getId()));
            newTemplateInstanceDataDO.setFldKy(templateInstanceDataDO.getFldKy());
            newTemplateInstanceDataDO.setFldVal(templateInstanceDataDO.getFldVal());
            templateInstanceDataDOS.add(newTemplateInstanceDataDO);
        });
        templateInstanceDataMapper.insertBatch(templateInstanceDataDOS);
        log.info("==================实例字段插入成功,共插入【{}】条记录==================", templateInstanceDataDOS.size());
        templateInstanceItemMapper.insertBatch(templateInstanceItemDOS);
        log.info("==================条款插入成功,共插入【{}】条记录==================", templateInstanceItemDOS.size());
        departmentInstanceRelativityMapper.insertBatch(newDepartmentInstanceRelativityDOS);
        log.info("==================部门实例关系插入成功,共插入【{}】条记录==================", newDepartmentInstanceRelativityDOS.size());
        TemplateInstanceRespVO templateInstanceRespVO = BeanUtils.toBean(newTpInstanceDO, TemplateInstanceRespVO.class);
        log.info("==================模板实例插入成功==================");
        getDetailedInfo(templateInstanceRespVO);
        return templateInstanceRespVO;
    }

    @Override
    public Map<String, Object> getVersion(String id) {
        validateTemplateInstanceExists(Long.valueOf(id));
        String ver = templateInstanceMapper.selectById(id).getVer();
        String newVer = incrementVersion(ver);
        return Map.of("version", ver, "newVersion", newVer);
    }

    @Override
    public List<TemplateInstanceRespVO> listByCdg(String cdg) {
        List<TemplateInstanceDO> templateInstanceDOS = templateInstanceMapper.selectList(
                new LambdaQueryWrapper<TemplateInstanceDO>()
                        .eq(TemplateInstanceDO::getCdg, cdg)
                        .eq(TemplateInstanceDO::getCompanyId, CompanyContextHolder.getCompanyId())
                        .orderByDesc(TemplateInstanceDO::getPublishTime)
                        .orderByDesc(TemplateInstanceDO::getCreateTime)
        );
        List<TemplateInstanceRespVO> templateInstanceRespVOS = BeanUtils.toBean(templateInstanceDOS, TemplateInstanceRespVO.class);
        templateInstanceRespVOS.forEach(this::getDetailedInfo);
        return templateInstanceRespVOS;
    }


    @Override
    public void getDetailedInfo(TemplateInstanceRespVO templateInstanceRespVO) {
        templateInstanceRespVO.setDeptIds(getDeptByInstanId(templateInstanceRespVO.getId())); //  部门
        templateInstanceRespVO.setInstanceItemRespVOS(setInstanceItemRespVOS(templateInstanceRespVO.getId())); // 条款
        templateInstanceRespVO.setTemplateInstanceDataRespVOS(setTemplateInstanceDataRespVOS(templateInstanceRespVO.getId())); // 实例字段
        if (!templateInstanceRespVO.getDeptIds().isEmpty()) {
            templateInstanceRespVO.setDeptRespVOS(deptApi.getDeptList(templateInstanceRespVO.getDeptIds().stream().map(Long::valueOf).toList()).getData()); // 部门详情
        }
        TmplTpDO tmplTp = tmplTpService.getTmplTp(templateInstanceRespVO.getTpId());
        if (tmplTp != null) {
            templateInstanceRespVO.setTpName(!tmplTp.getName().isEmpty() ? tmplTp.getName() : "分类未命名");
        }

    }

    @Override
    public void updateTemplateInstanceFileUrlByInstanceId(String id, String params) {
        validateTemplateInstanceExists(Long.valueOf(id));
        LambdaUpdateWrapper<TemplateInstanceDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TemplateInstanceDO::getId, id).set(TemplateInstanceDO::getCntt, params);
        templateInstanceMapper.update(updateWrapper);
        log.info("==================模板实例文件对象信息更新成功，文件对象信息为【{}】==================", params);
    }

    // 实例条款值
    private List<TemplateInstanceItemRespVO> setInstanceItemRespVOS(Long id) {
        List<TemplateInstanceItemDO> templateInstanceItemDOS = templateInstanceItemMapper.selectList(new LambdaQueryWrapper<TemplateInstanceItemDO>()
                .eq(TemplateInstanceItemDO::getInscId, id)
                .eq(TemplateInstanceItemDO::getCompanyId, CompanyContextHolder.getCompanyId()));
        List<TemplateInstanceItemRespVO> templateInstanceItemRespVOS = BeanUtils.toBean(templateInstanceItemDOS, TemplateInstanceItemRespVO.class);
        TmplItmMapper tmplItmMapper = SpringUtil.getBean(TmplItmMapper.class);
        List<String> ids = templateInstanceItemRespVOS.stream().map(TemplateInstanceItemRespVO::getItmId).toList();
        if (ids.isEmpty()) {
            return templateInstanceItemRespVOS;
        }
        List<TmplItmDO> tmplItmDOS = tmplItmMapper.selectByIds(ids);
        tmplItmDOS.forEach(tmplItmDO -> {
            templateInstanceItemRespVOS.forEach(templateInstanceItemRespVO -> {
                if (templateInstanceItemRespVO.getItmId().equals(tmplItmDO.getId())) {
                    templateInstanceItemRespVO.setItmName(tmplItmDO.getItmName());
                    templateInstanceItemRespVO.setItmNum(tmplItmDO.getItmNum());
                    templateInstanceItemRespVO.setVal(tmplItmDO.getItmVal());
                }
            });
        });
        return templateInstanceItemRespVOS;
    }

    // 实例数据
    private List<TemplateInstanceDataRespVO> setTemplateInstanceDataRespVOS(Long id) {
        List<TemplateInstanceDataRespVO> templateInstanceDataRespVOS = BeanUtils.toBean(templateInstanceDataMapper.selectList(new LambdaQueryWrapper<TemplateInstanceDataDO>()
                .eq(TemplateInstanceDataDO::getInscId, id)
                .eq(TemplateInstanceDataDO::getCompanyId, CompanyContextHolder.getCompanyId())), TemplateInstanceDataRespVO.class);
        List<TmplTpFldDO> tmplTpListByValKeys = tmplTpFldService.getTmplTpListByValKeys(templateInstanceDataRespVOS.stream().map(TemplateInstanceDataRespVO::getFldKy).toList());
        templateInstanceDataRespVOS.forEach(templateInstanceDataRespVO -> {
            tmplTpListByValKeys.forEach(tmplTpFldDO -> {
                if (templateInstanceDataRespVO.getFldKy().equals(tmplTpFldDO.getFldKy())) {
                    templateInstanceDataRespVO.setFldName(tmplTpFldDO.getFldName());
                    templateInstanceDataRespVO.setFldDoc(tmplTpFldDO.getFldDoc());
                    templateInstanceDataRespVO.setIsMust(tmplTpFldDO.getIsMust());
                }
            });
        });
        return templateInstanceDataRespVOS;
    }

    private void validateStatusCanDelete(List<Long> ids) {
        Set<String> sts = templateInstanceMapper.selectByIds(ids).stream().map(TemplateInstanceDO::getSts).collect(Collectors.toSet());
        sts.forEach(status -> {
            DeleteStatusEnum deleteStatusEnum = DeleteStatusEnum.fromCode(status);
            boolean transitionAllowed = false;
            if (deleteStatusEnum != null) {
                transitionAllowed = deleteStatusEnum.isTransitionAllowed(TmplStsEnum.DRAFT.getCode());
                if (!transitionAllowed) {
                    transitionAllowed = deleteStatusEnum.isTransitionAllowed(TmplStsEnum.STOPPED.getCode());
                }
            }
            if (!transitionAllowed) {
                throw exception(STATUS_OPERATION_FAIL);
            }
        });
    }

    private void validateStatusCanDelete(Long id) {
        String sts = templateInstanceMapper.selectById(id).getSts();
        DeleteStatusEnum deleteStatusEnum = DeleteStatusEnum.fromCode(sts);
        boolean transitionAllowed = false;
        if (deleteStatusEnum != null) {
            transitionAllowed = deleteStatusEnum.isTransitionAllowed(TmplStsEnum.DRAFT.getCode());
        }
        if (!transitionAllowed) {
            throw exception(STATUS_OPERATION_FAIL);
        }
    }

    private void validateStatusCanUpdate(Long id) {
        String sts = templateInstanceMapper.selectById(id).getSts();
        UpdateStatusEnum updateStatusEnum = UpdateStatusEnum.fromCode(sts);
        boolean transitionAllowed = false;
        if (updateStatusEnum != null) {
            transitionAllowed = updateStatusEnum.isTransitionAllowed(sts);
        }
        if (!transitionAllowed) {
            throw exception(STATUS_OPERATION_FAIL);
        }
    }

    private String getCdg() {
        String cdg = "TP" + DateUtils.format(new Date(), "yyyyMMddHHmmssSSS") + RandomUtil.randomNumbers(4);
        log.info("==================模板实例编号生成成功，模板实例编号为【{}】==================", cdg);
        return cdg;
    }

    @Override
    public FieldAndClauseRespVO getFieldAndClauseDetail(String id) {
        FieldAndClauseRespVO fieldAndClauseRespVO = new FieldAndClauseRespVO();
        //查询关联的实例模版字段
        List<String> valKeys = templateInstanceDataMapper.selectList(new LambdaQueryWrapper<TemplateInstanceDataDO>().eq(TemplateInstanceDataDO::getInscId, id)).stream().map(TemplateInstanceDataDO::getFldKy).distinct().toList();
        //查询关联的实例模版条款
        List<String> itmIds = templateInstanceItemMapper.selectList(new LambdaQueryWrapper<TemplateInstanceItemDO>().eq(TemplateInstanceItemDO::getInscId, id)).stream().map(TemplateInstanceItemDO::getItmId).toList();

        // 例模版条款去条款库查询条款信息
        if (!itmIds.isEmpty()) {
            List<TmplItmRespVO> tmplItmRespVOS = BeanUtils.toBean(tmplItmService.listTmplItmByIds(itmIds), TmplItmRespVO.class);
            fieldAndClauseRespVO.setTmplItmRespVOS(BeanUtils.toBean(tmplItmRespVOS, TmplItmRespVO.class));
        }
        if (!valKeys.isEmpty()) {
            //例模版字段去字段库查询字段信息
            List<TmplTpFldDO> tmplTpListByValKeys = tmplTpFldService.getTmplTpListByValKeys(valKeys);
            fieldAndClauseRespVO.setTmplFldRespVOS(BeanUtils.toBean(tmplTpListByValKeys, TmplFldRespVO.class));
        }

        return fieldAndClauseRespVO;
    }

    @Override
    public TemplateInstanceRespVO getTemplateInstance(String id) {
        return BeanUtils.toBean(templateInstanceMapper.selectById(id), TemplateInstanceRespVO.class);
    }

}
