package cn.iocoder.yudao.module.mes.service.planmaintenance;

import cn.iocoder.yudao.module.mes.dal.dataobject.dvsubject.DvSubjectDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.subjectplan.SubjectPlanDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.taskmanagement.TaskManagementDO;
import cn.iocoder.yudao.module.mes.dal.mysql.dvsubject.DvSubjectMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.subjectplan.SubjectPlanMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.taskmanagement.TaskManagementMapper;
import cn.iocoder.yudao.module.mes.service.subjectplan.SubjectPlanService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.mes.controller.admin.planmaintenance.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.planmaintenance.PlanMaintenanceDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.mes.dal.mysql.planmaintenance.PlanMaintenanceMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.*;

/**
 * 方案维护 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class PlanMaintenanceServiceImpl implements PlanMaintenanceService {

    @Resource
    private PlanMaintenanceMapper planMaintenanceMapper;
    @Resource
    private SubjectPlanMapper subjectPlanMapper;

    @Resource
    private DvSubjectMapper dvSubjectMapper;

    @Resource
    private TaskManagementMapper taskManagementMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPlanMaintenance(PlanMaintenanceSaveReqVO createReqVO) {
        // 插入
        PlanMaintenanceDO planMaintenance = BeanUtils.toBean(createReqVO, PlanMaintenanceDO.class);
        planMaintenanceMapper.insert(planMaintenance);

        if (StringUtils.isNotBlank(createReqVO.getSubjectIdS())){

            // 将逗号分隔的字符串转换为Long类型的List
            List<Long> idList = Arrays.stream( createReqVO.getSubjectIdS().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());


            //插入关联表
            insertSubjectPlan(planMaintenance.getId(),idList);
        }
        // 返回
        return planMaintenance.getId();
    }

    private void insertSubjectPlan(Long id, List<Long> idList) {

        List<SubjectPlanDO> subjectPlanDOArrayList = new ArrayList<>();
        for (Long subjectId : idList) {
            SubjectPlanDO subjectPlanDO = new SubjectPlanDO();
            subjectPlanDO.setPlanId(id);
            subjectPlanDO.setSubjectId(subjectId);
            subjectPlanDOArrayList.add(subjectPlanDO);
        }
        subjectPlanMapper.insertBatch(subjectPlanDOArrayList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePlanMaintenance(PlanMaintenanceSaveReqVO updateReqVO) {
        // 校验存在
        validatePlanMaintenanceExists(updateReqVO.getId());
        // 更新
        PlanMaintenanceDO updateObj = BeanUtils.toBean(updateReqVO, PlanMaintenanceDO.class);
        planMaintenanceMapper.updateById(updateObj);


        if (StringUtils.isNotBlank(updateReqVO.getSubjectIdS())) {
            // 将逗号分隔的字符串转换为Long类型的List
            List<Long> idList = Arrays.stream( updateReqVO.getSubjectIdS().split(","))
                    .map(String::trim) // 去除可能存在的空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            //更新关联表
            updateSubjectPlan(updateObj.getId(),idList);
        }
    }

    private void updateSubjectPlan(Long id, List<Long> idList) {

        subjectPlanMapper.deleteByPlanId(id);
        List<SubjectPlanDO> subjectPlanDOArrayList = new ArrayList<>();
        for (Long subjectId : idList) {
            SubjectPlanDO subjectPlanDO = new SubjectPlanDO();
            subjectPlanDO.setPlanId(id);
            subjectPlanDO.setSubjectId(subjectId);
            subjectPlanDOArrayList.add(subjectPlanDO);
        }
        subjectPlanMapper.insertBatch(subjectPlanDOArrayList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePlanMaintenance(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }

        // 批量校验存在性
        List<PlanMaintenanceDO> existList = planMaintenanceMapper.selectBatchIds(idList);
        if (existList.size() != idList.size()) {
            throw exception(PLAN_MAINTENANCE_NOT_EXISTS);
        }

        // 批量校验引用
        validateBatchReferences(idList);

        // 删除主表
        planMaintenanceMapper.deleteByIds(idList);

        // 删除关联表数据
        deleteSubjectPlan(idList);
    }

    private void validateBatchReferences(List<Long> idList) {
        boolean exists = taskManagementMapper.exists(
                Wrappers.<TaskManagementDO>lambdaQuery()
                        .in(TaskManagementDO::getProjectForm, idList)
        );

        if (exists) {
            throw exception(PLAN_MAINTENANCE_REFERENCES);
        }
    }

    private void deleteSubjectPlan(List<Long> idList) {
        for (Long id : idList) {
            if (id != null ){
                subjectPlanMapper.delete(Wrappers.<SubjectPlanDO>lambdaQuery()
                        .eq(SubjectPlanDO::getPlanId, id));
            }
        }

    }

    private void validatePlanMaintenanceExists(Long id) {
        if (planMaintenanceMapper.selectById(id) == null) {
            throw exception(PLAN_MAINTENANCE_NOT_EXISTS);
        }
    }

    @Override
    public PlanMaintenanceDO getPlanMaintenance(Long id) {
        return planMaintenanceMapper.selectById(id);
    }

    @Override
    public PageResult<PlanMaintenanceDO> getPlanMaintenancePage(PlanMaintenancePageReqVO pageReqVO) {
        PageResult<PlanMaintenanceDO> planMaintenanceDOPageResult = planMaintenanceMapper.selectPage(pageReqVO);
        for (PlanMaintenanceDO planMaintenanceDO : planMaintenanceDOPageResult.getList()) {
            List<Long> ids = new ArrayList<>();
            List<SubjectPlanDO> subjectPlanDOList = subjectPlanMapper.selectList(Wrappers.<SubjectPlanDO>lambdaQuery()
                    .eq(SubjectPlanDO::getPlanId, planMaintenanceDO.getId()));
            for (SubjectPlanDO subjectPlanDO : subjectPlanDOList) {
                ids.add(subjectPlanDO.getSubjectId());
            }
            planMaintenanceDO.setSubjectIds(ids);
        }


        return planMaintenanceDOPageResult;
    }

    @Override
    public List<DvSubjectDO> getSubjectList(Long id) {
        if (id == null ){
            throw exception(SUBJECT_ID_NOT_EXISTS);
        }
        //查询对应的设备列表
        List<DvSubjectDO> dvSubjectDOList = new ArrayList<>();
        List<SubjectPlanDO> subjectPlanDOList = subjectPlanMapper.selectList(Wrappers.<SubjectPlanDO>lambdaQuery()
                .eq(SubjectPlanDO::getPlanId, id));
        for (SubjectPlanDO subjectPlanDO : subjectPlanDOList) {
            DvSubjectDO dvSubjectDO = dvSubjectMapper.selectById(subjectPlanDO.getSubjectId());
            if (dvSubjectDO!=null){
                dvSubjectDOList.add(dvSubjectDO);
            }
        }

        return dvSubjectDOList;
    }

    @Override
    public List<PlanMaintenanceDO> getPlanMaintenanceList() {
        return planMaintenanceMapper.selectList();
    }

}