package com.ktg.iscs.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ktg.common.utils.bean.BeanUtils;
import com.ktg.iscs.domain.IsJobTicket;
import com.ktg.iscs.domain.IsJobTicketStep;
import com.ktg.iscs.domain.IsJobTicketUser;
import com.ktg.iscs.domain.dto.ticket.AddJobTicketDTO;
import com.ktg.iscs.domain.dto.ticket.AddTicketUserDTO;
import com.ktg.iscs.mapper.IsJobTicketUserMapper;
import com.ktg.iscs.service.*;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.stream.Collectors;

/**
 * 作业票用户Service业务层处理
 *
 * @author cgj
 * @date 2024-10-18
 */
@Slf4j
@Service
public class IsJobTicketUserServiceImpl extends ServiceImpl<IsJobTicketUserMapper, IsJobTicketUser> implements IIsJobTicketUserService {
    @Autowired
    private IsJobTicketUserMapper isJobTicketUserMapper;
    @Autowired
    private IIsJobTicketStepService iIsJobTicketStepService;
    @Autowired
    private IIsSystemAttributeService isSystemAttributeService;
    @Autowired
    private IIsTicketOperLogService iIsTicketOperLogService;
    @Autowired
    private IIsJobTicketService isJobTicketService;
    @Override
    public List<IsJobTicketUser> selectIsJobTicketUserListByTicketId(Long ticketId) {
        return isJobTicketUserMapper.selectIsJobTicketUserListByTicketId(ticketId);
    }

    @Transactional
    @Override
    public Boolean addJobUsers(AddJobTicketDTO dto) {
        Assert.notNull(dto.getTicketId(), "作业票id不可为空！");
        Assert.isFalse(dto.getTicketUserDTOList().isEmpty(), "请选择人员信息！");
        IsJobTicket byId = isJobTicketService.getById(dto.getTicketId());
        Assert.isTrue(byId != null, "作业不存在！");
        // 1.检查，如果第四步已经完成，就不允许再更改上锁人
        String jtlocker = isSystemAttributeService.getIsSystemAttributeByKey("role.jtlocker").getSysAttrValue();
        IsJobTicketStep step4 = iIsJobTicketStepService.getOne(Wrappers.<IsJobTicketStep>lambdaQuery()
                .eq(IsJobTicketStep::getTicketId, dto.getTicketId())
                .eq(IsJobTicketStep::getStepIndex, 4));
        if ("1".equals(step4.getStepStatus())) {
            List<IsJobTicketUser> jtlockerUserList = list(Wrappers.<IsJobTicketUser>lambdaQuery()
                    .eq(IsJobTicketUser::getTicketId, dto.getTicketId())
                    .eq(IsJobTicketUser::getUserRole, jtlocker));
            List<Long> collect = jtlockerUserList.stream().map(IsJobTicketUser::getUserId).collect(Collectors.toList());
            List<Long> collect1 = dto.getTicketUserDTOList().stream().filter(o -> o.getUserRole().equals(jtlocker)).map(AddTicketUserDTO::getUserId).collect(Collectors.toList());
            if (collect.containsAll(collect1) && collect1.containsAll(collect)) {
                log.info("两个列表内容相等（忽略顺序）");
            } else {
                Assert.isFalse(true, "您已执行完第4步，无法更换上锁人！");
            }
        }
        // 1.1执行完第六步后不可修改共锁人
        IsJobTicketStep step6 = iIsJobTicketStepService.getOne(Wrappers.<IsJobTicketStep>lambdaQuery()
                .eq(IsJobTicketStep::getTicketId, dto.getTicketId())
                .eq(IsJobTicketStep::getStepIndex, 6));
        Assert.isFalse("1".equals(step6.getStepStatus()), "您已执行完第6步，无法更换人员！");
        // 原来的人员结构
        List<IsJobTicketUser> list = list(Wrappers.<IsJobTicketUser>lambdaQuery().eq(IsJobTicketUser::getTicketId, dto.getTicketId()));
        ArrayList<IsJobTicketUser> isJobTicketUsers = Lists.newArrayList(list);
        // 2.先清理一下
        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);
            }
            save(jobTicketUser);
        }
        // 3.同时更新第三步为已执行
        iIsJobTicketStepService.update(Wrappers.<IsJobTicketStep>lambdaUpdate()
                .eq(IsJobTicketStep::getTicketId, dto.getTicketId())
                .eq(IsJobTicketStep::getStepIndex, 3)
                .set(IsJobTicketStep::getStepStatus, 1));
        // 4.人员变动
        removeUserLog(byId, isJobTicketUsers, dto.getTicketUserDTOList());
        addUserLog(byId, isJobTicketUsers, dto.getTicketUserDTOList());
        return true;
    }


    private void removeUserLog(IsJobTicket byId, List<IsJobTicketUser> list, List<AddTicketUserDTO> ticketUserDTOList) {
        list.removeIf(item -> ticketUserDTOList
                .stream()
                .filter(o -> o.getUserId().equals(item.getUserId()) && o.getUserRole().equals(item.getUserRole()))
                .map(AddTicketUserDTO::getUserId)
                .collect(Collectors.toSet())
                .contains(item.getUserId()));
        for (IsJobTicketUser isJobTicketUser : list) {
            String lockType = "";
            if (isJobTicketUser.getUserRole().equals(isSystemAttributeService.getIsSystemAttributeByKey("role.jtlocker").getSysAttrValue())) {
                lockType = "上锁人";
            }
            if (isJobTicketUser.getUserRole().equals(isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue())) {
                lockType = "共锁人";
            }
            iIsTicketOperLogService.addLog3(byId.getTicketId(), byId.getTicketName(), "移除", lockType, isJobTicketUser.getUserName());
        }

    }

    private void addUserLog(IsJobTicket byId, List<IsJobTicketUser> list, List<AddTicketUserDTO> ticketUserDTOList) {
        ticketUserDTOList.removeIf(item -> list
                .stream()
                .filter(o -> o.getUserId().equals(item.getUserId()) && o.getUserRole().equals(item.getUserRole()))
                .map(IsJobTicketUser::getUserId)
                .collect(Collectors.toSet())
                .contains(item.getUserId()));
        for (AddTicketUserDTO isJobTicketUser : ticketUserDTOList) {
            String lockType = "";
            if (isJobTicketUser.getUserRole().equals(isSystemAttributeService.getIsSystemAttributeByKey("role.jtlocker").getSysAttrValue())) {
                lockType = "上锁人";
            }
            if (isJobTicketUser.getUserRole().equals(isSystemAttributeService.getIsSystemAttributeByKey("role.jtcolocker").getSysAttrValue())) {
                lockType = "共锁人";
            }
            iIsTicketOperLogService.addLog3(byId.getTicketId(), byId.getTicketName(), "添加", lockType, isJobTicketUser.getUserName());
        }

    }

    @Override
    public List<IsJobTicketUser> getMyJob(Long userId) {
        return isJobTicketUserMapper.getMyJob(userId);
    }


}
