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

import cn.iocoder.yudao.module.mes.dal.dataobject.moldsubject.MoldSubjectDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.subjectmoldplan.SubjectMoldPlanDO;
import cn.iocoder.yudao.module.mes.dal.mysql.moldsubject.MoldSubjectMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.subjectmoldplan.SubjectMoldPlanMapper;
import cn.iocoder.yudao.module.mes.service.moldplanmaintenance.MoldPlanMaintenanceService;
import cn.iocoder.yudao.module.mes.service.subjectmoldplan.SubjectMoldPlanService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.moldplanmaintenance.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.moldplanmaintenance.MoldPlanMaintenanceDO;
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.moldplanmaintenance.MoldPlanMaintenanceMapper;

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 MoldPlanMaintenanceServiceImpl implements MoldPlanMaintenanceService {

    @Resource
    private MoldPlanMaintenanceMapper moldplanMaintenanceMapper;
    @Resource
    private SubjectMoldPlanMapper subjectMoldPlanMapper;

    @Resource
    private MoldSubjectMapper moldSubjectMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createMoldPlanMaintenance(MoldPlanMaintenanceSaveReqVO createReqVO) {
        // 插入
        MoldPlanMaintenanceDO moldplanMaintenance = BeanUtils.toBean(createReqVO, MoldPlanMaintenanceDO.class);
        moldplanMaintenanceMapper.insert(moldplanMaintenance);

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

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


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

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

        List<SubjectMoldPlanDO> subjectMoldPlanDOArrayList = new ArrayList<>();
        for (Long subjectId : idList) {
            SubjectMoldPlanDO subjectMoldPlanDO = new SubjectMoldPlanDO();
            subjectMoldPlanDO.setPlanId(id);
            subjectMoldPlanDO.setSubjectId(subjectId);
            subjectMoldPlanDOArrayList.add(subjectMoldPlanDO);
        }
        subjectMoldPlanMapper.insertBatch(subjectMoldPlanDOArrayList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMoldPlanMaintenance(MoldPlanMaintenanceSaveReqVO updateReqVO) {
        // 校验存在
        validateMoldPlanMaintenanceExists(updateReqVO.getId());
        // 更新
        MoldPlanMaintenanceDO updateObj = BeanUtils.toBean(updateReqVO, MoldPlanMaintenanceDO.class);
        moldplanMaintenanceMapper.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());
            //更新关联表
            updateSubjectMoldPlan(updateObj.getId(),idList);
        }
    }

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

        subjectMoldPlanMapper.deleteByPlanId(id);
        List<SubjectMoldPlanDO> subjectMoldPlanDOArrayList = new ArrayList<>();
        for (Long subjectId : idList) {
            SubjectMoldPlanDO subjectMoldPlanDO = new SubjectMoldPlanDO();
            subjectMoldPlanDO.setPlanId(id);
            subjectMoldPlanDO.setSubjectId(subjectId);
            subjectMoldPlanDOArrayList.add(subjectMoldPlanDO);
        }
        subjectMoldPlanMapper.insertBatch(subjectMoldPlanDOArrayList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMoldPlanMaintenance( List<Long> idList) {
        for (Long id : idList) {
            // 校验存在
            validateMoldPlanMaintenanceExists(id);

        }
        // 删除
        moldplanMaintenanceMapper.deleteByIds(idList);
        //删除关联表数据
        deleteSubjectMoldPlan(idList);

    }

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

    }

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

    @Override
    public MoldPlanMaintenanceDO getMoldPlanMaintenance(Long id) {
        return moldplanMaintenanceMapper.selectById(id);
    }

    @Override
    public PageResult<MoldPlanMaintenanceDO> getMoldPlanMaintenancePage(MoldPlanMaintenancePageReqVO pageReqVO) {
        PageResult<MoldPlanMaintenanceDO> moldplanMaintenanceDOPageResult = moldplanMaintenanceMapper.selectPage(pageReqVO);
        for (MoldPlanMaintenanceDO moldplanMaintenanceDO : moldplanMaintenanceDOPageResult.getList()) {
            List<Long> ids = new ArrayList<>();
            List<SubjectMoldPlanDO> subjectMoldPlanDOList = subjectMoldPlanMapper.selectList(Wrappers.<SubjectMoldPlanDO>lambdaQuery()
                    .eq(SubjectMoldPlanDO::getPlanId, moldplanMaintenanceDO.getId()));
            for (SubjectMoldPlanDO subjectMoldPlanDO : subjectMoldPlanDOList) {
                ids.add(subjectMoldPlanDO.getSubjectId());
            }
            moldplanMaintenanceDO.setSubjectIds(ids);
        }


        return moldplanMaintenanceDOPageResult;
    }

    @Override
    public List<MoldSubjectDO> getSubjectList(Long id) {
        if (id == null ){
            throw exception(SUBJECT_ID_NOT_EXISTS);
        }
        //查询对应的设备列表
        List<MoldSubjectDO> moldSubjectDOList = new ArrayList<>();
        List<SubjectMoldPlanDO> subjectMoldPlanDOList = subjectMoldPlanMapper.selectList(Wrappers.<SubjectMoldPlanDO>lambdaQuery()
                .eq(SubjectMoldPlanDO::getPlanId, id));
        for (SubjectMoldPlanDO subjectMoldPlanDO : subjectMoldPlanDOList) {
            MoldSubjectDO moldSubjectDO = moldSubjectMapper.selectById(subjectMoldPlanDO.getSubjectId());
            if (moldSubjectDO!=null){
                moldSubjectDOList.add(moldSubjectDO);
            }
        }

        return moldSubjectDOList;
    }

}