package cn.cslg.pas.service;

import cn.cslg.pas.common.model.dto.PasUserDTO;
import cn.cslg.pas.common.model.vo.PasUserVO;
import cn.cslg.pas.common.model.vo.ProjectUserVO;
import cn.cslg.pas.common.utils.DateUtils;
import cn.cslg.pas.common.utils.Response;
import cn.cslg.pas.domain.ProjectUser;
import cn.cslg.pas.mapper.ProjectUserMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 分配表 服务类
 * </p>
 *
 * @author 王岩
 * @since 2022-02-18
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ProjectUserService extends ServiceImpl<ProjectUserMapper, ProjectUser> {
    private final OAuth2Service oAuth2Service;

    public ProjectUser getProjectUserByProjectIdAndUserId(Integer projectId, Integer userId) {
        LambdaQueryWrapper<ProjectUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectUser::getProjectId, projectId);
        queryWrapper.eq(ProjectUser::getUserId, userId);
        return this.getOne(queryWrapper);
    }

    public List<ProjectUser> getProjectUserByUserId(Integer userId) {
        LambdaQueryWrapper<ProjectUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectUser::getUserId, userId);
        return this.list(queryWrapper);
    }

    public List<Integer> getProIdByUserId(Integer userId) {
        return this.getProjectUserByUserId(userId).stream().map(ProjectUser::getProjectId).collect(Collectors.toList());
    }

    public List<Integer> getProjectUserIdByProjectId(Integer projectId) {
        LambdaQueryWrapper<ProjectUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectUser::getProjectId, projectId);
        return this.list(queryWrapper).stream().map(ProjectUser::getUserId).collect(Collectors.toList());
    }

    public List<ProjectUser> getListByProIdAndUserIds(List<Integer> userIds, Integer projectId) {
        LambdaQueryWrapper<ProjectUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProjectUser::getUserId, userIds);
        queryWrapper.eq(ProjectUser::getProjectId, projectId);
        return this.list(queryWrapper);
    }

    public IPage<ProjectUser> getPageList(ProjectUserVO params) throws IOException {
        //根据专题库id和类型获得人员id
        LambdaQueryWrapper<ProjectUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectUser::getProjectId, params.getProjectId());
        if (params.getType() != null) {
            wrapper.eq(ProjectUser::getType, params.getType());
        }
        List<ProjectUser> projectUserList = this.list(wrapper);

        List<Integer> userIds = projectUserList.stream().map(ProjectUser::getUserId).collect(Collectors.toList());
        if (userIds.size() == 0) {
            IPage<ProjectUser> tem = new Page<>();
            tem.setSize(10);
            tem.setTotal(0);
            return tem;
        }
        PasUserDTO pasUserDTO = new PasUserDTO();
        pasUserDTO.setUserIds(userIds);
        pasUserDTO.setUsername(params.getUsername());
        pasUserDTO.setName(params.getName());
        pasUserDTO.setCurrent(params.getCurrent());
        pasUserDTO.setSize(params.getSize());
        String res = oAuth2Service.getPASAssignedUser(pasUserDTO);
        JSONObject jsonObject = JSONObject.parseObject(res);
        IPage<ProjectUser> pageList = new Page<>();
        pageList.setTotal(Integer.parseInt(jsonObject.get("total").toString()));
        pageList.setSize(Integer.parseInt(jsonObject.get("size").toString()));
        List<PasUserVO> records = JSONArray.parseArray(jsonObject.get("records").toString(), PasUserVO.class);
        List<ProjectUser> list = new ArrayList<>();
        for (PasUserVO item : records) {
            ProjectUser projectUser = projectUserList.stream().filter(tem -> tem.getUserId().equals(item.getId())).findFirst().orElse(new ProjectUser());
            projectUser.setName(item.getName());
            projectUser.setUsername(item.getUsername());
            list.add(projectUser);
        }
        //根据
        //根据人员姓名，id，账号，分页信息查询人员
        pageList.setRecords(list);
        return pageList;
    }

    @Transactional
    public String add(ProjectUser projectUser) {
        if (projectUser.getUserIds() != null && projectUser.getUserIds().size() != 0) {
            List<Integer> tempList = this.getListByProIdAndUserIds(projectUser.getUserIds(), projectUser.getProjectId()).stream().map(ProjectUser::getUserId).collect(Collectors.toList());
            List<ProjectUser> userList = new ArrayList<>();
            projectUser.getUsers().forEach(item -> {
                ProjectUser user = new ProjectUser();
                user.setUserId(item.getUserId());
                user.setProjectId(projectUser.getProjectId());
                user.setCreateTime(DateUtils.getDateTime());
                user.setRemark(projectUser.getRemark());
                user.setType(projectUser.getType());
                user.setTenantId(item.getTenantId());
                if (!tempList.contains(item.getUserId())) {
                    userList.add(user);
                }
            });
            if (userList.size() != 0) {
                this.saveOrUpdateBatch(userList);
            }
            return Response.success();
        } else {
            projectUser.setCreateTime(DateUtils.getDateTime());
            projectUser.insert();
            return Response.success(projectUser.getId());
        }
    }

    public String edit(ProjectUser projectUser) {
        projectUser.updateById();
        return Response.success();
    }

    public String delete(Integer id) {
        this.removeById(id);
        return Response.success();
    }

    public void deleteByProjectId(Integer projectId) {
        this.remove(Wrappers.<ProjectUser>lambdaQuery().eq(ProjectUser::getProjectId, projectId));
    }
}
