package com.bonus.bracelet.service.impl;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.bonus.bracelet.mapper.TeamMgeMapper;
import com.bonus.bracelet.service.ITeamMgeService;
import com.bonus.common.core.constant.BusinessConstants;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.entity.bracelet.BraceletParamsDto;
import com.bonus.common.entity.bracelet.vo.TeamPeopleVo;
import com.bonus.common.entity.bracelet.vo.TeamVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className:TeamMgeServiceImpl
 * @author:cwchen
 * @date:2024-07-16-10:37
 * @version:1.0
 * @description:班组管理-serviceImpl
 */
@Service(value = "ITeamMgeService")
@Slf4j
public class TeamMgeServiceImpl implements ITeamMgeService {

    @Resource(name = "TeamMgeMapper")
    private TeamMgeMapper mapper;

    @Override
    public List<TeamVo> getTeamLists(BraceletParamsDto dto) {
        List<TeamVo> list = new ArrayList<>();
        try {
            list = mapper.getTeamLists(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                for (TeamVo teamVo : list) {
                    List<Integer> numList = mapper.getWorkNum(teamVo.getTeamId());
                    teamVo.setWorkNum(numList.get(0));
                    teamVo.setNotWorkNum(numList.get(1));
                    teamVo.setLeaderPhone(Sm4Utils.decode(teamVo.getLeaderPhone()));
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addTeam(TeamVo vo) {
        try {
            if (vo.getUserIdArr() == null || vo.getUserIdArr().length == 0) {
                return AjaxResult.error("未添加班组成员");
            }
            // 同一工程下，不允许存在相同班组名称，已解散的班组除外
            int result = mapper.isExist(vo);
            if (result > 0) {
                return AjaxResult.error("所属工程的班组已存在");
            }
            // 判断班组长是否已经创建班组
            List<Integer> isDistributionList = mapper.isDistribution(vo);
            if (isDistributionList.get(0) > 0) {
                return AjaxResult.error("所选班组长已分配班组");
            }
            vo.setLeaderPhone(Sm4Utils.encode(vo.getLeaderPhone()));
            mapper.addTeam(vo);
            if (vo.getUserIdArr() != null && vo.getUserIdArr().length > 0) {
                mapper.updatePersonsByTeam(vo.getUserIdArr(), vo.getTeamId());
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editTeam(TeamVo vo) {
        try {
            log.info("班组长ID:{}",vo.getTeamLeaderId());
            if (vo.getUserIdArr() == null || vo.getUserIdArr().length == 0) {
                return AjaxResult.error("未添加班组成员");
            }
            // 同一工程下，不允许存在相同班组名称，已解散的班组除外
            int result = mapper.isExist(vo);
            if (result > 0) {
                return AjaxResult.error("所属工程的班组已存在");
            }
            // 更换班组长时选了已经分配的班组长
            List<Integer> isDistributionList = mapper.isDistribution(vo);
            if (isDistributionList.get(0) > 0) {
                return AjaxResult.error("所选班组长已分配班组");
            }
            // 移除人员/更换班组长时 判断人员/班组长是否已经分配手环/设备/手环箱
            List<Long> teamMembers = mapper.getTeamMembers(vo.getTeamId());
            List<Long> notExistData = getNotExistData(vo.getUserIdArr(), teamMembers);
            if(CollectionUtils.isNotEmpty(notExistData)){
                for (Long id : notExistData) {
                   List<Integer> isBandDevices = mapper.isBandDevice(id,vo.getTeamId());
                    if (isBandDevices.get(0) > 0) {
                        return AjaxResult.error("班组长/班组人员已分配手环，无法移除班组人员或更换班长");
                    }else if (isBandDevices.get(1) > 0) {
                        return AjaxResult.error("班组长/班组人员已领用设备，无法移除班组人员或更换班长");
                    }else if (isBandDevices.get(2) > 0) {
                        return AjaxResult.error("班组长已领用手环箱，无法更换班组长");
                    }else if (isBandDevices.get(3) > 0) {
                        return AjaxResult.error("班组长已领用设备，无法更换班组长");
                    }
                }
            }
            vo.setLeaderPhone(Sm4Utils.encode(vo.getLeaderPhone()));
            mapper.updateTeam(vo);
            // 删除改班组下已分配的人员
            mapper.updatePersonsByTeamId(vo);
            if (vo.getUserIdArr() != null && vo.getUserIdArr().length > 0) {
                mapper.updatePersonsByTeam(vo.getUserIdArr(), vo.getTeamId());
            }
            return AjaxResult.success();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 获取两个集合的差集
     * @param userIdArr
     * @param list
     * @return List<Long>
     * @author cwchen
     * @date 2024/8/20 15:39
     */
    public static List<Long> getNotExistData(Long[] userIdArr, List<Long> list) {
        List<Long> userIdList = Arrays.asList(userIdArr);
        List<Long> newList = list.stream()
                .filter(element -> !userIdList.contains(element))
                .collect(Collectors.toList());
        return newList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult dissolutionTeam(BraceletParamsDto dto) {
        try {
            TeamVo teamVo = new TeamVo();
            teamVo.setTeamId(dto.getId());
            // 班组成员/班组临时人员是否存在未归还的设备
            int result = mapper.hasNoReturnDevice(dto.getId());
            if (result > 0) {
                return AjaxResult.error("班组中存在未归还手环设备的班组长/班组成员/临时人员");
            }
            // 班组是否已领用手环箱或者设备
            List<Integer> isHasDeviceList = mapper.isHasDevice(dto.getId());
            if (isHasDeviceList.get(0) > 0) {
                return AjaxResult.error("班组已领用手环箱，请先归还手环箱");
            }
            if (isHasDeviceList.get(1) > 0) {
                return AjaxResult.error("班组已领用设备，请先归还设备");
            }
            // 清空班组下的人员
            mapper.updatePersonsByTeamId(teamVo);
            mapper.dissolutionTeam(dto);
            return AjaxResult.success();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.toString(), e);
            return AjaxResult.error();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delTeam(BraceletParamsDto dto) {
        try {
            if (Objects.equals(dto.getTeamStatus(), BusinessConstants.TYPE)) {
                return AjaxResult.error("班组已解散，无法删除");
            }
            int result = mapper.isExistPerson(dto);
            if (result > 0) {
                return AjaxResult.error("班组已分配人员，无法删除");
            }
            mapper.delTeam(dto);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.toString(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult getPersonList(BraceletParamsDto dto) {
        try {
            // type 1.全部人员 2.未分配人员 3.已分配人员 4.班组长
            List<Map<String, Object>> list = new ArrayList<>();
            list = mapper.getPersonList(dto);
            list = Lists.newArrayList(new HashSet(list));
            return AjaxResult.success(handleList(list));
        } catch (Exception e) {
            log.error(e.toString(), e);
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult getTeamInfo(BraceletParamsDto dto) {
        TeamVo vo = new TeamVo();
        try {
            vo = mapper.getTeamInfo(dto);
            vo.setLeaderPhone(Sm4Utils.decode(vo.getLeaderPhone()));
            dto.setType(2);
            List<Map<String, Object>> unCheckList = mapper.getPersonList(dto);
            dto.setType(3);
            List<Map<String, Object>> checkList = mapper.getPersonList(dto);
            vo.setCheckList(handleList(checkList));
            vo.setUnCheckList(handleList(unCheckList));
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(vo);
    }

    /**
     * 处理身份证号、手机号
     *
     * @param list
     * @return List<Map < String, Object>>
     * @author cwchen
     * @date 2024/7/17 17:44
     */
    public List<Map<String, Object>> handleList(List<Map<String, Object>> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<Map<String, Object>>();
        }
        for (Map<String, Object> map : list) {
            map.put("phone", Sm4Utils.decode(map.get("phone").toString()));
            map.put("idCard", Sm4Utils.decode(map.get("idCard").toString()));
        }
        return list;
    }

    @Override
    public List<TeamPeopleVo> getWorkPersonList(BraceletParamsDto dto) {
        List<TeamPeopleVo> list = new ArrayList<>();
        try {
            list = mapper.getWorkPersonList(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                for (TeamPeopleVo teamPeopleVo : list) {
                    teamPeopleVo.setPhone(Sm4Utils.decode(teamPeopleVo.getPhone()));
                    teamPeopleVo.setIdCard(Sm4Utils.decode(teamPeopleVo.getIdCard()));
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return list;
    }
}
