import { flattenDeep } from "lodash";
import { treeHelper } from "@zenview/micro-utils";
import { vehicleType } from "./index";
import Service from "../service";

const getLabelType = async () => {
  let labelType = [];
  let personLabel = [];
  let vehicleLabel = [];
  try {
    const result = await Service.getKvStoreByKey({
      storeKey: "LABEL_TYPE",
    });
    const list = JSON.parse(result.data.storeValue)|| [];
    labelType = list.filter(
      (v) =>
        v.name === "basicAttributes" ||
        v.name === "identity" ||
        v.name === "appearanceRule" ||
        v.name === "spatioTemporalLaw" ||
        v.name === "behaviorRule"
    );
    personLabel = list.filter(
      (v) =>
        v.name === "basicAttributes" ||
        v.name === "identity" ||
        v.name === "behaviorRule"
    );

    vehicleLabel = list.filter(
      (v) =>
        v.name === "vehicleIdentity" || v.name === "vehicleSpatioTemporalLaw"
    );
  } catch (e) {
    console.error("字典配置缺失", e);
    labelType = [];
    personLabel = [];
    vehicleLabel = [];
  }
  return {
    labelType,
    personLabel,
    vehicleLabel,
  };
};

const formartTagCodes = (list, labelType, isNoTree) => {
  list.forEach(item => {
    item.value = item.code = item.dicCode;
    item.typeCode = item.superTag;
    item.label = item.tagName;
    const group = labelType.find(v => v.value.indexOf(item.tagGroup) > -1);
    if (group) {
      item.tagColor = group.color;
    }
  });
  if (isNoTree) {
    return list;
  }
  return treeHelper.computTreeList(list, "code", "typeCode");
}

export const getPersonTagList = async (isNoTree = true) => {
  let labelList = await getLabelType()
  let labelType = labelList.labelType
  let tagGroups = flattenDeep(labelType.map(v => v.value));
  let res = await Service.getTagsByCondition({ tagGroups });
  return formartTagCodes(res.data,labelType, isNoTree);
}

const getPersonGroupTags = async (tags = []) => {
  let labelList=await getLabelType()
  let labelType = labelList.labelType
  tags.forEach(tag => {
    labelType.forEach(item => {
      if (item.value.indexOf(tag.tagGroup) > -1) {
        if (Array.isArray(item.children)) {
          item.children.push(tag);
        } else {
          item.children = [tag];
        }
      }
    });
  });
  return labelType;
}

export const getVehicleTagList = async (isNoTree = true)=> {
  let tagGroups = flattenDeep(vehicleType.map(v => v.value));
  let res = await Service.getTagsByCondition({ tagGroups });
  return formartTagCodes(res.data,[], isNoTree);
}

const FileUtils ={
  getPersonTagList,
  getPersonGroupTags,
  getVehicleTagList
}

export default FileUtils;
