package com.ktg.iscs.service.impl;

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.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ktg.common.core.text.Convert;
import com.ktg.iscs.domain.IsJobTicketPoints;
import com.ktg.iscs.domain.IsSopPoints;
import com.ktg.iscs.domain.IsWorkarea;
import com.ktg.iscs.domain.vo.points.PointDetailVO;
import com.ktg.iscs.domain.vo.workarea.PageWorkareaVO;
import com.ktg.iscs.domain.vo.workarea.PointsMapVO;
import com.ktg.iscs.mapper.IsWorkareaMapper;
import com.ktg.iscs.service.IIsIsolationPointService;
import com.ktg.iscs.service.IIsJobTicketPointsService;
import com.ktg.iscs.service.IIsSopPointsService;
import com.ktg.iscs.service.IIsWorkareaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工作区域Service业务层处理
 *
 * @author cgj
 * @date 2024-10-18
 */
@Service
public class IsWorkareaServiceImpl extends ServiceImpl<IsWorkareaMapper, IsWorkarea> implements IIsWorkareaService
{
    @Autowired
    private IsWorkareaMapper isWorkareaMapper;
    @Autowired
    private IIsSopPointsService iIsSopPointsService;
    @Autowired
    private IIsIsolationPointService iIsIsolationPointService;
    @Autowired
    private IIsJobTicketPointsService iIsJobTicketPointsService;

    /**
     * 查询工作区域
     *
     * @param workareaId 工作区域主键
     * @return 工作区域
     */
    @Override
    public IsWorkarea selectIsWorkareaByWorkareaId(Long workareaId)
    {
        return isWorkareaMapper.selectIsWorkareaByWorkareaId(workareaId);
    }

    /**
     * 查询工作区域列表
     *
     * @param isWorkarea 工作区域
     * @return 工作区域
     */
    @Override
    public List<IsWorkarea> selectIsWorkareaList(IsWorkarea isWorkarea)
    {
        return isWorkareaMapper.selectIsWorkareaList(isWorkarea);
    }

    /**
     * 新增工作区域
     *
     * @param isWorkarea 工作区域
     * @return 结果
     */
    @Override
    public int insertIsWorkarea(IsWorkarea isWorkarea)
    {
        // 断言校验
        Assert.isTrue(StringUtils.isNotBlank(isWorkarea.getWorkareaName()), "区域名称不可为空!");
        Assert.isTrue(StringUtils.isNotBlank(isWorkarea.getWorkareaCode()), "区域编号名称不可为空!");
        List<IsWorkarea> list = list(Wrappers.<IsWorkarea>lambdaQuery()
                .eq(IsWorkarea::getWorkareaCode, isWorkarea.getWorkareaCode()));
        Assert.isTrue(list.isEmpty(), "该区域编号已被使用!");
        IsWorkarea one =getById(isWorkarea.getParentId());
        String ancestors;
        if (one != null) {
            ancestors = one.getAncestors() + "," + isWorkarea.getParentId();
        } else {
            ancestors = "0";
        }
        isWorkarea.setAncestors(ancestors);
        return isWorkareaMapper.insertIsWorkarea(isWorkarea);
    }

    /**
     * 修改工作区域
     *
     * @param isWorkarea 工作区域
     * @return 结果
     */
    @Override
    public int updateIsWorkarea(IsWorkarea isWorkarea)
    {
        // 断言校验
        Assert.notNull(isWorkarea.getWorkareaId(), "区域ID不可为空!");
        Assert.isTrue(StringUtils.isNotBlank(isWorkarea.getWorkareaName()), "区域名称不可为空!");
        Assert.isTrue(StringUtils.isNotBlank(isWorkarea.getWorkareaCode()), "区域编号名称不可为空!");
        // Assert.notNull(isWorkarea.getWorkshopId(), "所属车间不可为空!");
        List<IsWorkarea> list = list(Wrappers.<IsWorkarea>lambdaQuery()
                .eq(IsWorkarea::getWorkareaCode, isWorkarea.getWorkareaCode())
                .ne(IsWorkarea::getWorkareaId, isWorkarea.getWorkareaId()));
        Assert.isTrue(list.isEmpty(), "该区域编号已被使用!");
        isWorkarea.setUpdateTime(new Date());
        return isWorkareaMapper.updateIsWorkarea(isWorkarea);
    }

    /**
     * 批量删除工作区域
     *
     * @param workareaIds 需要删除的工作区域主键
     * @return 结果
     */
    @Override
    public int deleteIsWorkareaByWorkareaIds(String workareaIds)
    {
        Assert.notBlank(workareaIds, "请选择需要删除的数据!");
        Long[] longIds = Convert.toLongArray(workareaIds);
        // 1.判断下面有没有隔离点信息
        for (Long longId : longIds) {
            List<IsSopPoints> list = iIsSopPointsService.list(Wrappers.<IsSopPoints>lambdaQuery()
                    .eq(IsSopPoints::getWorkareaId, longId));
            if (!list.isEmpty()) {
                IsWorkarea byId = getById(longId);
                Assert.isTrue(false, byId.getWorkareaName() + "下有隔离点，暂不可删除！");
            }
        }
        return isWorkareaMapper.deleteIsWorkareaByWorkareaIds(longIds);
    }

    /**
     * 删除工作区域信息
     *
     * @param workareaId 工作区域主键
     * @return 结果
     */
    @Override
    public int deleteIsWorkareaByWorkareaId(Long workareaId)
    {
        return isWorkareaMapper.deleteIsWorkareaByWorkareaId(workareaId);
    }

    @Override
    public Page<PageWorkareaVO> getIsWorkareaPage(Page page, IsWorkarea dto) {
        return isWorkareaMapper.getIsWorkareaPage(page, dto);
    }

    @Override
    public List<PointsMapVO> selectIsWorkareaMapById(Long workareaId, Long sopId, Long ticketId) {
        // 1.断言校验
        Assert.notNull(workareaId, "请传入区域id");
        // 2.查询区域信息
        IsWorkarea workarea = getById(workareaId);
        // 3.解析map
        List<PointsMapVO> points = new ArrayList<>();
        if (workarea != null) {
            String map = workarea.getMap();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                points = objectMapper.readValue(map, new TypeReference<List<PointsMapVO>>(){});
                // 4.补充点位name,隔离点类型,危险能量类型
                List<Long> pointIds = points.stream().map(PointsMapVO::getPointId).collect(Collectors.toList());
                List<PointDetailVO> pointDetailList = iIsIsolationPointService.getPointDetailList(pointIds);
                // 5.获取sop信息
                List<IsSopPoints> isSopPoints;
                if (sopId != null) {
                    isSopPoints = iIsSopPointsService.list(Wrappers.<IsSopPoints>lambdaQuery()
                            .eq(IsSopPoints::getSopId, sopId));
                } else {
                    isSopPoints = new ArrayList<>();
                }
                // 6.获取作业票点位数据
                List<IsJobTicketPoints> isJobTicketPoints;
                if (ticketId != null) {
                    isJobTicketPoints = iIsJobTicketPointsService.list(Wrappers.<IsJobTicketPoints>lambdaQuery()
                            .eq(IsJobTicketPoints::getTicketId, ticketId));
                } else {
                    isJobTicketPoints = new ArrayList<>();
                }
                // 6.组装数据
                points.stream().filter(o -> {
                    // 初始化选中状态
                    o.setState(false);
                    // 如果点位信息有，则填充
                    if (!pointDetailList.isEmpty()) {
                        for (PointDetailVO pointDetailVO : pointDetailList) {
                            if (o.getPointId().equals(pointDetailVO.getPointId())) {
                                o.setPointName(pointDetailVO.getPointName());
                                o.setPointType(pointDetailVO.getPointType());
                                o.setPointTypeName(pointDetailVO.getPointTypeName());
                                o.setPowerType(pointDetailVO.getPowerType());
                                o.setPowerTypeName(pointDetailVO.getPowerTypeName());
                                o.setPointIcon(pointDetailVO.getPointIcon());
                                o.setPointPicture(pointDetailVO.getPointPicture());
                            }
                        }
                    }
                    // sop如果选中信息有则开始标记
                    if (!isSopPoints.isEmpty()) {
                        for (IsSopPoints isSopPoint : isSopPoints) {
                            if (o.getPointId().equals(isSopPoint.getPointId())) {
                                o.setState(true);
                                // 根据sop的前置节点赋值
                                o.setPrePointId(isSopPoint.getPrePointId());
                            }
                        }
                    }
                    // 作业票如果选中信息有则开始标记
                    if (!isJobTicketPoints.isEmpty()) {
                        for (IsJobTicketPoints ticketPoint : isJobTicketPoints) {
                            if (o.getPointId().equals(ticketPoint.getPointId())) {
                                o.setState(true);
                                // 根据作业票的前置节点赋值
                                o.setPrePointId(ticketPoint.getPrePointId());
                            }
                        }
                    }
                    return true;
                }).collect(Collectors.toList());
            } catch (IOException e) {
                Assert.isTrue(false, "map数据解析失败！");
                e.printStackTrace();
            }
        }
        return points;
    }
}
