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

import cn.iocoder.yudao.module.iot.controller.admin.device.vo.LineDeviceRespVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.devicemodel.DeviceModelDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.criticalcomponent.CriticalComponentDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.devicetype.DeviceTypeDO;
import cn.iocoder.yudao.module.mes.dal.mysql.criticalcomponent.CriticalComponentMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.deviceledger.DeviceLedgerMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.repairtems.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.repairtems.RepairTemsDO;
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.repairtems.RepairTemsMapper;

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

/**
 * 维修项目 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class RepairTemsServiceImpl implements RepairTemsService {

    @Resource
    private RepairTemsMapper repairTemsMapper;


    @Resource
    private DeviceLedgerMapper deviceLedgerMapper;
    @Resource
    private CriticalComponentMapper criticalComponentMapper;

    @Override
    public Long createRepairTems(RepairTemsSaveReqVO createReqVO) {
        //编码重复判断
        boolean exists = repairTemsMapper.exists(Wrappers.<RepairTemsDO>lambdaQuery()
                .eq(RepairTemsDO::getSubjectCode, createReqVO.getSubjectCode())
        );

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

        // 插入
        RepairTemsDO repairTems = BeanUtils.toBean(createReqVO, RepairTemsDO.class);
        repairTemsMapper.insert(repairTems);
        // 返回
        return repairTems.getId();
    }

    @Override
    public void updateRepairTems(RepairTemsSaveReqVO updateReqVO) {
        // 校验存在
        validateRepairTemsExists(updateReqVO.getId());

        //编码重复判断
        Long count = repairTemsMapper.selectCount(new LambdaQueryWrapper<RepairTemsDO>()
                .eq(RepairTemsDO::getSubjectCode, updateReqVO.getSubjectCode())
                .ne(RepairTemsDO::getId, updateReqVO.getId())

        );

        if (count > 0) {
            throw exception(REPAIR_TEMS_CODE_EXISTS);
        }

        // 更新
        RepairTemsDO updateObj = BeanUtils.toBean(updateReqVO, RepairTemsDO.class);
        repairTemsMapper.updateById(updateObj);
    }

    @Override
    public void deleteRepairTems( List<Long> idList) {
        for (Long id : idList) {
            // 校验存在
            validateRepairTemsExists(id);
        }

        // 删除
        repairTemsMapper.deleteByIds(idList);
    }

    private void validateRepairTemsExists(Long id) {
        if (repairTemsMapper.selectById(id) == null) {
            throw exception(REPAIR_TEMS_NOT_EXISTS);
        }
    }

    @Override
    public RepairTemsDO getRepairTems(Long id) {
        return repairTemsMapper.selectById(id);
    }

    @Override
    public PageResult<RepairTemsRespVO> getRepairTemsPage(RepairTemsPageReqVO pageReqVO) {
        Page<RepairTemsRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<RepairTemsRespVO> repairTemsDOIPage = repairTemsMapper.getRepairTemsPage(page,pageReqVO);
        PageResult<RepairTemsRespVO> repairTemsDOPageResult = new PageResult<>(repairTemsDOIPage.getRecords(), repairTemsDOIPage.getTotal());
        return repairTemsDOPageResult;
    }

    @Override
    public List<RepairTemsRespVO> getDeviceOrComponent(Integer deviceType) {
        return repairTemsMapper.getRepairTemsList(new RepairTemsPageReqVO().setDeviceType(deviceType));
    }

    @Override
    public List<RepairTemsRespVO> getDeviceOrComponentList(Long deviceId, Long componentId) {
        return repairTemsMapper.getRepairTemsList(new RepairTemsPageReqVO().setDeviceId(deviceId).setComponentId(componentId));
    }

    @Override
    public List<CriticalComponentDO> getComponentList(Long deviceId) {

        DeviceLedgerDO deviceLedgerDO = deviceLedgerMapper.selectById(deviceId);
        if(deviceLedgerDO == null ){
            throw exception(DEVICE_LEDGER_NOT_EXISTS);
        }

        if (StringUtils.isBlank(deviceLedgerDO.getComponentId())){
            return new ArrayList<>();
        }

        List<CriticalComponentDO> criticalComponentDOS= new ArrayList<>();
        List<Long> idList = Arrays.stream(deviceLedgerDO.getComponentId().split(","))
                .map(String::trim) // 去除可能存在的空格
                .map(Long::valueOf)
                .collect(Collectors.toList());

        for (Long id : idList) {
            CriticalComponentDO criticalComponentDO = criticalComponentMapper.selectById(id);
            if (criticalComponentDO !=null){
                criticalComponentDOS.add(criticalComponentDO);
            }
        }

        return criticalComponentDOS;
    }

}