import { http } from '/nerv-lib/util/http';

let dictionary: any;
let dicCodeValueMap: any;
export function getDicCodeValue() {
  asyncLoadDictTree();
  return dicCodeValueMap;
}
export function getDictionary() {
  return dictionary;
}
export function asyncLoadDictTree(): Promise<any> {
  return http
    .get('/api/community/objs/DictTree')
    .then((res) => {
      if (res) {
        const response = res;
        if (response && response['success']) {
          const mainMap = {};
          const codeValueMap = {};
          transferData(response, 'data', mainMap);
          setCodeValueMap(response, 'data', codeValueMap);
          dicCodeValueMap = codeValueMap;
          dictionary = mainMap;
          return mainMap;
        }
      }
    })
    .catch((error) => {
      console.log(error);
    });
}
export function transferData(data, attri, mainMap): {} {
  const objs = data[attri];
  if (objs && objs instanceof Array && objs.length > 0) {
    objs.forEach((it) => {
      mainMap[it['dictCode']] = it;
      mainMap[it['dictCode'] + '_' + 'name'] = it['dictName'];
      if (it['subList'] && it['subList'] instanceof Array) {
        mainMap[it['dictCode'] + '_' + 'subList'] = it['subList'];
        transferData(it, 'subList', mainMap);
      } else {
        mainMap[it['dictCode'] + '_' + 'subList'] = [];
        return;
      }
    });
  } else {
    return '';
  }
}
export function setCodeValueMap(data: any, attri: any, map: any) {
  const objs = data[attri];
  if (objs && objs instanceof Array && objs.length > 0) {
    objs.forEach((it) => {
      map[it['dictParentCode'] + '_' + it['dictValue']] = it['dictName'];
      map[it['dictParentCode'] + '_' + it['dictCode']] = it['dictName'];
      if (it['subList'] && it['subList'] instanceof Array) {
        setCodeValueMap(it, 'subList', map);
      } else {
        // map[it['dictParentCode'] + '_' + it['dictCode']] = '';
        // map[it['dictParentCode'] + '_' + it['dictValue']] = '';
        return;
      }
    });
  } else {
    return;
  }
}
/**
 * 根据code和value获取显示名
 * @param code 字典code
 * @param value 值
 */
export function getCodeNameFromValue(code, value): string {
  console.log(code, value, 'code, value');
  const name =
    getDicCodeValue() && getDicCodeValue()[code + '_' + value]
      ? getDicCodeValue()[code + '_' + value]
      : '';
  return name;
}