package org.jeecg.modules.workOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.workOrder.entity.WorkDivisionSet;
import org.jeecg.modules.workOrder.mapper.WorkDivisionSetMapper;
import org.jeecg.modules.workOrder.service.IWorkDivisionSetService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 派工预设
 * @Author: jeecg-boot
 * @Date:   2025-06-11
 * @Version: V1.0
 */
@Service
public class WorkDivisionSetServiceImpl extends ServiceImpl<WorkDivisionSetMapper, WorkDivisionSet> implements IWorkDivisionSetService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(WorkDivisionSet workDivisionSet) {
        if(workDivisionSet.getExecutorList().isEmpty()) {
            throw new RuntimeException("请选择派工人员!");
        }
//        if(workDivisionSet.getTorType() == 0 && baseMapper.selectCount(new LambdaQueryWrapper<WorkDivisionSet>()
//                .eq(WorkDivisionSet::getRegularId,workDivisionSet.getRegularId())
//                .eq(WorkDivisionSet::getTorType,0))>0L) {
//            throw new RuntimeException("此规程已配置过负责人");
//        }
        List<WorkDivisionSet> workDivisionSetList = workDivisionSet.getExecutorList().stream()
                .map(executor -> {
                    long count = baseMapper.selectCount(new LambdaQueryWrapper<WorkDivisionSet>()
                            .eq(WorkDivisionSet::getRegularId,workDivisionSet.getRegularId())
                            .eq(WorkDivisionSet::getTorType,executor.getTorType())
                            .eq(WorkDivisionSet::getExecutor,executor.getExecutor()));
                    if(count>0L) {
                        throw new RuntimeException("存在重复的人员配置，请检查数据或刷新缓存！");
                    }

                    WorkDivisionSet newSet = new WorkDivisionSet();
                    newSet.setRegularId(workDivisionSet.getRegularId());
                    newSet.setTorType(executor.getTorType());
                    newSet.setRemark(workDivisionSet.getRemark());
                    newSet.setExecutor(executor.getExecutor());
                    return newSet;
                }).collect(Collectors.toList());

        return this.saveBatch(workDivisionSetList);
    }
}
