package com.fs.audit.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.audit.domain.AuditTemp;
import com.fs.audit.dto.TemplateConfigDTO;
import com.fs.audit.dto.TemplateStepDTO;
import com.fs.audit.exception.BusinessException;
import com.fs.audit.mapper.AuditTempMapper;
import com.fs.audit.service.AuditTempService;
import com.fs.common.utils.DateUtils;
import com.fs.company.cache.CompanyCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 审核模板服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuditTempServiceImpl implements AuditTempService {

    private final AuditTempMapper auditTempMapper;

    @Override
    @Transactional
    public Long createTemplate(String tempName, String description, TemplateConfigDTO config) {
        // 验证配置
        validateTemplateConfig(config);

        AuditTemp auditTemp = new AuditTemp();
        auditTemp.setTempName(tempName);
        auditTemp.setTempJson(JSON.toJSONString(config));

        auditTempMapper.insert(auditTemp);

        log.info("创建审核模板成功，ID: {}, 名称: {}", auditTemp.getId(), tempName);
        return auditTemp.getId();
    }

    @Override
    public AuditTemp getTemplate(Long tempId) {
        AuditTemp template = auditTempMapper.selectById(tempId);
        if (template == null) {
            throw new BusinessException("模板不存在: " + tempId);
        }
        return template;
    }

    @Override
    public AuditTemp getTemplate(String tempCode, Long companyId) {
        LambdaQueryWrapper<AuditTemp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AuditTemp> last = lambdaQueryWrapper.eq(AuditTemp::getTempCode, tempCode)
                .eq(AuditTemp::getCompanyId, companyId);
        AuditTemp auditTemp = auditTempMapper.selectOne(last);
        if(auditTemp == null) {
            throw new BusinessException(String.format("模板代码 {} 公司: {} 不存在",tempCode,companyId));
        }
        return auditTemp;
    }

    @Override
    public TemplateConfigDTO parseTemplateConfig(String tempJson) {
        try {
            return JSON.parseObject(tempJson, TemplateConfigDTO.class);
        } catch (Exception e) {
            log.error("解析模板配置失败: {}", tempJson, e);
            throw new BusinessException("模板配置格式错误");
        }
    }

    @Override
    @Transactional
    public void updateTemplate(Long tempId, String tempName, String description, TemplateConfigDTO config) {
        AuditTemp template = getTemplate(tempId);

        // 验证配置
        validateTemplateConfig(config);

        template.setTempName(tempName);
        template.setTempJson(JSON.toJSONString(config));

        auditTempMapper.updateById(template);

        log.info("更新审核模板成功，ID: {}", tempId);
    }

    @Override
    @Transactional
    public void deleteTemplate(Long tempId) {
        auditTempMapper.deleteById(tempId);
        log.info("删除审核模板成功，ID: {}", tempId);
    }

    @Override
    public List<AuditTemp> selectAuditTempList(AuditTemp auditTemp) {

        List<AuditTemp> auditTemps = auditTempMapper.selectAuditTempList(auditTemp);
        for (AuditTemp temp : auditTemps) {
            if(ObjectUtils.isNotNull(temp.getCompanyId())){
                String companyName = CompanyCacheService.getCompanyNameById(temp.getCompanyId());
                if(ObjectUtils.isNotNull(companyName)){
                    temp.setCompanyName(companyName);
                }
            }
        }
        return auditTemps;
    }

    @Override
    public String selectAuditTempById(Long id) {
        return "";
    }

    @Override
    public int insertAuditTemp(AuditTemp auditTemp) {
        auditTemp.setCreateTime(LocalDateTime.now());
        return auditTempMapper.insertAuditTemp(auditTemp);
    }

    @Override
    public int updateAuditTemp(AuditTemp auditTemp) {
        auditTemp.setUpdateTime(LocalDateTime.now());
        return auditTempMapper.updateAuditTemp(auditTemp);
    }

    @Override
    public int deleteAuditTempByIds(Long[] ids) {
        return auditTempMapper.deleteAuditTempByIds(ids);
    }

    @Transactional
    @Override
    public int initAuditTemp(Long companyId) {
        // 参数校验
        if (companyId == null) {
            return 0;
        }
        AuditTemp auditTemp1 = new AuditTemp();
        auditTemp1.setCompanyId(companyId);
        List<AuditTemp> auditTemps = auditTempMapper.selectAuditTempList(auditTemp1);
        if(!auditTemps.isEmpty()){
            throw new BusinessException("该公司已有模板，请先清空该公司审核模板后在执行");
        }


        // 构建七条模板数据（auditUserIds 已改为空数组）
        List<AuditTemp> tempList = Arrays.asList(
                createAuditTemp(null, "服务单审核", "ADUIT_FWDSH", "{\"steps\":[{\"step\":1,\"auditUserIds\":[],\"description\":\"客服审核\"}]}", 2, 0, companyId),
                createAuditTemp(null, "服务单任务生成配置", "AUDIT_FWDRWSCPZ", "{\"steps\":[{\"step\":1,\"auditUserIds\":[],\"description\":\"客服审核\"}]}", 2, 0, companyId),
                createAuditTemp(null, "完成任务审核", "ADUIT_WCRWSH", "{\"steps\":[{\"step\":1,\"auditUserIds\":[],\"description\":\"客服审核\"}]}", 2, 0, companyId),
                createAuditTemp(null, "创建任务审核", "ADUIT_CJRW", "{\"steps\":[{\"step\":1,\"auditUserIds\":[],\"description\":\"客服审核\"}]}", 2, 0, companyId),
                createAuditTemp(null, "定级审核", "ADUIT_DJSH", "{\"steps\":[{\"step\":1,\"auditUserIds\":[],\"description\":\"客服审核\"}]}", 2, 0, companyId),
                createAuditTemp(null, "讲者审核", "ADUIT_JZSH", "{\"steps\":[{\"step\":1,\"auditUserIds\":[],\"description\":\"客服审核\"}]}", 2, 0, companyId),
                createAuditTemp(null, "提现审核", "ADUIT_TXSH", "{\"steps\":[{\"step\":1,\"auditUserIds\":[],\"description\":\"客服审核\"}]}", 2, 0, companyId)
        );

        // 循环插入并累加影响行数
        int insertedCount = 0;
        for (AuditTemp auditTemp : tempList) {
            insertedCount += auditTempMapper.insertAuditTemp(auditTemp);
        }
        return insertedCount;
    }

    /**
     * 验证模板配置
     */
    private void validateTemplateConfig(TemplateConfigDTO config) {
        if (config == null || config.getSteps() == null || config.getSteps().isEmpty()) {
            throw new BusinessException("模板配置不能为空，且必须包含至少一个步骤");
        }

        for (int i = 0; i < config.getSteps().size(); i++) {
            TemplateStepDTO step = config.getSteps().get(i);
            if (step.getStep() == null || step.getStep() != i + 1) {
                throw new BusinessException("步骤序号必须从1开始连续递增");
            }
            if (step.getAuditUserIds() == null || step.getAuditUserIds().isEmpty()) {
                throw new BusinessException("步骤" + step.getStep() + "的审核人列表不能为空");
            }
        }
    }

    /**
     * 辅助方法：构建 AuditTemp 对象
     */
    private AuditTemp createAuditTemp(Long id, String tempName, String tempCode, String tempJson,
                                      Integer status, Integer isDel, Long companyId) {
        AuditTemp auditTemp = new AuditTemp();
        auditTemp.setId(id);
        auditTemp.setTempName(tempName);
        auditTemp.setTempCode(tempCode);
        auditTemp.setTempJson(tempJson);
        auditTemp.setStatus(status);
        auditTemp.setIsDel(isDel);
        auditTemp.setCompanyId(companyId);
         auditTemp.setCreateTime(LocalDateTime.now());
         auditTemp.setUpdateTime(LocalDateTime.now());
        return auditTemp;
    }

}

