package com.njcn.bpm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.bpm.enums.BpmResponseEnum;
import com.njcn.bpm.mapper.BpmFormMapper;
import com.njcn.bpm.pojo.param.BpmFormParam;
import com.njcn.bpm.pojo.po.BpmForm;
import com.njcn.bpm.pojo.vo.BpmFormVO;
import com.njcn.bpm.service.IBpmFormService;
import com.njcn.bpm.utils.BeanUtils;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.web.factory.PageFactory;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.*;


/**
 * 动态表单 Service 实现类
 *
 * @author 风里雾里
 */
@Service
@Validated
public class BpmFormServiceImpl extends ServiceImpl<BpmFormMapper, BpmForm> implements IBpmFormService {

    @Override
    public Page<BpmFormVO> getFormPage(BpmFormParam.BpmFormQueryParam bpmFormQueryParam) {
        QueryWrapper<BpmFormVO> bpmFormVOQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(bpmFormQueryParam.getName())) {
            bpmFormVOQueryWrapper.like("bpm_form.name", bpmFormQueryParam.getName());
        }
        bpmFormVOQueryWrapper.eq("bpm_form.state", DataStateEnum.ENABLE.getCode());
        bpmFormVOQueryWrapper.orderByDesc("bpm_form.update_time");
        bpmFormVOQueryWrapper.orderByAsc("bpm_form.sort");
        return this.baseMapper.page(new Page<>(PageFactory.getPageNum(bpmFormQueryParam), PageFactory.getPageSize(bpmFormQueryParam)), bpmFormVOQueryWrapper);
    }


    @Override
    public String createForm(BpmFormParam bpmFormParam) {
        checkFormName(bpmFormParam, false);
        // 插入
        BpmForm form = BeanUtils.toBean(bpmFormParam, BpmForm.class);
        this.baseMapper.insert(form);
        // 返回
        return form.getId();
    }

    private void checkFormName(BpmFormParam bpmFormParam, boolean isExcludeSelf) {
        LambdaQueryWrapper<BpmForm> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断流程表单的名称
        categoryLambdaQueryWrapper
                .eq(BpmForm::getName, bpmFormParam.getName())
                .eq(BpmForm::getState, DataStateEnum.ENABLE.getCode());
        //更新的时候，需排除当前记录
        if (isExcludeSelf) {
            if (bpmFormParam instanceof BpmFormParam.BpmFormUpdateParam) {
                categoryLambdaQueryWrapper.ne(BpmForm::getId, ((BpmFormParam.BpmFormUpdateParam) bpmFormParam).getId());
            }
        }
        int nameCountByAccount = this.count(categoryLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (nameCountByAccount >= 1) {
            throw new BusinessException(BpmResponseEnum.REPEAT_NAME_FORM);
        }
    }

    @Override
    public void updateForm(BpmFormParam.BpmFormUpdateParam updateParam) {
        checkFormName(updateParam, true);
        BpmForm updateObj = BeanUtils.toBean(updateParam, BpmForm.class);
        this.updateById(updateObj);
    }

    @Override
    public void deleteForm(List<String> ids) {
        this.lambdaUpdate().set(BpmForm::getState, DataStateEnum.DELETED.getCode())
                .in(BpmForm::getId, ids)
                .update();
    }


    @Override
    public List<BpmForm> getFormList() {
        LambdaQueryWrapper<BpmForm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(BpmForm::getId,BpmForm::getName)
                .eq(BpmForm::getState,DataStateEnum.ENABLE.getCode());
        return this.baseMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<BpmForm> getFormList(Collection<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return this.baseMapper.selectBatchIds(ids);
    }



    /**
     * 校验 Field，避免 field 重复
     *
     * @param fields field 数组
     */
    private void validateFields(List<String> fields) {
        // TODO 芋艿：兼容 Vue3 工作流：因为采用了新的表单设计器，所以暂时不校验
        if (true) {
            return;
        }
//        Map<String, String> fieldMap = new HashMap<>(); // key 是 vModel，value 是 label
//        for (String field : fields) {
//            BpmFormFieldRespDTO fieldDTO = JsonUtils.parseObject(field, BpmFormFieldRespDTO.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());
//        }
    }

}
