package com.ankaibei.workFlow.webadmin.ankaibei.service.impl;

import com.alibaba.fastjson.JSON;
import com.ankaibei.workFlow.webadmin.ankaibei.entity.ProjectInfoEntity;
import com.ankaibei.workFlow.webadmin.ankaibei.entity.ProjectTeamInfoEntity;
import com.ankaibei.workFlow.webadmin.ankaibei.entity.RelevanceProjectInfoEntity;
import com.ankaibei.workFlow.webadmin.ankaibei.entity.UserInfoEntity;
import com.ankaibei.workFlow.webadmin.ankaibei.enums.CodeEnum;
import com.ankaibei.workFlow.webadmin.ankaibei.mapper.ProjectInfoMapper;
import com.ankaibei.workFlow.webadmin.ankaibei.mapper.ProjectTeamMapper;
import com.ankaibei.workFlow.webadmin.ankaibei.mapper.RelevanceProjectInfoMapper;
import com.ankaibei.workFlow.webadmin.ankaibei.mapper.UserInfoMapper;
import com.ankaibei.workFlow.webadmin.ankaibei.service.ProjectTeamService;
import com.ankaibei.workFlow.webadmin.ankaibei.vo.ResMsg;
import com.ankaibei.workFlow.webadmin.ankaibei.vo.WorkSysUserVo;
import com.ankaibei.workFlow.webadmin.upms.controller.SysUserController;
import com.ankaibei.workFlow.webadmin.upms.vo.SysUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author lwq
 * @version 1.0
 * @description:
 * @date 2022/9/13 10:26
 */
@Service
public class ProjectTeamServiceImpl implements ProjectTeamService {

    @Resource
    private ProjectTeamMapper projectTeamMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private RelevanceProjectInfoMapper relevanceProjectInfoMapper;
    @Resource
    private ProjectInfoMapper projectInfoMapper;
    @Resource
    private SysUserController sysUserController;


    @Override
    public ResMsg findProjectTeamAll(Integer pageIndex, Integer pageSize, ProjectTeamInfoEntity projectTeamInfoEntity) {
        Pageable page = PageRequest.of(pageIndex - 1, pageSize);
        Page<ProjectTeamInfoEntity> all;
        if (StringUtils.isBlank(projectTeamInfoEntity.getProjectTeamName())) {
            all = projectTeamMapper.findAll(page);
        } else {
            all = projectTeamMapper.findAllByProjectTeamNameLike(projectTeamInfoEntity.getProjectTeamName(), page);
        }
        return new ResMsg(CodeEnum.OK, ResMsg.getMap(all.map(map -> {
            Optional<ProjectInfoEntity> byId = projectInfoMapper.findById(Integer.valueOf(map.getProjectId()));
            ProjectInfoEntity projectInfoEntity = byId.orElse(null);
            map.setProjectName(projectInfoEntity != null ? projectInfoEntity.getProjectName() : null);
            return map;
        }).getContent(), all.getTotalElements()));
    }

    @Override
    public ResMsg findProjectTeamUser(Integer pageIndex, Integer pageSize, Integer projectTeamId) {
        Pageable page = PageRequest.of(pageIndex - 1, pageSize);
        Page<Map<String, Integer>> byProjectTeamIdEquals = relevanceProjectInfoMapper.findByProjectTeamIdEquals(String.valueOf(projectTeamId), page);
        ArrayList<String> list = new ArrayList<>();
        byProjectTeamIdEquals.map(map -> {
            list.add(String.valueOf(map.get("userId")));
            return null;
        });
        List<SysUserVo> userList = new ArrayList<>();
        for (String str : list) {
                userList.add(sysUserController.view(str).getData());
        }
        return new ResMsg(CodeEnum.OK, ResMsg.getMap(userList, byProjectTeamIdEquals.getTotalElements()));
    }

    @Override
    public boolean deleteBatch(List<ProjectTeamInfoEntity> projectTeamInfoVos) {
        for (ProjectTeamInfoEntity info : projectTeamInfoVos) {
            projectTeamMapper.deleteById(info.getProjectTeamId());
        }
        return true;
    }

    @Override
    public ResMsg updateProjectTeam(ProjectTeamInfoEntity projectTeamInfoEntity) {
        List<ProjectTeamInfoEntity> all = projectTeamMapper.findAll();
        for (ProjectTeamInfoEntity project : all) {
            if (projectTeamInfoEntity.getProjectTeamName().equals(project.getProjectTeamName()) && !projectTeamInfoEntity.getProjectTeamId().equals(project.getProjectTeamId())) {
                return new ResMsg(CodeEnum.TNE_PROJECT_TEAM_NAME_ALREADY_EXISTS);
            }
            if (projectTeamInfoEntity.getProjectTeamId().equals(project.getProjectTeamId())) {
                project.setProjectTeamName(projectTeamInfoEntity.getProjectTeamName());
                projectTeamMapper.save(project);
            }

        }
        return new ResMsg(CodeEnum.OK);
    }

    @Override
    public boolean deleteBatchUser(List<UserInfoEntity> userInfoEntities) {
        for (UserInfoEntity info : userInfoEntities) {
            userInfoMapper.deleteById(info.getUserId());
        }
        return true;
    }

    @Override
    public ResMsg addUser(UserInfoEntity userInfoEntity) {
        List<UserInfoEntity> all = userInfoMapper.findAll();
//        for (UserInfoEntity info:all) {
//            if(userInfoEntity.getJobNumber().equals(info.getJobNumber())){
//                return new ResMsg(CodeEnum.THE_JOB_ID_ALREADY_EXISTS);
//            }
//            if(userInfoEntity.getUserPhone().equals(info.getUserPhone())){
//                return new ResMsg(CodeEnum.PHONE_ALREADY_EXISTS);
//            }
//        }
//        userInfoEntity.setCreateDate(new Date());
        userInfoEntity.setUserStatus(1);
        userInfoMapper.save(userInfoEntity);
        return new ResMsg(CodeEnum.OK);
    }

    @Override
    public ResMsg updateUser(UserInfoEntity userInfoEntity) {
//        List<UserInfoEntity> all = userInfoMapper.findAll();
//        for (UserInfoEntity info:all) {
//            if(userInfoEntity.getJobNumber().equals(info.getJobNumber()) && !userInfoEntity.getUserId().equals(info.getUserId())){
//                return new ResMsg(CodeEnum.THE_JOB_ID_ALREADY_EXISTS);
//            }
//            if(userInfoEntity.getUserPhone().equals(info.getUserPhone()) && !userInfoEntity.getUserId().equals(info.getUserId())){
//                return new ResMsg(CodeEnum.PHONE_ALREADY_EXISTS);
//            }
//            if(userInfoEntity.getUserId().equals(info.getUserId())){
//                userInfoEntity.setCreateDate(new Date());
//                userInfoMapper.save(userInfoEntity);
//            }
//        }
        return new ResMsg(CodeEnum.OK);
    }

    @Override
    public ResMsg findById(String userId) {
        UserInfoEntity byUserIdEquals = userInfoMapper.findByUserIdEquals(userId);
        return new ResMsg(CodeEnum.OK, byUserIdEquals);
    }

    @Override
    public ResMsg findPrincipal() {
        List<Map<String, String>> byUserDutyEquals = userInfoMapper.getProUserAll();
        List<WorkSysUserVo> workSysUserVoList = JSON.parseArray(JSON.toJSONString(byUserDutyEquals), WorkSysUserVo.class);
        return new ResMsg(CodeEnum.OK, workSysUserVoList);
    }

    @Override
    public ResMsg findTeamUser(ProjectTeamInfoEntity projectTeamInfoEntity) {
        //获取项目组的团队id，
        List<ProjectTeamInfoEntity> teams = projectTeamMapper.findByProjectIdEquals(projectTeamInfoEntity.getProjectId());
        List<UserInfoEntity> allByUserId = new ArrayList<>();
        if (teams.size() > 0) {
            List<String> userIds = relevanceProjectInfoMapper.findByProjectTeamIdEquals(teams.get(0).getProjectTeamId() + "");
            allByUserId = userInfoMapper.findAllByUserId(userIds);
        }
        return new ResMsg(CodeEnum.OK, allByUserId);
    }

    @Override
    public ResMsg addProjectTeam(ProjectTeamInfoEntity projectTeamInfoEntity, List<Long> userIds) {
        if (projectTeamMapper.findByProjectTeamNameEquals(projectTeamInfoEntity.getProjectTeamName()).size() > 0) {
            return new ResMsg(CodeEnum.TNE_PROJECT_TEAM_NAME_ALREADY_EXISTS);
        }
        if (projectTeamMapper.findByProjectIdEquals(projectTeamInfoEntity.getProjectId()).size() > 0) {
            return new ResMsg(CodeEnum.PROJECT_TEAM_HAS_BEEN_ESTABLISHED_FOR_THE_PROJECT);
        }
        projectTeamInfoEntity.setCreateDate(new Date());
        ProjectTeamInfoEntity save = projectTeamMapper.save(projectTeamInfoEntity);
        if (userIds.size() > 0) {
            addProjectTeamUser(save, userIds);
        }

        return new ResMsg(CodeEnum.OK);
    }

    @Override
    public ResMsg addProjectTeamUser(ProjectTeamInfoEntity projectTeamInfoEntity, List<Long> userIds) {
        List<String> list = new ArrayList<>();
        for (Long user : userIds) {
            int byuserIdbyrojectTeamid = relevanceProjectInfoMapper.findByuserIdbyrojectTeamid(String.valueOf(user), projectTeamInfoEntity.getProjectTeamId());
            if (byuserIdbyrojectTeamid > 0) {
                list.add(String.valueOf(user));
                continue;
            }
            RelevanceProjectInfoEntity relevanceProjectInfoEntity = new RelevanceProjectInfoEntity();
            relevanceProjectInfoEntity.setProjectTeamId(projectTeamInfoEntity.getProjectTeamId());
            relevanceProjectInfoEntity.setUserId(String.valueOf(user));
            relevanceProjectInfoMapper.save(relevanceProjectInfoEntity);
        }
        List<UserInfoEntity> allById = userInfoMapper.findAllById(list);
        StringBuffer str = new StringBuffer();
        if (allById.size() > 0) {
            for (UserInfoEntity userId : allById) {
                str.append(userId.getShowName() + ",");
            }
            int i = str.lastIndexOf(",");
            str.deleteCharAt(i);
            str.append("已存在");
            return new ResMsg(CodeEnum.OK, str);
        }
        return new ResMsg(CodeEnum.OK);
    }

    @Override
    public ResMsg removeUser(ProjectTeamInfoEntity projectTeamInfoEntity, List<Long> userIds) {
        for (Long user : userIds) {
            relevanceProjectInfoMapper.removeUser(projectTeamInfoEntity.getProjectTeamId(), user);
        }
        return new ResMsg(CodeEnum.OK);
    }

    @Override
    public ResMsg findUserProject(String userId) {
        List<Integer> projectTeamIds = new ArrayList<>();
        List<String> byUserId = relevanceProjectInfoMapper.findByUserId(userId);
        for (String s : byUserId) {
            projectTeamIds.add(Integer.valueOf(s));
        }
        List<ProjectTeamInfoEntity> allById = projectTeamMapper.findAllById(projectTeamIds);
        List<Integer> list = new ArrayList<>();
        for (ProjectTeamInfoEntity pro : allById) {
            list.add(Integer.valueOf(pro.getProjectId()));
        }
        List<ProjectInfoEntity> allById1 = projectInfoMapper.findAllById(list);
        return new ResMsg(CodeEnum.OK, allById1);
    }
}
