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.*;

/**
 * @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 {
            int result = mapper.isExist(vo);
            if (result > 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 {
            int result = mapper.isExist(vo);
            if (result > 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();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult dissolutionTeam(BraceletParamsDto dto) {
        try {
            TeamVo teamVo = new TeamVo();
            teamVo.setTeamId(dto.getId());
            // 班组下有在施工人员，无法删除
            List<TeamPeopleVo> workPersonList = getWorkPersonList(dto);
            if(CollectionUtils.isNotEmpty(workPersonList)){
                for (TeamPeopleVo teamPeopleVo : workPersonList) {
                    if(Objects.equals(teamPeopleVo.getWorkStatus(), BusinessConstants.WORK_STATUS)){
                        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);
            dto.setTeamId(vo.getTeamId());
            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;
    }
}
