package com.nokia.service;

import com.nokia.dao.AreaDao;
import com.nokia.dao.UserDao;
import com.nokia.pojo.Area;
import com.nokia.pojo.Role;
import com.nokia.pojo.User;
import com.nokia.vo.flow.FlowRoleVo;
import com.nokia.vo.flow.FlowUserVo;
import com.nokia.vo.flow.UserTreeReq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Service
public class FlowService {

    private final UserDao userDao;
    private final AreaDao areaDao;

    @Autowired
    public FlowService(UserDao userDao, AreaDao areaDao) {
        this.userDao = userDao;
        this.areaDao = areaDao;
    }

    public List<FlowRoleVo> findRoleList(String username) {
        return userDao.findRoleList(username);
    }

    public List<FlowRoleVo> findRoleList() {
        return userDao.findRoleList2();
    }

    public List<FlowUserVo> findToPage() {
        return userDao.findToPage();
    }

    public FlowUserVo getByLoginId(String loginId) {
        return userDao.getFlowUserVoByLoginId(loginId);
    }

    public FlowUserVo getByUserId(Integer userId) {
        return userDao.getFlowUserVoByUserId(userId);
    }

    public List<Integer> findRoleIdByUserId(Integer userId) {
        return userDao.findRoleIdByUserId(userId);
    }

    public List<Integer> findUserIdByRoleId(Integer roleId) {
        return userDao.findUserIdByRoleId(roleId);
    }

    public List<FlowUserVo> findAuthorizedUser(String loginId, Integer roleId, String userName) {
        return userDao.findAuthorizedUser(loginId, roleId, userName);
    }

    public List<Role> getRoleCityByUserId(Integer userId) {
        return userDao.getRoleCityByUserId(userId);
    }

    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> getUserTree(UserTreeReq userTreeReq) {
        // cityIds 用于查找用户 用户在叶子节点
        List<Integer> cityIds = new ArrayList<>();
        // areas 用于构建树结构的前两层
        List<Area> areas = new ArrayList<>();
        // 这里检查一下查找条件的role不为空
        List<Integer> queryRoles = (userTreeReq.getRole() == null || userTreeReq.getRole().size() == 0) ? null
                : userTreeReq.getRole();
        if (userTreeReq.getCity() == -1 || queryRoles == null) {
            // 如果这里给的是河北省 或者 role 为空，那么需要取全部
            areas = areaDao.getAll();
        } else {
            // 都需要添加省级用户
            areas.add(areaDao.getByAreaId(-1));
            // 添加对应的地市
            areas.add(areaDao.getByAreaId(userTreeReq.getCity()));
            // 添加地市对应的区县
            areas.addAll(areaDao.getByParentId(userTreeReq.getCity()));
        }
        // query用的cityIds
        if (userTreeReq.getCity() == -1) {
            // 如果这里给的是河北省，那么需要取全部
            cityIds = null;
        } else {
            cityIds.add(-1);
            cityIds.add(userTreeReq.getCity());
        }
        // 组织结果
        List<Map<String, Object>> result = new ArrayList<>();
        // 用于记录第一层排序
        Map<Integer, Integer> top = new HashMap<>();
        // 用于记录第二层排序
        Map<Integer, Integer> second = new HashMap<>();
        for (int i = 0; i < areas.size(); i++) {
            if (areas.get(i).getTypeCode() == 1) {
                // 省
                // 第一层
                Map<String, Object> map1 = new LinkedHashMap<>();
                map1.put("name", areas.get(i).getAreaName());
                map1.put("child", new ArrayList<>());
                result.add(map1);
                // 记录第一层排序
                top.put(areas.get(i).getAreaId(), i);
                // 第二层
                Map<String, Object> map2 = new LinkedHashMap<>();
                map2.put("name", "省公司");
                map2.put("child", new ArrayList<>());
                ((List<Object>) map1.get("child")).add(map2);
            } else if (areas.get(i).getTypeCode() == 2) {
                // 地市
                // 第一层
                Map<String, Object> map1 = new LinkedHashMap<>();
                map1.put("name", areas.get(i).getAreaName());
                map1.put("child", new ArrayList<>());
                result.add(map1);
                // 记录第一层排序
                top.put(areas.get(i).getAreaId(), i);
                // 第二层
                Map<String, Object> map2 = new LinkedHashMap<>();
                map2.put("name", "市公司");
                map2.put("child", new ArrayList<>());
                ((List<Object>) map1.get("child")).add(map2);
            } else {
                // 区县，仅第二层
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("name", areas.get(i).getAreaName());
                map.put("child", new ArrayList<>());
                // 加入到第二层
                List<Object> list = (List<Object>) result.get(top.get(areas.get(i).getParentId())).get("child");
                list.add(map);
                // 记录第二层排序
                second.put(areas.get(i).getAreaId(), list.size() - 1);
            }
        }

        // 查询符合条件的用户
        List<User> users = userDao.getByRoleIds(queryRoles, cityIds);
        // key 区域（市公司或区域） value 一个列表，列表内放区域内全部的用户信息
        Map<Area, Object> userMap = new LinkedHashMap<>();
        // 将用户归类
        for (User user : users) {
            Map<String, Object> map = new LinkedHashMap<>();
            // 获取用户区县，如果区县为空则获取用户地市
            Area area = user.getArea() == null ? user.getCity() : user.getArea();
            map.put("name", area.getAreaName());
            map.put("userName", user.getUserName());
            map.put("userId", user.getUserId());
            map.put("child", new ArrayList<>());
            // 把 map 放入 列表中
            List<Object> userList = ((List<Object>) userMap.getOrDefault(area, new ArrayList<>()));
            userList.add(map);
            userMap.put(area, userList);
        }
        // 把归类后的用户放入第三层
        for (Entry<Area, Object> entry : userMap.entrySet()) {
            if (entry.getKey().getTypeCode() < 3) {
                // 第一层的child
                List<Map<String, Object>> list = (List<Map<String, Object>>) result
                        .get(top.get(entry.getKey().getAreaId())).get("child");
                // 省级和地市级用户
                list.get(0).put("child", entry.getValue());
            } else {
                // 第一层的child
                List<Map<String, Object>> list = (List<Map<String, Object>>) result
                        .get(top.get(entry.getKey().getParentId())).get("child");
                // 区县级用户
                list.get(second.get(entry.getKey().getAreaId())).put("child", entry.getValue());
            }
        }
        // 只保留叶子节点不为空的
        // 组织结果
        for (Map<String, Object> map1 : result) {
            List<Map<String, Object>> list1 = (List<Map<String, Object>>) map1.get("child");
            for (int i = 0; i < list1.size(); i++) {
                List<Map<String, Object>> list2 = (List<Map<String, Object>>) list1.get(i).get("child");
                if (list2.size() == 0) {
                    list1.remove(i);
                    i--;
                }
            }
        }
        return result;
    }
}
