import * as request from '../../utils/request';
import config from '../../config/config';

export function getAllotDepartments(params) {
  return request.get(`${config.authorize_api.getAllotDepartments}`, params);
}

export function getAllotPosts(params) {
  return request.get(`${config.authorize_api.getAllotPosts}`, params);
}

export function getAllotRoles(params) {
  return request.get(`${config.authorize_api.getAllotRoles}`, params);
}

export function onAllotCorrelate(params) {
  return request.post(`${config.authorize_api.onAllotCorrelate}`, params);
}

export function getAllotAuthorizeDetail(params) {
  return request.get(`${config.authorize_api.getAllotAuthorizeDetail}`, params);
}

export function deleteAllots(params) {
  return request.get(`${config.authorize_api.deleteAllots}`, params);
}

export function resolveAllotRecord(data, radioValue) {
  let correlateRecord = null, correlateSelectedKeys = null;
  if ("department" == radioValue) {
    let map = new Map();
    resolveAllotTree(data, map);
    correlateRecord = map.get("allotRecord");
    correlateSelectedKeys = map.get("selectedKeys");
  } else {
    correlateRecord = data[0];
    correlateSelectedKeys = [correlateRecord.id];
  }
  return {correlateRecord, correlateSelectedKeys};
}

const resolveAllotTree = (data, map) => {
  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item.children) {
      resolveAllotTree(item.children, map);
    } else {
      if (map.size == 0) {
        map.set("allotRecord", item);
      }
    }

    let selectedKeys = map.get("selectedKeys");
    if (selectedKeys) {
      selectedKeys.push(item.id);
      map.set("selectedKeys", selectedKeys);
    } else {
      const array = new Array();
      array.push(item.id);
      map.set("selectedKeys", array);
    }
  }
}
