/*
 * Author: Zev
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.paln.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.api.DepartmentClient;
import com.tofly.api.UserClent;
import com.tofly.common.oauth.auth.ToflyUser;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.pojo.plan.vo.GroupUserAllVo;
import com.tofly.pojo.plan.vo.GroupUserDeptVo;
import com.tofly.pojo.plan.vo.GroupuserVo;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.plan.GroupuserMapper;
import com.tofly.gpsboot.service.config.InspectgroupService;
import com.tofly.pojo.User;
import com.tofly.pojo.plan.Groupuser;
import com.tofly.gpsboot.service.paln.GroupuserService;
import com.tofly.pojo.plan.Inspectgroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 巡查分组配置信息表：TF_YWPN_GROUPUSER_W
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@Service("groupuserService")
public class GroupuserServiceImpl extends ServiceImpl<GroupuserMapper, Groupuser> implements GroupuserService {

    @Autowired
    private UserClent userClent;

    @Autowired
    private DepartmentClient departmentClient;

    @Autowired
    private InspectgroupService inspectgroupService;


    @Override
    public List<GroupuserVo> viewConversion(List<Groupuser> infoList) {
        List<GroupuserVo> infoVoList = new ArrayList<>();
        infoList.forEach(info -> {
            GroupuserVo baseInfo = JSONObject.parseObject(JSON.toJSONString(info), GroupuserVo.class);
            String userId = baseInfo.getUserId();
            if (!StringUtils.isEmpty(userId)) {
                User result = userClent.getById(Long.valueOf(userId)).getResult();
                if(null!=result){
                    baseInfo.setUserIdName(result.getRealName());
                }

            }
            baseInfo.setGroupName(inspectgroupService.getById(info.getGroupId()).getName());
            infoVoList.add(baseInfo);
        });
        return infoVoList;
    }


    @Override
    public Map<Long, String> getGroupUserIdNameMap(Long id) {
        List<Groupuser> list = this.list(new QueryWrapper<Groupuser>().lambda().eq(Groupuser::getGroupId, id));

        if (null == list) {
            throw new BusinessException(Constant.GROUP_USER_NOT_NULL_CODE, Constant.GROUP_USER_NOT_NULL);
        }
        List<Long> collect = list.stream().map(m -> Long.valueOf(m.getUserId().trim())).collect(Collectors.toList());
        Map<Long, String> map = new HashMap<>(12);
        collect.forEach(info -> map.put(info, userClent.getById(info).getResult().getRealName()));
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public GroupUserAllVo saveUpdateGroupUserInfo(List<Groupuser> groupUserList) {
        // 清空对应部门下的数据
        ToflyUser toflyUser = SecurityUtils.getUser();
        Long departmentId = toflyUser.getDepartmentId();
        if(null == departmentId){
            throw new BusinessException(Constant.IS_DEPT_NOT_USER_NULL_CODE,Constant.IS_DEPT_NOT_USER_NULL);
        }
        List<Long> inspectGroupIdList = inspectgroupService.list(new QueryWrapper<Inspectgroup>().lambda().eq(Inspectgroup::getDeptId, departmentId)).stream().map(Inspectgroup::getId).collect(Collectors.toList());

        this.remove(new QueryWrapper<Groupuser>().lambda().in(Groupuser::getGroupId,inspectGroupIdList));
        groupUserList.forEach(this::save);

        return this.getGroupUserMap();
    }
    @Override
    public GroupUserAllVo getGroupUserMap() {
        GroupUserAllVo userAllVo = new GroupUserAllVo();
        // 获取当前用户下的部门的用户列表
        ToflyUser toflyUser = SecurityUtils.getUser();
        Long departmentId = toflyUser.getDepartmentId();
        if(null == departmentId){
            throw new BusinessException(Constant.IS_DEPT_NOT_USER_NULL_CODE,Constant.IS_DEPT_NOT_USER_NULL);
        }
        List<User> nowUserList = departmentClient.getDeptUserList(String.valueOf(departmentId)).getResult();

        List<GroupUserDeptVo> lostUserList = new ArrayList<>();
        // 获取分组信息列表
        List<Inspectgroup> inspectGroupList = inspectgroupService.list(new QueryWrapper<Inspectgroup>().lambda().eq(Inspectgroup::getDeptId, departmentId));
        if(null == inspectGroupList || inspectGroupList.size()==0){
            nowUserList.forEach(user->{
                GroupUserDeptVo vo = new GroupUserDeptVo();
                vo.setUserId(user.getId());
                vo.setUserName(user.getRealName());
                vo.setDeptId(user.getDepartmentId());
                vo.setDeptName(user.getDepartmentName());
                lostUserList.add(vo);
            });
            userAllVo.setGroupUserVoList(new ArrayList<>());
            userAllVo.setGroupUserDeptVoList(lostUserList);
            return userAllVo;
        }
        List<Long> inspectGroupIdList = inspectGroupList.stream().map(Inspectgroup::getId).collect(Collectors.toList());
        List<Groupuser> groupUserList = this.list(new QueryWrapper<Groupuser>().lambda().in(Groupuser::getGroupId,inspectGroupIdList));
        if(null != groupUserList && groupUserList.size()>0){
            List<String> userListInfo = groupUserList.stream().map(Groupuser::getUserId).collect(Collectors.toList());
            nowUserList.forEach(user ->{
                if(!userListInfo.contains(String.valueOf(user.getId()))){
                    GroupUserDeptVo vo = new GroupUserDeptVo();
                    vo.setUserId(user.getId());
                    vo.setUserName(user.getRealName());
                    vo.setDeptId(user.getDepartmentId());
                    vo.setDeptName(user.getDepartmentName());
                    lostUserList.add(vo);
                }
            });
            // 若当前组没有绑定用户,则也需要展示
            List<Groupuser> addList = new ArrayList<>();
            Set<Long> groupUserGroupList = groupUserList.stream().map(s -> Long.parseLong(s.getGroupId())).collect(Collectors.toSet());
            inspectGroupIdList.forEach(in ->{
                if(!groupUserGroupList.contains(in)){
                    Groupuser g = new Groupuser();
                    g.setGroupId(String.valueOf(in));
                    addList.add(g);
                }
            });
            groupUserList.addAll(addList);
            userAllVo.setGroupUserVoList(this.viewConversion(groupUserList));
        }else {
            nowUserList.forEach(user->{
                GroupUserDeptVo vo = new GroupUserDeptVo();
                vo.setUserId(user.getId());
                vo.setUserName(user.getRealName());
                vo.setDeptId(user.getDepartmentId());
                vo.setDeptName(user.getDepartmentName());
                lostUserList.add(vo);
            });
            List<Groupuser> newGroupUserList = new ArrayList<>();
            inspectGroupList.forEach(group ->{
                Groupuser g = new Groupuser();
                g.setGroupId(String.valueOf(group.getId()));
                newGroupUserList.add(g);
            });
            userAllVo.setGroupUserVoList(this.viewConversion(newGroupUserList));
        }

        userAllVo.setGroupUserDeptVoList(lostUserList);


        return userAllVo;
    }
}
