package com.microservices.pms.project.service.impl;

import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.enums.UserIdentityStatus;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.PageUtils;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.pms.common.service.IPmsCommonService;
import com.microservices.pms.project.domain.PmsProject;
import com.microservices.pms.project.domain.PmsProjectMembers;
import com.microservices.pms.project.domain.vo.PmsProjectMembersDetailVo;
import com.microservices.pms.project.domain.vo.PmsProjectMembersSearchVo;
import com.microservices.pms.project.mapper.PmsProjectMembersMapper;
import com.microservices.pms.project.service.IPmsProjectMembersService;
import com.microservices.pms.project.service.IPmsProjectService;
import com.microservices.system.api.RemoteUserService;
import com.microservices.system.api.domain.SimpleSysUser;
import com.microservices.system.api.domain.SysUserDeptRole;
import com.microservices.system.api.utils.FeignUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 项目-成员Service业务层处理
 *
 * @author wanjia
 * @date 2023-10-11
 */
@Service
public class PmsProjectMembersServiceImpl implements IPmsProjectMembersService {
    @Autowired
    private PmsProjectMembersMapper pmsProjectMembersMapper;

    @Autowired
    private IPmsCommonService pmsCommonService;

    @Autowired
    @Lazy
    private IPmsProjectService pmsProjectService;
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询项目-成员
     *
     * @param id 项目-成员主键
     * @return 项目-成员
     */
    @Override
    public PmsProjectMembers selectPmsProjectMembersById(Long id) {
        PmsProjectMembers pmsProjectMembers = pmsProjectMembersMapper.selectPmsProjectMembersById(id);
        if (pmsProjectMembers == null) {
            throw new ServiceException("该项目成员不存在(项目成员ID[%s])", id);
        }
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectMembers.getPmsProjectId());
        return pmsProjectMembers;
    }

    /**
     * 查询项目-成员列表
     *
     * @param pmsProjectMembers 项目-成员
     * @return 项目-成员
     */
    @Override
    public GenericsTableDataInfo<PmsProjectMembersDetailVo> selectPmsProjectMembersList(PmsProjectMembers pmsProjectMembers) {
        PmsProject pmsProject = pmsProjectService.selectAndCheckPmsProjectById(pmsProjectMembers.getPmsProjectId());
        List<PmsProjectMembers> list = pmsProjectMembersMapper.selectPmsProjectMembersList(pmsProjectMembers);
        list = list.stream().filter(x -> {
            SysUserDeptRole userIdentity = FeignUtils.getReturnData(
                    remoteUserService.getAllStatusUserIdentityByDeptIdAndUserId(pmsProject.getDeptId(), x.getUserId(), SecurityConstants.INNER)
            );
            return userIdentity != null && UserIdentityStatus.NORMAL.getState().equals(userIdentity.getState());
        }).collect(Collectors.toList());
        return PageUtils.toPage(list, x -> {
            PmsProjectMembersDetailVo pmsProjectMembersDetailVo = new PmsProjectMembersDetailVo();
            BeanUtils.copyProperties(x, pmsProjectMembersDetailVo);
            SimpleSysUser userInfo = pmsCommonService.getSimpleSysUserByGitlinkUserId(x.getPmsProjectMemberId());
            pmsProjectMembersDetailVo.setProjectMemberInfo(userInfo);
            return pmsProjectMembersDetailVo;
        });
    }

    @Override
    public List<SimpleSysUser> selectPmsProjectMemberInfoListByProjectId(Long pmsProjectId) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectId);
        List<SimpleSysUser> memberUserInfoList = new ArrayList<>();
        List<Integer> projectMemberIds = pmsProjectMembersMapper.selectPmsProjectMemberIdsByProjectId(pmsProjectId);
        for (Integer projectMemberId : projectMemberIds) {
            memberUserInfoList.add(pmsCommonService.getSimpleSysUserByGitlinkUserId(Long.valueOf(projectMemberId)));
        }
        return memberUserInfoList;
    }

    @Override
    public void checkUserInProject(Long pmsProjectId) {
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectId);
        PmsProjectMembersSearchVo pmsProjectMembersSearchVo = new PmsProjectMembersSearchVo();
        pmsProjectMembersSearchVo.setPmsProjectId(pmsProjectId);
        pmsProjectMembersSearchVo.setPmsProjectMemberId(SecurityUtils.getGitlinkUserId());
        int count = pmsProjectMembersMapper.selectPmsProjectMembersCount(pmsProjectMembersSearchVo);
        if (count == 0) {
            throw new ServiceException("该用户非当前项目成员(项目id[%s]，用户名[%s])", pmsProjectId, SecurityUtils.getUsername());
        }
    }

    /**
     * 新增项目-成员
     *
     * @param pmsProjectMembers 项目-成员
     * @return 结果
     */
    @Override
    public int insertPmsProjectMembers(PmsProjectMembers pmsProjectMembers) {
        SimpleSysUser user = pmsCommonService.getSimpleSysUserByGitlinkUserId(pmsProjectMembers.getPmsProjectMemberId());
        if (user != null) {
            pmsProjectMembers.setUserId(user.getUserId());
        }
        pmsProjectService.selectAndCheckPmsProjectById(pmsProjectMembers.getPmsProjectId());
        boolean exist = pmsProjectMembersMapper.countPmsProjectMembersByProjectIdAndMemberId(
                pmsProjectMembers.getPmsProjectId(),
                pmsProjectMembers.getPmsProjectMemberId()
        ) > 0;
        //成员已存在于项目，不处理
        if (exist) {
            return 1;
        }
        return pmsProjectMembersMapper.insertPmsProjectMembers(pmsProjectMembers);
    }

    /**
     * 新增项目-成员:跳过鉴权
     *
     * @param pmsProjectMembers 项目-成员
     * @return 结果
     */
    @Override
    public int insertPmsProjectMembersWithoutAuthCheck(PmsProjectMembers pmsProjectMembers) {
        SimpleSysUser user = pmsCommonService.getSimpleSysUserByGitlinkUserId(pmsProjectMembers.getPmsProjectMemberId());
        pmsProjectMembers.setUserId(user.getUserId());
        boolean exist = pmsProjectMembersMapper.countPmsProjectMembersByProjectIdAndMemberId(
                pmsProjectMembers.getPmsProjectId(),
                pmsProjectMembers.getPmsProjectMemberId()
        ) > 0;
        //成员已存在于项目，不处理
        if (exist) {
            return 1;
        }
        return pmsProjectMembersMapper.insertPmsProjectMembers(pmsProjectMembers);
    }

    /**
     * 批量删除项目-成员
     *
     * @param ids 需要删除的项目-成员主键
     * @return 结果
     */
    @Override
    public int deletePmsProjectMembersByIds(Long[] ids) {
        int success = 0;
        for (Long id : ids) {
            PmsProjectMembers pmsProjectMembers = selectPmsProjectMembersById(id);
            PmsProject pmsProject = pmsProjectService.selectAndCheckPmsProjectById(pmsProjectMembers.getPmsProjectId());
            if (Objects.equals(pmsProject.getProjectAssigneeId(), pmsProjectMembers.getPmsProjectMemberId())) {
                throw new ServiceException("该用户为当前项目负责人，不允许从成员中移出");
            }
            success += pmsProjectMembersMapper.deletePmsProjectMembersById(id);
        }
        return success;
    }

}
