package cn.iocoder.yudao.module.system.service.worklog;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.system.controller.admin.worklog.vo.form.LogFormCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.worklog.vo.form.LogFormPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.worklog.vo.form.LogFormRuleVO;
import cn.iocoder.yudao.module.system.controller.admin.worklog.vo.form.LogFormUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.worklog.LogFormConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.worklog.LogFormDO;
import cn.iocoder.yudao.module.system.dal.dataobject.worklog.LogRuleDO;
import cn.iocoder.yudao.module.system.dal.mysql.worklog.LogFormMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.system.service.worklog.dto.LogFormFieldRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 动态表单 Service 实现类
 *
 * @author 风里雾里
 */
@Service
@Validated
public class LogFormServiceImpl implements LogFormService {

    @Resource
    private LogFormMapper formMapper;
    @Resource
    private LogRuleService logRuleService;

    @Resource
    private LogUseService logUseService;

    @Override
    public Long createForm(LogFormCreateReqVO createReqVO) {
        this.checkFields(createReqVO.getFields());
        // 插入
        LogFormDO form = LogFormConvert.INSTANCE.convert(createReqVO);
        formMapper.insert(form);
        // 返回
        return form.getId();
    }

    @Override
    public void updateForm(LogFormUpdateReqVO updateReqVO) {
        this.checkFields(updateReqVO.getFields());
        // 校验存在
        this.validateFormExists(updateReqVO.getId());
        // 更新
        LogFormDO updateObj = LogFormConvert.INSTANCE.convert(updateReqVO);
        formMapper.updateById(updateObj);
    }

    @Override
    public void deleteForm(Long id) {
        // 校验存在
        this.validateFormExists(id);
        // 删除
        formMapper.deleteById(id);

        //同步删除规则
        logRuleService.deleteLogRuleByFormId(id);

        //同步删除模板使用者
        logUseService.deletByFormId(id);
    }

    private void validateFormExists(Long id) {
        if (formMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.FORM_NOT_EXISTS);
        }
    }

    @Override
    public LogFormDO getForm(Long id) {
        return formMapper.selectById(id);
    }

    @Override
    public List<LogFormDO> getFormList() {
        return formMapper.selectList();
    }

    @Override
    public List<LogFormDO> getFormList(Collection<Long> ids) {
        return formMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<LogFormDO> getFormPage(LogFormPageReqVO pageReqVO) {
        return formMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<LogFormDO> getFormPageByRule(LogFormPageReqVO pageReqVO) {

        List<Long> formIds = logUseService.getFormIdByUserId(getLoginUserId());
        if (formIds.isEmpty()) {

            return null;
        }
        return formMapper.selectPageByRule(pageReqVO, formIds);
    }

    @Override
    public List<LogFormRuleVO> getLogFormRuleList() {
        //查询模版
        List<LogFormDO> formList = formMapper.selectList(new LambdaQueryWrapper<LogFormDO>()
                .eq(LogFormDO::getStatus, 0)
                .isNotNull(LogFormDO::getRuleId)
        );
        List<Long> ruleIds = formList.stream().map(LogFormDO::getRuleId).collect(Collectors.toList());
        List<LogRuleDO> logRuleDOS = new ArrayList<>();
        Map<Long, LogRuleDO> ruleMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(ruleIds)) {
            logRuleDOS = logRuleService.getLogRuleByIds(ruleIds);
            ruleMap = logRuleDOS.stream().collect(Collectors.toMap(LogRuleDO::getId, v -> v));
        }
        List<LogFormRuleVO> list = new ArrayList<>();
        for (LogFormDO logFormDO : formList) {
            LogFormRuleVO vo = new LogFormRuleVO();
            vo.setFormDO(logFormDO);
            vo.setRuleDO(ruleMap.get(logFormDO.getRuleId()));
            list.add(vo);
        }
        return list;
    }

    /**
     * 校验 Field，避免 field 重复
     *
     * @param fields field 数组
     */
    private void checkFields(List<String> fields) {
        if (true) { // TODO 芋艿：兼容 Vue3 工作流：因为采用了新的表单设计器，所以暂时不校验
            return;
        }
        Map<String, String> fieldMap = new HashMap<>(); // key 是 vModel，value 是 label
        for (String field : fields) {
            LogFormFieldRespDTO fieldDTO = JsonUtils.parseObject(field, LogFormFieldRespDTO.class);
            Assert.notNull(fieldDTO);
            String oldLabel = fieldMap.put(fieldDTO.getVModel(), fieldDTO.getLabel());
            // 如果不存在，则直接返回
            if (oldLabel == null) {
                continue;
            }
            // 如果存在，则报错
            throw exception(ErrorCodeConstants.FORM_FIELD_REPEAT, oldLabel, fieldDTO.getLabel(), fieldDTO.getVModel());
        }
    }
}