package com.ktg.iscs.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ktg.common.utils.DictUtils;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.iscs.domain.*;
import com.ktg.iscs.domain.dto.flexiblejob.AddFlexibleJobDTO;
import com.ktg.iscs.domain.dto.hardwareApi.TakeOutKeyDTO;
import com.ktg.iscs.domain.dto.hardwareApi.TakeTicketLockDTO;
import com.ktg.iscs.domain.enums.JobStepEnum;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 灵活作业调用接口
 *
 * @author cgj
 * @date 2025-11-10
 */
@Slf4j
@Service
public class FlexibleJobServiceImpl implements FlexibleJobService {

    @Autowired
    private IIsJobTicketService iIsJobTicketService;
    @Autowired
    private IIsWorkstationService iIsWorkstationService;
    @Autowired
    private IIsTicketOperLogService isTicketOperLogService;
    @Autowired
    private IIsJobTicketStepService iIsJobTicketStepService;
    @Autowired
    private IIsJobTicketKeyService iIsJobTicketKeyService;
    @Autowired
    private IIsKeyService iIsKeyService;
    @Autowired
    private IIsLockService iIsLockService;
    @Autowired
    private IIsJobTicketLockService iIsJobTicketLockService;


    @Override
    public Long insertFlexibleJobTicket(AddFlexibleJobDTO dto) {
        // 1.1自动生成名称
        String jobName = generateJobName(dto.getWorkstationId(), dto.getType());
        // 2.新增作业票
        IsJobTicket jobTicket = new IsJobTicket();
        jobTicket.setTicketName(jobName);
        jobTicket.setWorkstationId(dto.getWorkstationId());
        jobTicket.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        jobTicket.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        iIsJobTicketService.save(jobTicket);
        // 启动作业
        isTicketOperLogService.addLog1(jobTicket.getTicketId(), jobName);

        // 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);
        }
        // 操作确认
        for (IsJobTicketStep isJobTicketStep : isJobTicketSteps) {
            if ("1".equals(isJobTicketStep.getStepStatus())) {
                isTicketOperLogService.addLog2(jobTicket.getTicketId(), jobName, isJobTicketStep.getAndroidStepContent(), 0L, "系统");
            }
        }
        return jobTicket.getTicketId();
    }

    public String generateJobName(Long workstationId, String ticketType) {
        String jobName;
        int counter = 1;
        // 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);
            }

        }
        String ticketTypeValue = null;
        if (StringUtils.isNotBlank(ticketType)) {
            ticketTypeValue = "-" + DictUtils.getDictValue("ticket_type", ticketType);
        }
        jobName = "灵活作业" + "-" + workstationName + ticketTypeValue;
        // 开始生成文件名称尾缀
        String rname = jobName;
        while (!iIsJobTicketService.list(Wrappers.<IsJobTicket>lambdaQuery().eq(IsJobTicket::getTicketName, jobName)).isEmpty()) {
            jobName = rname + "(" + counter + ")";
            counter++;
        }
        return jobName;
    }


    @Transactional
    @Override
    public Boolean insertTakeOutKey(List<TakeOutKeyDTO> list) {
        for (TakeOutKeyDTO dto : list) {
            Assert.notNull(dto.getTicketId(), "作业id不能为空！");
            // 检查钥匙是否存在
            IsKey key = iIsKeyService.getOne(Wrappers.<IsKey>lambdaQuery().eq(IsKey::getKeyNfc, dto.getKeyNfc()));
            Assert.notNull(key, dto.getKeyNfc() + "对应的钥匙信息不存在！");
            // 如果已经有了取出记录
            IsJobTicketKey jobTicketKey = iIsJobTicketKeyService.getOne(Wrappers.<IsJobTicketKey>lambdaQuery()
                    .eq(IsJobTicketKey::getTicketId, dto.getTicketId())
                    .eq(IsJobTicketKey::getKeyId, key.getKeyId()));
            if (jobTicketKey != null) {

            } else {
                // 如果没有取出记录
                IsJobTicketKey jobTicketKey1 = new IsJobTicketKey();
                jobTicketKey1.setTicketId(dto.getTicketId());
                jobTicketKey1.setKeyId(key.getKeyId());
                jobTicketKey1.setCollectTime(new Date());
                jobTicketKey1.setKeyStatus("0");
                jobTicketKey1.setTicketType(0);
                iIsJobTicketKeyService.save(jobTicketKey1);
            }
        }
        return true;
    }

    @Override
    public Boolean updateTakeBackKey(List<TakeOutKeyDTO> list) {
        Date date = new Date();
        for (TakeOutKeyDTO dto : list) {
            Assert.notNull(dto.getTicketId(), "请告诉我关于哪个作业票!");
            Assert.notBlank(dto.getKeyNfc(), "请告诉我钥匙的NFC!");
            // 1.获取作业票数据
            IsJobTicket jobTicket = iIsJobTicketService.getById(dto.getTicketId());
            Assert.notNull(jobTicket, "作业票数据丢失啦!");
            // 1.1获取上锁时取出的锁的信息
            IsKey startKey = iIsKeyService.getOne(Wrappers.<IsKey>lambdaQuery().eq(IsKey::getKeyNfc, dto.getKeyNfc()));
            Assert.notNull(startKey, "钥匙数据丢失啦!");
            // 1.4修改为归还
            iIsJobTicketKeyService.update(Wrappers.<IsJobTicketKey>lambdaUpdate()
                    .eq(IsJobTicketKey::getTicketId, jobTicket.getTicketId())
                    .eq(IsJobTicketKey::getKeyId, startKey.getKeyId())
                    .ne(IsJobTicketKey::getKeyStatus, "2")
                    .set(IsJobTicketKey::getKeyStatus, "2")
                    .set(IsJobTicketKey::getGiveBackTime, date));
        }
        return true;
    }

    @Override
    public Boolean insertTakeOutLock(List<TakeTicketLockDTO> list) {
        Date date = new Date();
        for (TakeTicketLockDTO dto : list) {
            Assert.notNull(dto.getTicketId(), "作业id不能为空！");
            // 检查锁是否存在
            IsLock lock = iIsLockService.getOne(Wrappers.<IsLock>lambdaQuery().eq(IsLock::getLockNfc, dto.getLockNfc()));
            Assert.notNull(lock, dto.getLockNfc() + "对应的挂锁信息不存在！");
            // 如果已经有了取出记录
            IsJobTicketLock jobTicketLock = iIsJobTicketLockService.getOne(Wrappers.<IsJobTicketLock>lambdaQuery()
                    .eq(IsJobTicketLock::getTicketId, dto.getTicketId())
                    .eq(IsJobTicketLock::getLockId, lock.getLockId()));
            if (jobTicketLock != null) {

            } else {
                // 如果没有取出记录
                IsJobTicketLock jobTicketLock1 = new IsJobTicketLock();
                jobTicketLock1.setTicketId(dto.getTicketId());
                jobTicketLock1.setLockId(lock.getLockId());
                jobTicketLock1.setLockStatus("1");
                jobTicketLock1.setCreateTime(date);
                iIsJobTicketLockService.save(jobTicketLock1);
            }
        }
        return true;
    }

    @Override
    public Boolean updateTakeBackLock(List<TakeTicketLockDTO> list) {
        for (TakeTicketLockDTO dto : list) {
            Assert.notNull(dto.getTicketId(), "请告诉我关于哪个作业票!");
            Assert.notBlank(dto.getLockNfc(), "请告诉我挂锁的NFC!");
            // 1.获取作业票数据
            IsJobTicket jobTicket = iIsJobTicketService.getById(dto.getTicketId());
            Assert.notNull(jobTicket, "作业票数据丢失啦!");
            // 1.1获取锁的信息
            IsLock isLock = iIsLockService.getOne(Wrappers.<IsLock>lambdaQuery().eq(IsLock::getLockNfc, dto.getLockNfc()));
            Assert.notNull(isLock, "挂锁数据丢失啦!");
            // 1.4修改为归还
            iIsJobTicketLockService.update(Wrappers.<IsJobTicketLock>lambdaUpdate()
                    .eq(IsJobTicketLock::getTicketId, jobTicket.getTicketId())
                    .eq(IsJobTicketLock::getLockId, isLock.getLockId())
                    .ne(IsJobTicketLock::getLockStatus, "5")
                    .set(IsJobTicketLock::getLockStatus, "5"));
        }
        return true;
    }


}
