package com.bonus.material.clz.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.clz.domain.BmTeam;
import com.bonus.material.clz.domain.vo.IwsTeamUserVo;
import com.bonus.material.clz.mapper.BmTeamMapper;
import com.bonus.material.clz.mapper.IwsTeamUserMapper;
import com.bonus.material.clz.service.IwsTeamUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author : 阮世耀
 * @version : 1.0
 * @PackagePath: com.bonus.material.app.service.impl
 * @CreateTime: 2025-06-10  15:21
 * @Description: i皖送查询班组信息接口
 */
@Service
@Slf4j
public class IwsTeamUserServiceImpl implements IwsTeamUserService {

    @Resource
    private IwsTeamUserMapper iwsTeamUserMapper;

    @Resource
    private BmTeamMapper bmTeamMapper;

    /**
     * 根据userName查询用户的身份证号码(idCard)
     *
     * @param userName i皖送登陆用户名
     * @return Object对象
     */
    @Override
    public IwsTeamUserVo selectUserInfoByUserName(String userName) {
        IwsTeamUserVo iwsTeamUserVo = iwsTeamUserMapper.selectUserInfoByUserName(userName);
        if (iwsTeamUserVo == null) {
            return null;
        }
        if (StringUtils.isBlank(iwsTeamUserVo.getIdCard())) {
            iwsTeamUserVo.setIdCard(SecurityUtils.getLoginUser().getUsername());
        }
        return iwsTeamUserVo;
    }

    /**
     * 根据身份证号码查询用户所属班组及工程信息
     *
     * @param dto
     * @return List集合
     */
    @Override
    public List<IwsTeamUserVo> selectProjectTeamInfoByIdCard(IwsTeamUserVo dto) {
        List<IwsTeamUserVo> iwsTeamUserVos = iwsTeamUserMapper.selectProjectTeamInfoByIdCard(dto.getIdCard());
        if (iwsTeamUserVos.isEmpty()) {
            if (CollectionUtils.isEmpty(dto.getProjectIds())) {
                return Collections.emptyList();
            }
            List<String> ids = dto.getProjectIds();
            iwsTeamUserVos = iwsTeamUserMapper.selectProjectTeamInfoByProjectIds(ids);
        }
        return iwsTeamUserVos;
    }

    /**
     * 根据第三方信息修改班组及工程信息
     * @param dto
     * @return
     */
    @Override
    public AjaxResult updateTeamProject(IwsTeamUserVo dto) {
        log.info("i皖送修改班组信息开始:{}",  dto);
        // 根据前端传的信息获取班组信息
        if (CollectionUtils.isEmpty(dto.getTeamList())) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        try {
            // 根据用户名查询班组信息
            BmTeam team = new BmTeam();
            team.setCreateUser(SecurityUtils.getLoginUser().getUserid().toString());
            List<BmTeam> list = bmTeamMapper.queryByPage(team);
            // 先从dto中提取所有teamName到Set中，提高查找效率
            Set<String> dtoTeamNames = dto.getTeamList().stream()
                    .map(IwsTeamUserVo::getTeamName)
                    .collect(Collectors.toSet());
            // 对比2个集合，根据班组名称找出list中有，而dto中没有的元素
            List<BmTeam> collect = list.stream().filter(bmTeam -> !dtoTeamNames.contains(bmTeam.getTeamName())).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                // 走删除逻辑
                for (BmTeam bmTeam : collect) {
                    // 将班组状态改为停用
                    bmTeam.setStatus("1");
                    int result = bmTeamMapper.update(bmTeam);
                    if (result <= 0) {
                        return AjaxResult.error(HttpCodeEnum.UPDATE_TO_DATABASE.getCode(), HttpCodeEnum.UPDATE_TO_DATABASE.getMsg());
                    }
                }
            }
            for (IwsTeamUserVo iwsTeamUserVo : dto.getTeamList()) {
                BmTeam bmTeam = new BmTeam();
                bmTeam.setTeamName(StringUtils.isNotBlank(iwsTeamUserVo.getTeamName()) ? iwsTeamUserVo.getTeamName() : null);
                bmTeam.setCreateUser(SecurityUtils.getLoginUser().getUserid().toString());
                bmTeam.setRelName(StringUtils.isNotBlank(iwsTeamUserVo.getRelName()) ? iwsTeamUserVo.getRelName() : null);
                bmTeam.setIdCard(StringUtils.isNotBlank(iwsTeamUserVo.getTeamLeaderIdCard()) ? iwsTeamUserVo.getTeamLeaderIdCard() : null);
                bmTeam.setProjectId(StringUtils.isNotBlank(iwsTeamUserVo.getProjectId()) ? iwsTeamUserVo.getProjectId() : null);
                bmTeam.setRelPhone(StringUtils.isNotBlank(iwsTeamUserVo.getRelPhone()) ? iwsTeamUserVo.getRelPhone() : null);
                // 班组类型固定传值
                bmTeam.setTypeId(1731L);
                // 根据班组名称去bm_unit表查询班组信息
                BmTeam bmTeam1 = bmTeamMapper.selectByName(bmTeam);
                if (bmTeam1 == null) {
                    // 走新增逻辑
                    int result = bmTeamMapper.insert(bmTeam);
                    if (result <= 0) {
                        return AjaxResult.error(HttpCodeEnum.UPDATE_TO_DATABASE.getCode(), HttpCodeEnum.UPDATE_TO_DATABASE.getMsg());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg());
    }
}
