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.ktg.common.core.redis.RedisCache;
import com.ktg.common.core.text.Convert;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.DictUtils;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.common.utils.bean.BeanUtils;
import com.ktg.iscs.domain.*;
import com.ktg.iscs.domain.dto.hardwareApi.UpdateSwitchStatusDTO;
import com.ktg.iscs.domain.dto.ticket.AddJobTicketDTO;
import com.ktg.iscs.domain.dto.ticket.AddMarsJobDTO;
import com.ktg.iscs.domain.dto.ticket.AddTicketUserDTO;
import com.ktg.iscs.domain.dto.ticket.PageTicketDTO;
import com.ktg.iscs.domain.enums.*;
import com.ktg.iscs.domain.vo.points.PointDetailVO;
import com.ktg.iscs.domain.vo.ticket.*;
import com.ktg.iscs.domain.vo.ticketKey.IsJobTicketKeyVO;
import com.ktg.iscs.domain.vo.ticketLockset.IsJobTicketLocksetVO;
import com.ktg.iscs.domain.vo.ticketPoints.IsJobTicketPointsVO;
import com.ktg.iscs.mapper.IsJobTicketMapper;
import com.ktg.iscs.mapper.IsJobTicketUserMapper;
import com.ktg.iscs.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static com.ktg.common.constant.Constants.SYS_ATTR;
import static com.ktg.iscs.domain.constant.ErrorCodeConstants.*;
import static com.ktg.iscs.domain.enums.TicketStatusEnum.*;
import static com.ktg.system.strategy.ServiceExceptionUtil.exception;

/**
 * 作业票Service业务层处理
 *
 * @author cgj
 * @date 2024-10-18
 */
@Service
@Slf4j
public class IsJobTicketServiceImpl extends ServiceImpl<IsJobTicketMapper, IsJobTicket> implements IIsJobTicketService {
    @Autowired
    private IsJobTicketMapper isJobTicketMapper;
    @Autowired
    private IIsJobTicketPointsService iIsJobTicketPointsService;
    @Autowired
    private IIsJobTicketUserService iIsJobTicketUserService;
    @Autowired
    private IIsIsolationPointService iIsIsolationPointService;
    @Autowired
    private IIsJobTicketKeyService iIsJobTicketKeyService;
    @Autowired
    private IIsJobTicketLockService iIsJobTicketLockService;
    @Autowired
    private IIsJobTicketLocksetService iIsJobTicketLocksetService;
    @Autowired
    private IIsWorkareaService iIsWorkareaService;
    @Autowired
    private IsJobTicketUserMapper isJobTicketUserMapper;
    @Autowired
    private IIsJobTicketStepService iIsJobTicketStepService;
    @Autowired
    private IIsWorkstationService iIsWorkstationService;
    @Autowired
    private IIsMachineryService isMachineryService;
    @Autowired
    private IIsSopService iIsSopService;
    @Autowired
    private IIsMachineryPointsService iIsMachineryPointsService;
    @Value("${ktg-mes.eightSteps}")
    private String eightSteps;
    @Value("${ktg-mes.androidEightSteps}")
    private String androidEightSteps;
    @Autowired
    private IIsSystemAttributeService isSystemAttributeService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IIsTicketOperLogService isTicketOperLogService;


    /**
     * 查询作业票
     *
     * @param ticketId 作业票主键
     * @return 作业票
     */
    @Override
    public JobTicketDetailVO selectIsJobTicketByTicketId(Long ticketId) {
        // 1.查询基础数据
        IsJobTicket jobTicket = isJobTicketMapper.selectIsJobTicketByTicketId(ticketId);
        Assert.notNull(jobTicket, "作业票信息不存在!");
        JobTicketDetailVO jobTicketDetailVO = BeanUtils.toBean(jobTicket, JobTicketDetailVO.class);
        // 1.1 查询工作区域数据
        if (jobTicket != null && jobTicket.getWorkareaId() != null) {
            IsWorkarea workarea = iIsWorkareaService.getById(jobTicket.getWorkareaId());
            if (workarea != null) {
                jobTicketDetailVO.setWorkareaName(workarea.getWorkareaName());
            }
        }
        // 2.查询作业票和隔离点的关联关系
        List<IsJobTicketPointsVO> isJobTicketPoints = iIsJobTicketPointsService.getListByTicketId(ticketId);
        // 2.1查询隔离点的详细信息
        if (!isJobTicketPoints.isEmpty()) {
            List<Long> pointIds = isJobTicketPoints.stream().map(IsJobTicketPointsVO::getPointId).collect(Collectors.toList());
            List<PointDetailVO> pointDetailList = iIsIsolationPointService.getPointDetailList(pointIds);
            ArrayList<PointDetailVO> pointDetailVOS = new ArrayList<>();
            /*pointDetailList.forEach(o ->
                    isJobTicketPoints.stream()
                            .filter(o1 -> o1.getPointId().equals(o.getPointId()))
                            .findFirst()
                            .ifPresent(data -> {
                                o.setLockId(data.getLockId());
                                o.setPrePointId(data.getPrePointId());
                            }));*/
            // 需要按序输出
            for (IsJobTicketPointsVO isJobTicketPoint : isJobTicketPoints) {
                for (PointDetailVO pointDetailVO : pointDetailList) {
                    if (isJobTicketPoint.getPointId().equals(pointDetailVO.getPointId())) {
                        pointDetailVO.setLockId(isJobTicketPoint.getLockId());
                        pointDetailVO.setLockNfc(isJobTicketPoint.getLockNfc());
                        pointDetailVO.setPrePointId(isJobTicketPoint.getPrePointId());
                        pointDetailVOS.add(pointDetailVO);
                    }
                }
            }
            // 2.2组装隔离点数据
            jobTicketDetailVO.setPointDetailVOList(pointDetailVOS);
        }
        // 3.查询人员信息
        List<IsJobTicketUser> jobTicketUserList = iIsJobTicketUserService.list(Wrappers.<IsJobTicketUser>lambdaQuery().eq(IsJobTicketUser::getTicketId, ticketId));
        // 3.1组装人员数据
        jobTicketDetailVO.setJobTicketUserList(jobTicketUserList);
        return jobTicketDetailVO;
    }

    /**
     * 查询作业票列表
     *
     * @param isJobTicket 作业票
     * @return 作业票
     */
    @Override
    public List<IsJobTicket> selectIsJobTicketList(IsJobTicket isJobTicket) {
        return isJobTicketMapper.selectIsJobTicketList(isJobTicket);
    }

    /**
     * 新增作业票
     *
     * @param dto 作业票
     * @return 结果
     */
    @Transactional
    @Override
    public Long insertJobTicketBySop(AddMarsJobDTO dto) {
        // 1.断言判断必填
        Assert.notNull(dto.getSopId(), "sopid不可为空!");
        IsSop sop = iIsSopService.getById(dto.getSopId());
        Assert.notNull(sop, "sop数据不存在!");
        // 1.1自动生成名称
        String jobName = generateJobName(dto.getWorkstationId(), dto.getMachineryId(), dto.getSopId(), sop.getSopType());
        // 1.2获取隔离点数据
        List<IsMachineryPoints> points = iIsMachineryPointsService.list(Wrappers.<IsMachineryPoints>lambdaQuery()
                .eq(IsMachineryPoints::getMachineryId, sop.getMachineryId()));
        // 2.新增作业票
        IsJobTicket jobTicket = new IsJobTicket();
        jobTicket.setTicketName(jobName);
        jobTicket.setSopId(dto.getSopId());
        jobTicket.setTicketType(sop.getSopType());
        jobTicket.setWorkstationId(sop.getWorkstationId());
        jobTicket.setMachineryId(sop.getMachineryId());
        jobTicket.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        jobTicket.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        isJobTicketMapper.insertIsJobTicket(jobTicket);
        // 启动作业
        isTicketOperLogService.addLog1(jobTicket.getTicketId(), jobName);
        // 3.新增作业票和隔离点的关联关系
        // TODO 批量新增
        ArrayList<IsJobTicketPoints> isJobTicketPoints = new ArrayList<>();
        for (IsMachineryPoints point : points) {
            IsJobTicketPoints jobTicketPoints = new IsJobTicketPoints();
            jobTicketPoints.setTicketId(jobTicket.getTicketId());
            jobTicketPoints.setWorkstationId(sop.getWorkstationId());
            jobTicketPoints.setMachineryId(point.getMachineryId());
            jobTicketPoints.setPointId(point.getPointId());
            isJobTicketPoints.add(jobTicketPoints);
            iIsJobTicketPointsService.save(jobTicketPoints);
        }
        // iIsJobTicketPointsService.saveBatch(isJobTicketPoints);
        // 3.1新增作业票和钥匙的关联关系(两条数据，一条上锁，一条解锁)
        saveJobTicketKey(jobTicket.getTicketId());
        // 3.2新增作业票和挂锁的关联关// 3.3新增作业票和锁具的关联关系
        List<Long> pointIds = points.stream().map(IsMachineryPoints::getPointId).collect(Collectors.toList());
        Assert.isFalse(pointIds.isEmpty(), "点位信息不能为空！");
        List<IsIsolationPoint> pointList = iIsIsolationPointService.listByIds(pointIds);
        saveJobTicketLockAndSet(pointList, jobTicket.getTicketId());

        // 4.新增八大步骤信息
        JobStepEnum jobStepEnum = new JobStepEnum();
        List<String> steps = jobStepEnum.getSteps();
        List<String> androidSteps = jobStepEnum.getAndroidSteps();
        List<IsJobTicketStep> isJobTicketSteps = new ArrayList<>();
        for (int i = 1; i <= steps.size(); i++) {
            IsJobTicketStep isJobTicketStep = new IsJobTicketStep();
            isJobTicketStep.setTicketId(jobTicket.getTicketId());
            isJobTicketStep.setStepIndex(i);
            isJobTicketStep.setStepStatus(i < 3 ? "1" : "0");
            isJobTicketStep.setStepContent(steps.get(i-1));
            isJobTicketStep.setAndroidStepContent(androidSteps.get(i-1));
            isJobTicketSteps.add(isJobTicketStep);
            iIsJobTicketStepService.save(isJobTicketStep);
        }
        // iIsJobTicketStepService.saveBatch(isJobTicketSteps);
        // 操作确认
        for (IsJobTicketStep isJobTicketStep : isJobTicketSteps) {
            if (isJobTicketStep.getStepStatus().equals("1")) {
                isTicketOperLogService.addLog2(jobTicket.getTicketId(), jobName, isJobTicketStep.getAndroidStepContent(), 0L, "系统");
            }
        }
        return jobTicket.getTicketId();
    }

    @Override
    public Boolean insertJobByMachinery(AddMarsJobDTO dto) {
        // 1.断言判断必填
        Assert.notNull(dto.getWorkstationId(), "岗位不可为空!");
        Assert.notNull(dto.getMachineryId(), "工艺不可为空!");
        // 1.1自动生成名称
        String jobName = generateJobName(dto.getWorkstationId(), dto.getMachineryId(), dto.getSopId(), null);
        // 1.2获取隔离点数据
        List<IsMachineryPoints> points = iIsMachineryPointsService.list(Wrappers.<IsMachineryPoints>lambdaQuery()
                .eq(IsMachineryPoints::getMachineryId, dto.getMachineryId()));
        IsMachinery machinery = isMachineryService.getById(dto.getMachineryId());
        // 2.新增作业票
        IsJobTicket jobTicket = new IsJobTicket();
        jobTicket.setTicketName(jobName);
        jobTicket.setSopId(dto.getSopId());
        jobTicket.setTicketType(machinery.getMachineryType());
        jobTicket.setWorkstationId(dto.getWorkstationId());
        jobTicket.setMachineryId(dto.getMachineryId());
        isJobTicketMapper.insertIsJobTicket(jobTicket);
        // 启动作业
        isTicketOperLogService.addLog1(jobTicket.getTicketId(), jobName);
        // 3.新增作业票和隔离点的关联关系
        // TODO 批量新增
        ArrayList<IsJobTicketPoints> isJobTicketPoints = new ArrayList<>();
        for (IsMachineryPoints point : points) {
            IsJobTicketPoints jobTicketPoints = new IsJobTicketPoints();
            jobTicketPoints.setTicketId(jobTicket.getTicketId());
            jobTicketPoints.setWorkstationId(dto.getWorkstationId());
            jobTicketPoints.setMachineryId(point.getMachineryId());
            jobTicketPoints.setPointId(point.getPointId());
            isJobTicketPoints.add(jobTicketPoints);
            iIsJobTicketPointsService.save(jobTicketPoints);
        }
        // iIsJobTicketPointsService.saveBatch(isJobTicketPoints);
        // 3.1新增作业票和钥匙的关联关系(两条数据，一条上锁，一条解锁)
        saveJobTicketKey(jobTicket.getTicketId());
        // 3.2新增作业票和挂锁的关联关// 3.3新增作业票和锁具的关联关系
        List<Long> pointIds = points.stream().map(IsMachineryPoints::getPointId).collect(Collectors.toList());
        List<IsIsolationPoint> pointList = iIsIsolationPointService.listByIds(pointIds);
        saveJobTicketLockAndSet(pointList, jobTicket.getTicketId());

        // 4.新增八大步骤信息
        JobStepEnum jobStepEnum = new JobStepEnum();
        List<String> steps = jobStepEnum.getSteps();
        List<IsJobTicketStep> isJobTicketSteps = new ArrayList<>();
        for (int i = 1; i <= steps.size(); i++) {
            IsJobTicketStep isJobTicketStep = new IsJobTicketStep();
            isJobTicketStep.setTicketId(jobTicket.getTicketId());
            isJobTicketStep.setStepIndex(i);
            isJobTicketStep.setStepStatus(i < 3 ? "1" : "0");
            isJobTicketStep.setStepContent(steps.get(i-1));
            isJobTicketSteps.add(isJobTicketStep);
        }
        // iIsJobTicketStepService.saveBatch(isJobTicketSteps);
        for (IsJobTicketStep isJobTicketStep : isJobTicketSteps) {
            iIsJobTicketStepService.save(isJobTicketStep);
        }
        // 操作确认
        for (IsJobTicketStep isJobTicketStep : isJobTicketSteps) {
            if (isJobTicketStep.getStepStatus().equals("1")) {
                isTicketOperLogService.addLog2(jobTicket.getTicketId(), jobName, isJobTicketStep.getAndroidStepContent(), 0L, "系统");
            }
        }
        return true;
    }

    /**
     * 3.1新增作业票和钥匙的关联关系(两条数据，一条上锁，一条解锁)
     *
     * @return b
     */
    private boolean saveJobTicketKey(Long ticketId) {
        IsJobTicketKey isJobTicketKey = new IsJobTicketKey();
        isJobTicketKey.setTicketId(ticketId);
        isJobTicketKey.setKeyStatus("0");
        isJobTicketKey.setTicketType(0);

        IsJobTicketKey jobTicketKey = new IsJobTicketKey();
        jobTicketKey.setTicketId(ticketId);
        jobTicketKey.setKeyStatus("0");
        jobTicketKey.setTicketType(1);

        List<IsJobTicketKey> isJobTicketKeys = new ArrayList<>();
        isJobTicketKeys.add(isJobTicketKey);
        isJobTicketKeys.add(jobTicketKey);
        for (IsJobTicketKey ticketKey : isJobTicketKeys) {
            iIsJobTicketKeyService.save(ticketKey);
        }
        return true; // iIsJobTicketKeyService.saveBatch(isJobTicketKeys);
    }

    private boolean saveJobTicketLockAndSet(List<IsIsolationPoint> pointList, Long ticketId) {
        ArrayList<IsJobTicketLock> isJobTicketLocks = new ArrayList<>();
        // ArrayList<IsJobTicketLockset> isJobTicketLocksets = new ArrayList<>();
        for (IsIsolationPoint point : pointList) {
            //if (point.getLockTypeId() != null) {
                IsJobTicketLock isJobTicketLock = new IsJobTicketLock();
                isJobTicketLock.setTicketId(ticketId);
                isJobTicketLock.setLockStatus("0");
                isJobTicketLocks.add(isJobTicketLock);
            //}
            /*if (point.getLocksetTypeId() != null) {
                IsJobTicketLockset isJobTicketLockset = new IsJobTicketLockset();
                isJobTicketLockset.setJobTicketId(ticketId);
                isJobTicketLockset.setLocksetStatus("0");
                isJobTicketLockset.setLocksetTypeId(point.getLocksetTypeId());
                isJobTicketLocksets.add(isJobTicketLockset);
            }*/
        }
        // 开始批量新增
        // iIsJobTicketLockService.saveBatch(isJobTicketLocks);
        for (IsJobTicketLock isJobTicketLock : isJobTicketLocks) {
            iIsJobTicketLockService.save(isJobTicketLock);
        }
        // iIsJobTicketLocksetService.saveBatch(isJobTicketLocksets);
        return true;
    }

    /**
     * 自动生成sop名称
     *
     * @param workstationId
     * @param machineryId
     * @param sopId
     * @return
     */
    public String generateJobName(Long workstationId, Long machineryId, Long sopId, String ticketType) {
        String jobName;
        int counter = 1;
        // 1.如果sop生成的，直接拿sop名称加上日期
        if (sopId != null) {
            IsSop sop = iIsSopService.getById(sopId);
            Assert.notNull(sop, "sop不存在");
            jobName = sop.getSopName() + "-" + DateUtils.parseDateToStr("yyyy-MM-dd", new Date());
        } else {
            // 2.如果不是sop生成的，则根据数据自己生成
            IsWorkstation workstation = iIsWorkstationService.getById(workstationId);
            Assert.notNull(workstation, "岗位信息不存在！");
            String workstationName = workstation.getWorkstationName();
            // 2.1如果岗位是有父级的，则处理
            if (!"0".equals(workstation.getAncestors())) {
                // 使用 split 方法按逗号分隔字符串
                String[] items = workstation.getAncestors().split(",");
                // 将数组转换为 List
                List<String> list = Arrays.asList(items);
                List<IsWorkstation> isWorkstationList = iIsWorkstationService.list(Wrappers.<IsWorkstation>lambdaQuery()
                        .in(IsWorkstation::getWorkstationId, list));
                if (!isWorkstationList.isEmpty()) {
                    List<String> collect = isWorkstationList.stream().map(IsWorkstation::getWorkstationName).collect(Collectors.toList());
                    workstationName = String.join("-", collect);
                }

            }
            IsMachinery machinery = isMachineryService.getById(machineryId);
            Assert.notNull(machinery, "设备工艺信息不存在！");
            String ticketTypeValue;
            if (StringUtils.isNotBlank(ticketType)) {
                ticketTypeValue = DictUtils.getDictValue("ticket_type", ticketType);
            } else {
                ticketTypeValue = DictUtils.getDictValue("ticket_type", machinery.getMachineryType());
            }
            jobName = workstationName + "-" + machinery.getMachineryName() + "-" + ticketTypeValue;
        }
        // 开始生成文件名称尾缀
        String rname = jobName;
        while (!list(Wrappers.<IsJobTicket>lambdaQuery().eq(IsJobTicket::getTicketName, jobName)).isEmpty()) {
            jobName = rname + "(" + counter + ")";
            counter++;
        }
        return jobName;
    }

    /**
     * 修改作业票
     *
     * @param dto 作业票
     * @return 结果
     */
    @Transactional
    @Override
    public Boolean updateIsJobTicket(AddJobTicketDTO dto) {
        // 1.断言判断必填
        Assert.notNull(dto.getTicketId(), "id不可为空!");
        Assert.isTrue(StringUtils.isNotBlank(dto.getTicketCode()), "作业票编号不可为空!");
        Assert.isTrue(StringUtils.isNotBlank(dto.getTicketName()), "作业票名称不可为空!");
        // Assert.notNull(dto.getWorkshopId(), "所属车间不可为空!");
        Assert.isFalse(dto.getPointsList().isEmpty(), "请选择隔离点!");
        Assert.isFalse(dto.getTicketUserDTOList().isEmpty(), "人员信息不可为空!");
        // 1.2人员信息是否存在重复
        boolean b = dto.getTicketUserDTOList().size() == dto.getTicketUserDTOList().stream().distinct().count();
        Assert.isTrue(b, "用户数据存在同名情况，请修改！");
        // 1.3检查作业票编码是否唯一
        List<IsJobTicket> list = list(Wrappers.<IsJobTicket>lambdaQuery().eq(IsJobTicket::getTicketCode, dto.getTicketCode()).ne(IsJobTicket::getTicketId, dto.getTicketId()));
        Assert.isTrue(list.isEmpty(), "该编码已被使用!");
        // 1.4检查区域有没有变，区域变了的话隔离点肯定变了，因为隔离点是从区域数据中解析的
        // IsJobTicket isJobTicket = getById(dto.getTicketId());
        // 2.修改作业票
        IsJobTicket jobTicket = BeanUtils.toBean(dto, IsJobTicket.class);
        jobTicket.setUpdateTime(DateUtils.getNowDate());
        isJobTicketMapper.updateById(jobTicket);

        // 3.1检查隔离点有没有变更
        /*List<Long> pointIds = dto.getPointsList().stream().map(IsJobTicketPoints::getPointId).collect(Collectors.toList());
        List<IsJobTicketPoints> isSopPoints = iIsJobTicketPointsService.list(Wrappers.<IsJobTicketPoints>lambdaQuery()
                .eq(IsJobTicketPoints::getTicketId, dto.getTicketId())
                .in(IsJobTicketPoints::getPointId, pointIds));*/
        // 3.2如果查出来变更了，开始执行删除，重新增加一轮 / 当workarea变更也要全部换掉
        // if (pointIds.size() != isSopPoints.size() || !Objects.equals(isJobTicket.getWorkareaId(), dto.getWorkareaId())) {
        // 无法检测隔离点属性是否变更，直接清理重新新增
        iIsJobTicketPointsService.remove(Wrappers.<IsJobTicketPoints>lambdaQuery().eq(IsJobTicketPoints::getTicketId, dto.getTicketId()));
        // TODO 批量新增
        ArrayList<IsJobTicketPoints> isJobTicketPointsArrayList = new ArrayList<>();
        for (IsJobTicketPoints isJobTicketPoints : dto.getPointsList()) {
            IsJobTicketPoints jobTicketPoints = new IsJobTicketPoints();
            jobTicketPoints.setTicketId(jobTicket.getTicketId());
            jobTicketPoints.setWorkshopId(dto.getWorkshopId());
            jobTicketPoints.setWorkareaId(dto.getWorkareaId());
            jobTicketPoints.setPointId(isJobTicketPoints.getPointId());
            jobTicketPoints.setPrePointId(isJobTicketPoints.getPrePointId());
            isJobTicketPointsArrayList.add(jobTicketPoints);
            iIsJobTicketPointsService.save(jobTicketPoints);
        }
        // iIsJobTicketPointsService.saveBatch(isJobTicketPointsArrayList);
        // 3.2新增作业票和挂锁的关联关// 3.3新增作业票和锁具的关联关系 ----先清除
        iIsJobTicketLockService.remove(Wrappers.<IsJobTicketLock>lambdaQuery().eq(IsJobTicketLock::getTicketId, dto.getTicketId()));
        iIsJobTicketLocksetService.remove(Wrappers.<IsJobTicketLockset>lambdaQuery().eq(IsJobTicketLockset::getJobTicketId, dto.getTicketId()));
        List<Long> pointIds = dto.getPointsList().stream().map(IsJobTicketPoints::getPointId).collect(Collectors.toList());
        List<IsIsolationPoint> pointList = iIsIsolationPointService.listByIds(pointIds);
        saveJobTicketLockAndSet(pointList, jobTicket.getTicketId());
        // }
        // 4.修改人员信息，先删后增
        iIsJobTicketUserService.remove(Wrappers.<IsJobTicketUser>lambdaQuery().eq(IsJobTicketUser::getTicketId, dto.getTicketId()));
        for (AddTicketUserDTO addTicketUserDTO : dto.getTicketUserDTOList()) {
            IsJobTicketUser jobTicketUser = BeanUtils.toBean(addTicketUserDTO, IsJobTicketUser.class);
            jobTicketUser.setTicketId(dto.getTicketId());
            if (null == addTicketUserDTO.getUserId() || addTicketUserDTO.getUserId() == 0) {
                addTicketUserDTO.setUserId(0L);
            }
            iIsJobTicketUserService.save(jobTicketUser);
        }
        return true;
    }

    /**
     * 批量删除作业票
     *
     * @param ticketIds 需要删除的作业票主键
     * @return 结果
     */
    @Transactional
    @Override
    public Boolean deleteIsJobTicketByTicketIds(String ticketIds) {
        // 1.断言判断
        Assert.notBlank(ticketIds, "请选择需要删除的数据!");
        // 2.删除主数据
        Long[] longIds = Convert.toLongArray(ticketIds);
        isJobTicketMapper.deleteIsJobTicketByTicketIds(longIds);
        // 3.同时删除is_job_ticket_points
        iIsJobTicketPointsService.remove(Wrappers.<IsJobTicketPoints>lambdaQuery().in(IsJobTicketPoints::getTicketId, longIds));
        // 3.1同时删除is_job_ticket_key
        iIsJobTicketKeyService.remove(Wrappers.<IsJobTicketKey>lambdaQuery().in(IsJobTicketKey::getTicketId, longIds));
        // 3.2同时删除is_job_ticket_lock
        iIsJobTicketLockService.remove(Wrappers.<IsJobTicketLock>lambdaQuery().in(IsJobTicketLock::getTicketId, longIds));
        // 3.3同时删除is_job_ticket_lockset
        iIsJobTicketLocksetService.remove(Wrappers.<IsJobTicketLockset>lambdaQuery().in(IsJobTicketLockset::getJobTicketId, longIds));
        // 3.4同时删除is_job_ticket_user
        iIsJobTicketUserService.remove(Wrappers.<IsJobTicketUser>lambdaQuery().in(IsJobTicketUser::getTicketId, longIds));
        // 3.5同时删除is_job_ticket_step
        iIsJobTicketStepService.remove(Wrappers.<IsJobTicketStep>lambdaQuery().in(IsJobTicketStep::getTicketId, longIds));
        return true;
    }

    /**
     * 删除作业票信息
     *
     * @param ticketId 作业票主键
     * @return 结果
     */
    @Override
    public int deleteIsJobTicketByTicketId(Long ticketId) {
        return isJobTicketMapper.deleteIsJobTicketByTicketId(ticketId);
    }

    @Override
    public Page<PageTicketVO> getIsJobTicketPage(Page<IsJobTicket> page, PageTicketDTO dto) {
        return isJobTicketMapper.getIsJobTicketPage(page, dto);
    }

    @Override
    public List<IsJobTicket> getWorkstationTicketList() {
        IsSystemAttribute isSystemAttributeByKey = null;
        try {
            isSystemAttributeByKey = isSystemAttributeService.getIsSystemAttributeByKey("sys.permit.visible_for_all");
        } catch (Exception e) {
            log.info("sys.lock.auth参数不存在！");
        }

        List<IsJobTicket> list = null;
        if (isSystemAttributeByKey != null) {
            String sysAttrValue = isSystemAttributeByKey.getSysAttrValue();
            if ("1".equals(sysAttrValue)) {
                // 全部可见
                list = list(Wrappers.<IsJobTicket>lambdaQuery().lt(IsJobTicket::getTicketStatus, FINISHED.status));
            }
            if ("2".equals(sysAttrValue)) {
                // 创建人和上锁人可见
                Long userId = SecurityUtils.getUserId();
                list = isJobTicketMapper.getTicketListByAttrValue(userId);
            }
        } else {
            // 没有权限就直接返回全部
            // 查询所有未完成的作业票返回给岗位视图
            list = list(Wrappers.<IsJobTicket>lambdaQuery().lt(IsJobTicket::getTicketStatus, FINISHED.status));
        }
        return list;
    }

    @Override
    public List<IsJobTicket> getMapWorkstationTicketList() {
        List<IsJobTicket> list = list(Wrappers.<IsJobTicket>lambdaQuery().lt(IsJobTicket::getTicketStatus, FINISHED.status));
        return list;
    }

    @Override
    @Transactional
    public Boolean updateTicketProgress(JobTicketUpdateProgressReqVO reqVO) {
        if (reqVO.equipStatus == null) {
            reqVO.equipStatus = 3;
        }
        IsJobTicket isJobTicket = isJobTicketMapper.selectIsJobTicketByTicketId(reqVO.ticketId);
        if (isJobTicket == null) {
            log.error("Job ticket not exists, ticketId: {}, userId : {}", reqVO.ticketId, reqVO.userId);
            throw exception(JOB_TICKET_NOT_EXISTS);
        }

        List<IsJobTicketUser> jobUserList = iIsJobTicketUserService.selectIsJobTicketUserListByTicketId(reqVO.ticketId);
        if (jobUserList.isEmpty()) {
            log.error("Job ticket user not exists, ticketId: {}, userId : {}", reqVO.ticketId, reqVO.userId);
            throw exception(JOB_TICKET_USER_NOT_EXISTS);
        }

        // 可能身兼数职
        List<IsJobTicketUser> matchList = jobUserList.stream().filter(jobUser -> Objects.equals(jobUser.getUserId(), reqVO.userId)).collect(Collectors.toList());
        if (matchList.isEmpty()) {
            log.error("Job ticket user not included, ticketId: {}, userId : {}", reqVO.ticketId, reqVO.userId);
            // throw exception(JOB_TICKET_USER_NOT_INCLUDED);
        } else {
            handleTicketStatus(isJobTicket, jobUserList, reqVO);
        }
        isJobTicketMapper.updateIsJobTicket(isJobTicket);
        isJobTicketUserMapper.updateBatch(jobUserList);
        return true;
    }

    /**
     * 处理工作票状态
     *
     * @param isJobTicket 工作票
     * @param jobUserList 在工作票中的所有人
     */
    private void handleTicketStatus(IsJobTicket isJobTicket, List<IsJobTicketUser> jobUserList, JobTicketUpdateProgressReqVO reqVO) {
        List<IsJobTicketUser> matchUserList = jobUserList.stream().filter(jobUser -> Objects.equals(jobUser.getUserId(), reqVO.userId)).collect(Collectors.toList());
        if (Objects.equals(isJobTicket.getTicketStatus(), FINISHED.status)) {
            log.warn("Job ticket status is finished, cannot update progress, ticketId: {}, userId : {}", reqVO.ticketId, reqVO.userId);
            throw exception(JOB_TICKET_STATUS_FINISHED);
        }
        if (matchUserList.stream().anyMatch(user -> Objects.equals(user.getUserRole(), isSystemAttributeService.getIsSystemAttributeByKey("role.jtlocker").getSysAttrValue()))) {
            if (Objects.equals(isJobTicket.getTicketStatus(), NOT_STARTED.status) || Objects.equals(isJobTicket.getTicketStatus(), READY_TO_LOCK.status) || Objects.equals(isJobTicket.getTicketStatus(), READY_TO_UNLOCK.status) || Objects.equals(isJobTicket.getTicketStatus(), UNLOCKED.status)) {
                handleJobStatus(isJobTicket, jobUserList, reqVO.userId, true, reqVO.equipStatus);
            } else if (Objects.equals(isJobTicket.getTicketStatus(), PROCESSING.status)) {
                // 同时为上锁人、共锁人
                if (matchUserList.stream().anyMatch(user -> Objects.equals(user.getUserRole(), isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue()))) {
                    handleJobStatus(isJobTicket, jobUserList, reqVO.userId, false, reqVO.equipStatus);
                } else {
                    log.warn("Job ticket status is processing, cannot update progress, ticketId: {}, userId : {}", reqVO.ticketId, reqVO.userId);
                    //throw exception(JOB_TICKET_STATUS_NOT_PERMITTED);
                }
            }
        } else if (matchUserList.stream().anyMatch(user -> Objects.equals(user.getUserRole(), isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue()))) {
            if (Objects.equals(isJobTicket.getTicketStatus(), NOT_STARTED.status) || Objects.equals(isJobTicket.getTicketStatus(), READY_TO_LOCK.status) || Objects.equals(isJobTicket.getTicketStatus(), READY_TO_UNLOCK.status) || Objects.equals(isJobTicket.getTicketStatus(), UNLOCKED.status)) {
                log.warn("Job ticket status is processing, cannot update progress, ticketId: {}, userId : {}", reqVO.ticketId, reqVO.userId);
                throw exception(JOB_TICKET_STATUS_NOT_PERMITTED);
            } else if (Objects.equals(isJobTicket.getTicketStatus(), PROCESSING.status)) {
                handleJobStatus(isJobTicket, jobUserList, reqVO.userId, false, reqVO.equipStatus);
            }
        }
    }

    /**
     * 处理工作票相关人员作业状态
     *
     * @param isJobTicket 工作票
     * @param jobUserList 在工作票中的所有人
     * @param isLocker    true：上锁人 false：共锁人
     */
    private void handleJobStatus(IsJobTicket isJobTicket, List<IsJobTicketUser> jobUserList, Long userId, boolean isLocker, int equipStatus) {
        if (isLocker) {
            jobUserList.stream().filter(jobUser -> Objects.equals(jobUser.getUserId(), userId)).filter(user -> Objects.equals(user.getUserRole(), isSystemAttributeService.getIsSystemAttributeByKey("role.jtlocker").getSysAttrValue())).findFirst().ifPresent(jobUser -> {
                if (Objects.equals(jobUser.getJobStatus(), JobStatusEnum.NOT_STARTED.status) || Objects.equals(jobUser.getJobStatus(), JobStatusEnum.ACQUIRE_LOCK.status) || Objects.equals(jobUser.getJobStatus(), JobStatusEnum.ACQUIRE_KEY.status)) {
                    // 部分拿锁
                    if (equipStatus == 1) {
                        jobUser.setJobStatus(String.valueOf(JobStatusEnum.ACQUIRE_LOCK.status));
                    } else if (equipStatus == 2) {  // 全部拿锁
                        jobUser.setJobStatus(String.valueOf(JobStatusEnum.ACQUIRE_KEY.status));
                    } else if (equipStatus == 3) {    // 已拿钥匙
                        jobUser.setJobStatus(String.valueOf(JobStatusEnum.READY_TO_LOCK.status));
                        isJobTicket.setTicketStatus(READY_TO_LOCK.status);
                    } else {
                        log.warn("Job ticket user equipment status is null, ticketId: {}, userId : {}", isJobTicket.getTicketId(), userId);
                        throw exception(JOB_TICKET_USER_EQUIPMENT_STATUS_NULL);
                    }
                } else if (Objects.equals(jobUser.getJobStatus(), JobStatusEnum.READY_TO_LOCK.status)) {
                    jobUser.setJobStatus(String.valueOf(JobStatusEnum.READY_TO_UNLOCK.status));
                    isJobTicket.setTicketStatus(PROCESSING.status);
                } else if (Objects.equals(jobUser.getJobStatus(), JobStatusEnum.READY_TO_UNLOCK.status)) {
                    // 检查所有人
                    if (checkJobStatus(isJobTicket, jobUserList)) {
                        jobUser.setJobStatus(String.valueOf(JobStatusEnum.UNLOCKED.status));
                        // 检查所有设备归还，钥匙归还，锁没还完：已解锁（ticket_status），都还：已完成（ticket_status）
                        int toolRst = checkToolReturn(isJobTicket.getTicketId());
                        int unlockedRst = checkAllUnlocked(isJobTicket.getTicketId());
                        System.out.println("1-------------" + toolRst + " - " + unlockedRst);

                        if (unlockedRst == 0) {
                            if (toolRst == 2) {
                                isJobTicket.setTicketStatus(FINISHED.status);
                            } else {
                                isJobTicket.setTicketStatus(UNLOCKED.status);
                            }
                        } else {
                            // TODO 只还设备，不操作点位
                        }
                    } else {
                        throw exception(JOB_TICKET_USER_WAIT_COLOCKERS);
                    }
                } else if (Objects.equals(jobUser.getJobStatus(), JobStatusEnum.UNLOCKED.status)) {
                    // 任务已完成，更新
//                    jobUser.setJobStatus(JobStatusEnum.UNLOCKED.status);
//                    if (checkToolReturn(isJobTicket.getTicketId())) {
//                        isJobTicket.setTicketStatus(FINISHED.status);
//                    }
                    // 检查所有设备归还，钥匙归还，锁没还完：已解锁（ticket_status），都还：已完成（ticket_status）
                    int toolRst = checkToolReturn(isJobTicket.getTicketId());
                    int unlockedRst = checkAllUnlocked(isJobTicket.getTicketId());
                    System.out.println("2-------------" + toolRst + " - " + unlockedRst);

                    if (unlockedRst == 0) {
                        if (toolRst == 2) {
                            isJobTicket.setTicketStatus(FINISHED.status);
                        } else {
                            isJobTicket.setTicketStatus(UNLOCKED.status);
                        }
                    } else {
                        // TODO 只还设备，不操作点位
                    }
                }
            });
        } else {
            jobUserList.stream().filter(jobUser -> Objects.equals(jobUser.getUserId(), userId)).filter(user -> Objects.equals(user.getUserRole(), isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue())).findFirst().ifPresent(jobUser -> {
                if (Objects.equals(isJobTicket.getTicketStatus(), PROCESSING.status)) {
                    if (Objects.equals(jobUser.getJobStatus(), JobStatusEnum.NOT_STARTED.status)) {
                        jobUser.setJobStatus(String.valueOf(JobStatusEnum.READY_TO_UNLOCK.status));
                    } else if (Objects.equals(jobUser.getJobStatus(), JobStatusEnum.READY_TO_UNLOCK.status)) {
                        jobUserList.stream().filter(data -> Objects.equals(data.getUserId(), userId) && Objects.equals(data.getUserRole(), isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue())).findFirst().ifPresent(data -> data.setJobStatus(String.valueOf(JobStatusEnum.UNLOCKED.status)));
                        checkJobStatus(isJobTicket, jobUserList);
                    } else if (Objects.equals(jobUser.getJobStatus(), JobStatusEnum.UNLOCKED.status)) {
                        // 作业票本人Job部分已完成
                        throw exception(JOB_TICKET_USER_JOB_IS_DONE);
                    }
                } else if (Objects.equals(isJobTicket.getTicketStatus(), NOT_STARTED.status) || Objects.equals(isJobTicket.getTicketStatus(), READY_TO_LOCK.status)) {
                    // 等上锁人上锁
                    throw exception(JOB_TICKET_USER_WAIT_TO_LOCK);
                }
            });
        }
    }

    // 0-全部解锁 1-存在未解锁的点位
    private int checkAllUnlocked(Long ticketId) {
        List<IsJobTicketPoints> unlockedList = iIsJobTicketPointsService.list(Wrappers.<IsJobTicketPoints>lambdaQuery().eq(IsJobTicketPoints::getTicketId, ticketId).ne(IsJobTicketPoints::getPointStatus, PointStatusEnum.REMOVE_LOCK.status));
        if (unlockedList.isEmpty()) {
            return 0;
        } else {
            return 1;
        }
    }

    /**
     * 根据作业票检查锁、辅件、钥匙是否都已经归还了
     *
     * @return 1:挂锁全还，其他有未还  2：全还 3：其他
     */
    private int checkToolReturn(Long ticketId) {
        // 1.1检查钥匙
        List<IsJobTicketKey> ticketKeyList = iIsJobTicketKeyService.list(Wrappers.<IsJobTicketKey>lambdaQuery().eq(IsJobTicketKey::getTicketId, ticketId).ne(IsJobTicketKey::getKeyStatus, KeyStatusEnum.RETURNED.status));

        // 1.2检查挂锁是否都已经归还
        List<IsJobTicketLock> jobTicketLockList = iIsJobTicketLockService.list(Wrappers.<IsJobTicketLock>lambdaQuery().eq(IsJobTicketLock::getTicketId, ticketId).ne(IsJobTicketLock::getLockStatus, LockStatusEnum.RETURN_LOCK.status));

        // 1.3检查辅件是否都已经归还
        List<IsJobTicketLockset> jobTicketLocksetList = iIsJobTicketLocksetService.list(Wrappers.<IsJobTicketLockset>lambdaQuery().eq(IsJobTicketLockset::getJobTicketId, ticketId).ne(IsJobTicketLockset::getLocksetStatus, LocksetStatusEnum.RETURNED.status));

        // 锁全还
        if (jobTicketLockList.isEmpty()) {
            if (ticketKeyList.isEmpty() && jobTicketLocksetList.isEmpty()) {
                return 2;
            } else {
                return 1;
            }
        } else {
            return 3;
        }
    }

    /**
     * 根据关联人作业状态更新工作票状态
     */
    private Boolean checkJobStatus(IsJobTicket isJobTicket, List<IsJobTicketUser> jobUserList) {
        List<IsJobTicketUser> coLockerList = jobUserList.stream().filter(jobUser -> Objects.equals(jobUser.getUserRole(), isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue())).collect(Collectors.toList());
        boolean isCoLockerDone = coLockerList.stream().allMatch(jobUser -> Objects.equals(jobUser.getJobStatus(), JobStatusEnum.UNLOCKED.status));
        if (isCoLockerDone) {
            // 防止进度回溯
            if (Integer.parseInt(isJobTicket.getTicketStatus()) <= 3) {
                isJobTicket.setTicketStatus(TicketStatusEnum.READY_TO_UNLOCK.status);
            }
        }
        return isCoLockerDone;
    }

    @Override
    public Page<MonitorTicketPageVO> getMonitorJobTicketPage(Page<IsJobTicket> page, PageTicketDTO dto) {
        Page<MonitorTicketPageVO> monitorJobTicketPage = isJobTicketMapper.getMonitorJobTicketPage(page, dto);
        // 获取所有的人员信息
        List<IsJobTicketUser> allUserList = null;
        if (!monitorJobTicketPage.getRecords().isEmpty()) {
            List<Long> ticketIds = monitorJobTicketPage.getRecords().stream().map(MonitorTicketPageVO::getTicketId).collect(Collectors.toList());
            // 相关人员信息
            allUserList = iIsJobTicketUserService.list(Wrappers.<IsJobTicketUser>lambdaQuery()
                    .in(IsJobTicketUser::getTicketId, ticketIds));

        }

        for (MonitorTicketPageVO record : monitorJobTicketPage.getRecords()) {
            // 初始值
            record.setLockNum(0);
            record.setLockedNum(0);
            record.setRemoveLockNum(0);
            record.setColockNum(0);
            record.setColockedNum(0);
            record.setRemoveColockNum(0);
            if (allUserList != null) {
                // 1.获取关联的上锁人信息
                List<IsJobTicketUser> jtlockerList = allUserList.stream().filter(o -> o.getTicketId().equals(record.getTicketId()) && o.getUserRole().equals(isSystemAttributeService.getIsSystemAttributeByKey("role.jtlocker").getSysAttrValue())).collect(Collectors.toList());
                if (!jtlockerList.isEmpty()) {
                    // 上锁总数
                    record.setLockNum(jtlockerList.size());
                    // 已上锁数
                    int lockedNum = (int) jtlockerList.stream().filter(o -> o.getJobStatus() != null && o.getJobStatus().equals(String.valueOf(JobStatusEnum.READY_TO_UNLOCK.status))).count();
                    record.setLockedNum(lockedNum);
                    // 已完成(解锁)上锁数
                    int removeLockNum = (int) jtlockerList.stream().filter(o -> o.getJobStatus() != null && o.getJobStatus().equals(String.valueOf(JobStatusEnum.UNLOCKED.status))).count();
                    record.setRemoveLockNum(removeLockNum);
                }
                //2.获取关联的共锁人信息
                List<IsJobTicketUser> jtcolockerList = allUserList.stream().filter(o -> o.getTicketId().equals(record.getTicketId()) && o.getUserRole().equals(isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue())).collect(Collectors.toList());
                if (!jtcolockerList.isEmpty()) {
                    // 上锁总数
                    record.setColockNum(jtcolockerList.size());
                    // 已上锁数
                    int colockedNum = (int) jtcolockerList.stream().filter(o -> o.getJobStatus() != null && o.getJobStatus().equals(String.valueOf(JobStatusEnum.READY_TO_UNLOCK.status))).count();
                    record.setColockedNum(colockedNum);
                    // 已完成(解锁)上锁数
                    int removeColockNum = (int) jtcolockerList.stream().filter(o -> o.getJobStatus() != null && o.getJobStatus().equals(String.valueOf(JobStatusEnum.UNLOCKED.status))).count();
                    record.setRemoveColockNum(removeColockNum);
                }
            }
        }
        return monitorJobTicketPage;
    }

    @Override
    public MonitorJobTicketDetailVO selectMonitorJobTicketDetail(Long ticketId) {
        Assert.notNull(ticketId, "作业票id不可为空!");
        // 1.获取作业票
        IsJobTicket isJobTicket = getById(ticketId);
        Assert.notNull(isJobTicket, "作业票信息丢失了!");
        // 2.获取关联钥匙
        List<IsJobTicketKeyVO> listByTicketId = iIsJobTicketKeyService.getListByTicketId(ticketId);
        // 3.获取上锁人信息
        List<IsJobTicketUser> lockUserList = iIsJobTicketUserService.list(Wrappers.<IsJobTicketUser>lambdaQuery().eq(IsJobTicketUser::getTicketId, ticketId).eq(IsJobTicketUser::getUserRole, isSystemAttributeService.getIsSystemAttributeByKey("role.jtlocker").getSysAttrValue()));
        // 4.获取共锁人信息
        List<IsJobTicketUser> colockUserList = iIsJobTicketUserService.list(Wrappers.<IsJobTicketUser>lambdaQuery().eq(IsJobTicketUser::getTicketId, ticketId).eq(IsJobTicketUser::getUserRole, isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue()));
        // 5.关联隔离点信息
        List<IsJobTicketPointsVO> jobTicketPointsVOList = iIsJobTicketPointsService.getListByTicketId(ticketId);
        List<UpdateSwitchStatusDTO> switchStatusList = redisCache.getCacheList(SYS_ATTR + "sys.points.switch.records");
        // 5.1获取隔离点关联的锁具数据
        List<IsJobTicketLocksetVO> ticketLocksetVOList = iIsJobTicketLocksetService.getListByTicketId(ticketId);
        for (IsJobTicketPointsVO vo : jobTicketPointsVOList) {
            String collect = ticketLocksetVOList.stream().filter(o -> o.getPointId() != null && o.getPointId().equals(vo.getPointId())).map(IsJobTicketLocksetVO::getLocksetName).collect(Collectors.joining(", "));
            vo.setLocksetName(collect);
            if (!switchStatusList.isEmpty()) {
                for (UpdateSwitchStatusDTO updateSwitchStatusDTO : switchStatusList) {
                    if (StringUtils.isNotBlank(vo.getPointSerialNumber())
                            && StringUtils.isNotBlank(updateSwitchStatusDTO.getPointSerialNumber())
                            && vo.getPointSerialNumber().equals(updateSwitchStatusDTO.getPointSerialNumber())) {
                        vo.setSwitchStatus(updateSwitchStatusDTO.getSwitchStatus());
                        vo.setSwitchLastUpdateTime(updateSwitchStatusDTO.getSwitchLastUpdateTime());
                    }
                }
            }
        }
        MonitorJobTicketDetailVO vo = new MonitorJobTicketDetailVO();
        vo.setJobTicket(isJobTicket);
        if (!listByTicketId.isEmpty()) {
            vo.setLockKeyName(listByTicketId.get(0).getKeyName());
            vo.setColockKeyName(listByTicketId.get(1).getKeyName());
        }
        vo.setLockUserList(lockUserList);
        vo.setColockUserList(colockUserList);
        vo.setTicketPointsList(jobTicketPointsVOList);
        return vo;
    }

    @Override
    public Boolean updateJobToFinish(IsJobTicket isJobTicket) {
        Assert.notNull(isJobTicket.getTicketId(), "作业票ID不可为空！");
        // 1.查询未完成的八大步骤
        List<IsJobTicketStep> list = iIsJobTicketStepService.list(Wrappers.<IsJobTicketStep>lambdaQuery()
                .eq(IsJobTicketStep::getTicketId, isJobTicket.getTicketId())
                .ne(IsJobTicketStep::getStepStatus, 1));
        Assert.isTrue(list.isEmpty(), "存在未完成的步骤，暂不可完成！");
        // 2.既然走到这了，说明可以完成了
        update(Wrappers.<IsJobTicket>lambdaUpdate().eq(IsJobTicket::getTicketId, isJobTicket.getTicketId())
                .set(IsJobTicket::getTicketStatus, FINISHED.status)
                .set(IsJobTicket::getTicketEndTime, new Date()));
        // 结束作业
        isTicketOperLogService.addLog11(isJobTicket.getTicketId(), getById(isJobTicket.getTicketId()).getTicketName());
        return true;
    }

    @Override
    public Boolean updateJobToCancel(IsJobTicket isJobTicket) {
        Assert.notNull(isJobTicket.getTicketId(), "作业票ID不可为空！");
        // 1.检查第六步有没有被执行，被执行了不能取消
        IsJobTicketStep jobTicketStep = iIsJobTicketStepService.getOne(Wrappers.<IsJobTicketStep>lambdaQuery()
                .eq(IsJobTicketStep::getTicketId, isJobTicket.getTicketId())
                .eq(IsJobTicketStep::getStepIndex, 6)
                .eq(IsJobTicketStep::getStepStatus, 1));
        Assert.isFalse(jobTicketStep != null, "该作业票已执行至第六步，无法取消！");
        // 2.既然走到这了，说明可以取消
        update(Wrappers.<IsJobTicket>lambdaUpdate().eq(IsJobTicket::getTicketId, isJobTicket.getTicketId())
                .set(IsJobTicket::getTicketStatus, 6));
        // 取消作业
        isTicketOperLogService.addLog10(isJobTicket.getTicketId(), getById(isJobTicket.getTicketId()).getTicketName());
        return true;
    }

    @Override
    public List<JobTicketDetailVO> selectConflictTicket1(List<Long> pointIds, Long ticketId) {
        return isJobTicketMapper.selectConflictTicket1(pointIds, ticketId);
    }

    @Override
    public List<JobTicketDetailVO> selectConflictTicket2(List<Long> pointIds, Long ticketId) {
        return isJobTicketMapper.selectConflictTicket2(pointIds, ticketId);
    }


}
