package com.yeejoin.amos.knowledgebase.face.feign;

import com.google.common.base.Joiner;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.DataNotFound;

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

public class RemoteData {
    /**
     * 根据用户id Set集合查询对应的用户姓名
     *
     * @param userIds
     * @return Map
     */
    public static Map<String, String> getUserMap(Set<String> userIds) {
        String join = Joiner.on(",").join(userIds);
        try {
            List<AgencyUserModel> agencyUserModelList = FeignUtil.remoteCall(() -> Privilege.agencyUserClient.queryByIds(join, false));
            Map<String, String> userMap = agencyUserModelList.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));
            return userMap;
        } catch (Exception e) {

        }
        return Collections.emptyMap();
    }

    /**
     * 根据用户id查询对应的用户姓名
     *
     * @param userId
     * @return Map
     */
    public static String getUserRealNamById(String userId) {
        if (ValidationUtil.isEmpty(userId)) {
            return null;
        }
        try {
            AgencyUserModel user = FeignUtil.remoteCall(() -> Privilege.agencyUserClient.queryByUserId(userId));
            if (!ValidationUtil.isEmpty(user)) {
                return user.getRealName();
            }
        } catch (Exception e) {

        }
        return null;
    }


    public static List<DictionarieValueModel> queryDict(String enumName) throws Exception {
        return FeignUtil.remoteCall(() -> Systemctl.dictionarieClient.dictValues(enumName));
    }


    /**
     * 获取当前操作者对应角色下的部门信息
     *
     * @param roleName 角色名
     * @return 部门
     */
    public static String getOrgWithCurUserAndRole(String roleName) {
        Map<String, String> roleOrgMap = getCurUserOrgRoleMap();
        return roleOrgMap.get(roleName);
    }


    private static Map<String, String> getCurUserOrgRoleMap() {
        Map<String, String> resMap = new HashMap<>();
        try {
            AgencyUserModel agencyUserModel = FeignUtil.remoteCall(() -> Privilege.agencyUserClient.queryByUserId(RequestContext.getExeUserId()));
            Map<Long, List<RoleModel>> rolesMap = agencyUserModel.getOrgRoles();

            //组装部门信息为Map
            Map<Long, DepartmentModel> departmentMap = new HashMap<>();
            for (List<DepartmentModel> departments : agencyUserModel.getCompanyDepartments().values()) {
                if (ValidationUtil.isEmpty(departments)) {
                    continue;
                }
                Iterator<DepartmentModel> iterator = departments.iterator();
                while (iterator.hasNext()) {
                    DepartmentModel next = iterator.next();
                    if (!ValidationUtil.isEmpty(next)) {
                        departmentMap.put(next.getSequenceNbr(), next);
                    }
                }
            }
            //组装单位信息为Map
            Map<Long, CompanyModel> companyMap = new HashMap(Bean.listToMap(agencyUserModel.getCompanys(), "sequenceNbr", CompanyModel.class));

            Map<Long, List<Long>> orgRoleMap = agencyUserModel.getOrgRoleSeqs();
            for (Long orgKey : orgRoleMap.keySet()) {
                List<RoleModel> roleModels = rolesMap.get(orgKey);
                for (RoleModel roleModel : roleModels) {
                    String orgCode = null;
                    if (departmentMap.containsKey(orgKey)) {
                        orgCode = departmentMap.get(orgKey).getOrgCode();
                    } else if (companyMap.containsKey(orgKey)) {
                        orgCode = companyMap.get(orgKey).getOrgCode();
                    } else {
                        throw new DataNotFound("用户角色数据丢失");
                    }
                    resMap.put(roleModel.getRoleName(), orgCode);
                }
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return resMap;
    }
}
