package com.securitycontrol.background.service.impl;

import com.securitycontrol.background.mapper.TeamManageMapper;
import com.securitycontrol.background.service.TeamService;
import com.securitycontrol.common.core.utils.StringUtils;
import com.securitycontrol.common.core.utils.aes.AesCbcUtils;
import com.securitycontrol.common.core.utils.uuid.IdUtils;
import com.securitycontrol.common.core.web.domain.AjaxResult;
import com.securitycontrol.common.security.utils.ValidatorsUtils;
import com.securitycontrol.entity.background.dto.ParamDto;
import com.securitycontrol.entity.background.vo.HumanManageVo;
import com.securitycontrol.entity.background.vo.TeamManageVo;
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.*;

/**
 * 班组-业务逻辑层
 * @author 10488
 */
@Service(value = "TeamService")
@Slf4j
public class TeamServiceImpl implements TeamService {

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

    @Resource(name = "ValidatorsUtils")
    private ValidatorsUtils validatorsUtils;

    @Override
    public List<TeamManageVo> getTeamLists(ParamDto dto) {
        List<TeamManageVo> list = new ArrayList<>();
        try {
            list = mapper.getTeamLists(dto);
            for (TeamManageVo vo : list) {
                int num = mapper.getTeamUserNum(vo.getTeamId());
                vo.setTeamNum(String.valueOf(num));
            }
        } catch (Exception e) {
            log.error("获取班组列表",e);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addOrUpdateTeam(TeamManageVo vo) {
        try {
            String validResult = validatorsUtils.valid(vo, TeamManageVo.Query.class);
            if (StringUtils.isNotBlank(validResult)) {
                return AjaxResult.error(validResult);
            }
            List<Map<String, String>> list = mapper.isTeamExist(vo);
            if (CollectionUtils.isNotEmpty(list)) {
                Boolean result = teamIsExist(list,vo.getIdNumber());
                if (result) {
                    return AjaxResult.error("班组不能重复");
                }
            }
            if (StringUtils.isEmpty(vo.getTeamId())) {
                String teamId = IdUtils.getUUId();
                vo.setTeamId(teamId);
                vo.setType(1);
            } else {
                vo.setType(2);
            }
            vo.setIdNumber(AesCbcUtils.encrypt(vo.getIdNumber()));
            mapper.addOrUpdateTeam(vo);
        } catch (Exception e) {
            log.error("新增/修改班组", e);
            //手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 班组是否存在
     * @param list
     * @param idNumber
     * @return Boolean
     * @description
     * @author cwchen
     * @date 2024/3/21 10:36
     */
    public Boolean teamIsExist(List<Map<String, String>> list, String idNumber) {
        for (Map<String, String> map : list) {
            String value = map.get("value");
            String decryptValue = AesCbcUtils.decrypt(value);
            if (decryptValue == null) {
                if (Objects.equals(idNumber, value)) {
                    return true;
                }
            } else {
                if (Objects.equals(idNumber, decryptValue)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public AjaxResult getTeamDetailById(ParamDto dto) {
        TeamManageVo vo = new TeamManageVo();
        try {
            vo = mapper.getTeamDetailById(dto);
            String decryptIdNumber = AesCbcUtils.decrypt(vo.getIdNumber());
            if(decryptIdNumber != null){
                vo.setIdNumber(decryptIdNumber);
            }
        } catch (Exception e) {
            log.error("班组详情",e);
        }
        return AjaxResult.success(vo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delTeam(ParamDto dto) {
        try {
            int result = mapper.isPeopleByTeam(dto);
            if(result > 0){
                return AjaxResult.error("班组存在人员");
            }
            mapper.delTeam(dto);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("删除班组",e);
            //手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    public List<HumanManageVo> getTeamUserLists(ParamDto dto) {
        List<HumanManageVo> list = new ArrayList<>();
        try {
            list = mapper.getTeamUserLists(dto);
        } catch (Exception e) {
            log.error("获取班组人员列表",e);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult removeTeamUser(ParamDto dto) {
        try {
            mapper.removeTeamUser(dto);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("移出班组人员");
            //手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult getTeamUserAndNoBandingUser(ParamDto dto) {
        Map<String, Object> map = new HashMap<>(16);
        List<Map<String, String>> teamUsers = new ArrayList<>();
        List<Map<String, String>> noBandingUsers = new ArrayList<>();
        try {
            List<Map<String, String>> list = mapper.getTeamUserAndNoBandingUser(dto);
            if(CollectionUtils.isNotEmpty(list)){
                for (Map<String, String> stringMap : list) {
                    if(Objects.equals(stringMap.get("type"),"1")){
                        teamUsers.add(stringMap);
                    }else if(Objects.equals(stringMap.get("type"),"2")){
                        noBandingUsers.add(stringMap);
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取班组组员和未加入班组人员",e);
        }
        map.put("teamUsers",teamUsers);
        map.put("noBandingUsers",noBandingUsers);
        return AjaxResult.success(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addTeamUser(ParamDto dto) {
        try {
            if(StringUtils.isNotEmpty(dto.getBandingUsers())){
                String[] bandingUserArr = dto.getBandingUsers().split(",");
                for (String bandingUser : bandingUserArr) {
                    mapper.addTeamUser(bandingUser,dto.getId(),1);
                }
            }
            if(StringUtils.isNotEmpty(dto.getUnBandingUsers())){
                String[] unBandingUserArr = dto.getUnBandingUsers().split(",");
                for (String unBandingUser : unBandingUserArr) {
                    mapper.addTeamUser(unBandingUser,null,2);
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("添加班组人员");
            //手动回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }
}
