package com.ktg.iscs.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.core.domain.entity.SysDictData;
import com.ktg.common.utils.DictUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.common.utils.bean.BeanUtils;
import com.ktg.iscs.domain.IsMachinery;
import com.ktg.iscs.domain.IsMachineryPoints;
import com.ktg.iscs.domain.IsSop;
import com.ktg.iscs.domain.dto.machinery.IsMachineryDTO;
import com.ktg.iscs.domain.vo.machinery.IsMachineryVO;
import com.ktg.iscs.mapper.IsMachineryMapper;
import com.ktg.iscs.service.IIsMachineryPointsService;
import com.ktg.iscs.service.IIsMachineryService;
import com.ktg.iscs.service.IIsSopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 设备工艺Service业务层处理
 *
 * @author cgj
 * @date 2024-12-19
 */
@Service
public class IsMachineryServiceImpl extends ServiceImpl<IsMachineryMapper, IsMachinery> implements IIsMachineryService {

    @Autowired
    private IsMachineryMapper isMachineryMapper;
    @Autowired
    private IIsMachineryPointsService iIsMachineryPointsService;
    @Autowired
    private IIsSopService iIsSopService;

    @Override
    public Page<IsMachineryVO> getIsMachineryPage(Page<IsMachinery> page, IsMachinery isMachinery) {
        Page<IsMachineryVO> isMachineryPage = isMachineryMapper.getIsMachineryPage(page, isMachinery);
        if (!isMachineryPage.getRecords().isEmpty()) {
            List<Long> machineryIds = isMachineryPage.getRecords().stream().map(IsMachineryVO::getMachineryId).collect(Collectors.toList());
            List<IsSop> sops = iIsSopService.list(Wrappers.<IsSop>lambdaQuery().in(IsSop::getMachineryId, machineryIds));
            List<SysDictData> dictSopTypes = DictUtils.getDictCache("sop_type");
            for (IsMachineryVO record : isMachineryPage.getRecords()) {
                // 获取该工艺下面有哪些建立的sop类型
                List<String> sopTypes = sops.stream().filter(o -> o.getMachineryId().equals(record.getMachineryId()))
                        .map(IsSop::getSopType).collect(Collectors.toList());
                ArrayList<SysDictData> sysDictData = new ArrayList<>();
                if (!sopTypes.isEmpty()) {
                    // 如果工艺下面有sop，找到这些sop是哪些类型的，返回
                    for (String sopType : sopTypes) {
                        for (SysDictData dictSopType : dictSopTypes) {
                            if (sopType.equals(dictSopType.getDictValue())) {
                                sysDictData.add(dictSopType);
                            }
                        }
                    }
                }
                record.setSysDictDatas(sysDictData);
            }
        }
        return isMachineryPage;
    }

    @Transactional
    @Override
    public Boolean insertIsMachinery(IsMachinery isMachinery) {
        // 断言校验
        Assert.isTrue(StringUtils.isNotBlank(isMachinery.getMachineryName()), "名称不可为空!");
        Assert.notNull(isMachinery.getParentId(), "父id不可为空!");
        // 判断名称重复
        List<IsMachinery> list = list(Wrappers.<IsMachinery>lambdaQuery()
                .eq(IsMachinery::getMachineryName, isMachinery.getMachineryName()));
        Assert.isTrue(list.isEmpty(), "[" + isMachinery.getMachineryName() + "]名称已被工艺/设备使用，请重新填写！");
        IsMachinery one = getById(isMachinery.getParentId());
        String ancestors;
        if (one != null) {
            ancestors = one.getAncestors() + "," + isMachinery.getParentId();
        } else {
            ancestors = "0";
        }
        isMachinery.setAncestors(ancestors);
        save(isMachinery);
        return true;
    }

    @Override
    public Boolean updateIsMachinery(IsMachinery isMachinery) {
        // 断言校验
        Assert.notNull(isMachinery.getMachineryId(), "id不可为空!");
        Assert.isTrue(StringUtils.isNotBlank(isMachinery.getMachineryName()), "名称不可为空!");
        Assert.notNull(isMachinery.getParentId(), "父id不可为空!");
        // 判断名称重复
        List<IsMachinery> list = list(Wrappers.<IsMachinery>lambdaQuery()
                .eq(IsMachinery::getMachineryName, isMachinery.getMachineryName())
                .ne(IsMachinery::getMachineryId, isMachinery.getMachineryId()));
        Assert.isTrue(list.isEmpty(), "[" + isMachinery.getMachineryName() + "]名称已被工艺/设备使用，请重新填写！");
        IsMachinery one = getById(isMachinery.getParentId());
        String ancestors;
        if (one != null) {
            ancestors = one.getAncestors() + "," + isMachinery.getParentId();
        } else {
            ancestors = "0";
        }
        isMachinery.setAncestors(ancestors);
        update(Wrappers.<IsMachinery>lambdaUpdate()
                .eq(IsMachinery::getMachineryId, isMachinery.getMachineryId())
                .set(IsMachinery::getAncestors, isMachinery.getAncestors())
                .set(IsMachinery::getMachineryName, isMachinery.getMachineryName())
                .set(IsMachinery::getWorkstationId, isMachinery.getWorkstationId())
                .set(IsMachinery::getLotoId, isMachinery.getLotoId())
                .set(IsMachinery::getRemark, isMachinery.getRemark())
                .set(IsMachinery::getMachineryImg, StringUtils.isBlank(isMachinery.getMachineryImg()) ? null : isMachinery.getMachineryImg()));
        return true;
    }

    @Override
    public Boolean saveMachineryPoints(IsMachineryDTO dto) {
        // 断言校验
        Assert.notNull(dto.getMachineryId(), "id不可为空!");
        Assert.isFalse(dto.getPointIdList().isEmpty(), "请选择隔离点!");
        // 开始存储工艺和隔离点的关联关系
        iIsMachineryPointsService.remove(Wrappers.<IsMachineryPoints>lambdaQuery()
                .eq(IsMachineryPoints::getMachineryId, dto.getMachineryId()));
        List<IsMachineryPoints> isMachineryPoints = new ArrayList<>();
        for (Long pointId : dto.getPointIdList()) {
            IsMachineryPoints isMachineryPoint = new IsMachineryPoints();
            isMachineryPoint.setMachineryId(dto.getMachineryId());
            isMachineryPoint.setPointId(pointId);
            isMachineryPoints.add(isMachineryPoint);
            iIsMachineryPointsService.save(isMachineryPoint);
        }
        // iIsMachineryPointsService.saveBatch(isMachineryPoints);
        return true;
    }

    @Transactional
    @Override
    public Boolean deleteIsMachineryByMachineryIds(String machineryIds) {

        Assert.notBlank(machineryIds, "请选择需要删除的数据!");
        Long[] longIds = Convert.toLongArray(machineryIds);
        removeBatchByIds(Arrays.asList(longIds));
        // 移除关联的点位信息
        iIsMachineryPointsService.remove(Wrappers.<IsMachineryPoints>lambdaQuery()
                .in(IsMachineryPoints::getMachineryId, Arrays.asList(longIds)));
        return true;
    }

    @Override
    public IsMachineryVO selectIsMachineryById(Long machineryId) {
        Assert.notNull(machineryId, "id不可为空!");
        IsMachinery machinery = getById(machineryId);
        IsMachineryVO bean = BeanUtils.toBean(machinery, IsMachineryVO.class);
        // 查询关联的点位信息
        List<IsMachineryPoints> list = iIsMachineryPointsService.list(Wrappers.<IsMachineryPoints>lambdaQuery()
                .eq(IsMachineryPoints::getMachineryId, machineryId));
        if (!list.isEmpty()) {
            List<Long> collect = list.stream().map(IsMachineryPoints::getPointId).collect(Collectors.toList());
            bean.setPointIdList(collect);
        }
        return bean;
    }
}
