import {Message} from 'element-ui';
import {dataapiDetail, openurl,optionList , enumCheck} from '@/api/report/report';
import {dictDetail} from './dict';
import {param} from "./config";
// 整理树结构
export const countTreeOptions = (originData) => {
  originData.forEach((i) => {
    i.children = [];
    i.KEY = i.ID || i.KEY || i.key || i.VALUE || i.value;
  });
  let parents = [...originData];
  let res = [], childrens = [];
  originData.forEach((i) => i.PID == "0" ? res.push(i) : childrens.push(i));
  childrens.forEach((i) => {
    let parent = parents.find((j) => j.ID == i.PID);
    if (parent) {
      parent.children.push(i);
    }
  });
  return res;
};
// 整理字典树结构
export const countDictTreeOptions = (node) => {
  if (node.children) {
    node.children = node.children.map(countDictTreeOptions);
  }
  node.KEY = node.key;
  node.VALUE = node.value;
  return node;
};
// 去掉子项空数组
export const clearChildren = node => {
  if (!node.children) return;
  if (!node.children.length) {
    delete node.children;
  } else {
    node.children.forEach(clearChildren);
  }
};
// 获取枚举可选值
export const getEnumData = (filter, cubeDataId, visualId, componentId, isEdit) => {
  let {enumSource, enumId} = filter;
  if (enumSource == "1") {
    filter.loading = true;
    let {tableName, columnName} = filter;
    if (!tableName || !columnName) {
      tableName = filter.column.tableName;
      columnName = filter.column.columnName;
    }
    if (isEdit) {
      enumCheck({tableName, columnName, cubeDataId}).then(() => {
        optionList({tableName, columnName, cubeDataId, visualId, componentId}).then((res) => {
          filter.options = res.data.data.map((i) => ({KEY: i[columnName], VALUE: i[columnName],}));
          filter.loading = false;
        });
      }).catch(() => {
        Message.warning('此数据集不支持原始数据聚合');
        filter.loading = false;
      });
    } else {
      optionList({tableName, columnName, cubeDataId, visualId, componentId}).then((res) => {
        filter.options = res.data.data.map((i) => ({KEY: i[columnName], VALUE: i[columnName],}));
        filter.loading = false;
      });
    }
  } else if (enumSource == "2") {
    if (!enumId) {
      return Message.warning('请选择api');
    }
    filter.loading = true;
    dataapiDetail(enumId).then((res) => {
      let {apiKey} = res.data.data;
      openurl(apiKey, param).then((res) => {
        filter.loading = false;
        let data = res.data.data;
        let hasChild = data.find(i => i.PID)
        if (hasChild) {
          let tree = countTreeOptions(data);
          tree.forEach(clearChildren);
          filter.options = tree;
        } else {
          filter.options = data.map(i => ({
            KEY: i.ID || i.KEY || i.key || i.VALUE || i.value,
            VALUE: i.VALUE || i.value
          }));
        }
      });
    });
  } else {
    if (!enumId) {
      return Message.warning('请选择字典');
    }
    dictDetail({id: enumId}).then((res) => {
      let tree = JSON.parse(res.data.data.content || "[]");
      tree = tree.map(countDictTreeOptions);
      tree.forEach(clearChildren);
      filter.options = tree;
    });
  }
};
export const onEnumSelectAll = filter => {
  let options = filter.options;
  let arr = [];
  options.forEach((i) => getOptionValue(arr, i));
  filter.conditions[0].values = arr;
};
export const getOptionValue = (arr, item) => {
  if (item.children) {
    item.children.forEach((i) => {
      getOptionValue(arr, i);
    });
  } else {
    arr.push(item.KEY);
  }
};
// 全局筛选器获取枚举可选值
export const getAllEnumData = (filter, isEdit, vm, value = {}) => new Promise((resolve, reject) => {
  if (!isEdit && filter.options.length) return resolve();
  let {enumSource, enumId} = filter;
  if (enumSource == "1") {
    if (vm) vm.OptionLoading = true;
    let opts = [];
    let charts = filter.chartList;
    if (isEdit) {
      charts = charts.filter((i) => i.select && !i.asValue);
    } else {
      charts = charts.filter((i) => !i.asValue);
    }
    let tasks = charts.map((i) => {
      if (isEdit) {
        return new Promise((r, j) => {
          let {tableName, columnName} = i.field;
          enumCheck({tableName, columnName, cubeDataId: i.cubeDataId,}).then(() => {
            optionList({
              tableName, columnName,
              cubeDataId: i.cubeDataId,
              visualId: vm ? vm.visualId || "" : '',
              componentId: vm ? vm.chartId || "" : '',
            }).then((res) => {
              opts = opts.concat(res.data.data.map((i) => i[columnName]));
              r();
            });
          }).catch(() => {
            Message({'message': '此数据集不支持原始聚合', type: 'warning'});
            j();
          });
        });
      } else {
        return new Promise((r, j) => {
          let {tableName, columnName} = i.field;
          optionList({
            tableName, columnName,
            cubeDataId: i.cubeDataId,
            visualId: vm ? vm.visualId || "" : '',
            componentId: vm ? vm.chartId || "" : '',
          }).then((res) => {
            opts = opts.concat(res.data.data.map((i) => i[columnName]));
            r();
          });
        });
      }
    });
    Promise.all(tasks).then(() => {
      filter.options = XEUtils.uniq(opts).map((i) => ({KEY: i, VALUE: i,}));
      resolve();
    }).finally((_) => {
      if (vm) vm.OptionLoading = false;
    });
  }
  if (enumSource == "2") {
    if (!enumId) return Message({message: "请选择api", type: "warning"});
    if (vm) vm.OptionLoading = true;
    dataapiDetail(enumId).then((res) => {
      let {apiKey} = res.data.data;
      openurl(apiKey, {...param, ...value}).then((res) => {
        if (vm) vm.OptionLoading = false;
        let data = res.data.data;
        let hasChild = data.find(i => i.PID)
        if (hasChild) {
          let tree = countTreeOptions(data);
          tree.forEach(clearChildren);
          filter.options = tree;
        } else {
          filter.options = data.map(i => ({
            KEY: i.ID || i.KEY || i.key || i.VALUE || i.value,
            VALUE: i.VALUE || i.value
          }));
        }
        resolve();
      });
    });
  }
  if (enumSource == "3") {
    if (!enumId) return Message({message: "请选择字典", type: "warning"});
    dictDetail({id: enumId}).then((res) => {
      let tree = JSON.parse(res.data.data.content || "[]");
      tree = tree.map(countDictTreeOptions);
      tree.forEach(clearChildren);
      filter.options = tree;
      resolve();
    });
  }
});
// 获取枚举可选值
export const filterGetEnumData = (filter, isEdit, filterList, vm) => {
  let value = {};
  if (filter.linkFrom && filter.linkKey) {
    let from = filterList.find(i => i.key == filter.linkFrom);
    if (from) {
      let val = from.conditions[0].values[0] || '';
      value = {[filter.linkKey]: val};
    }
  }
  return new Promise((resolve, reject) => {
    getAllEnumData(filter, isEdit, vm, value).then(res => {
      if (filter.enumSource == '2' && filter.useFirstOption) {
        if (filter.options.length) {
          filter.conditions[0].values = [filter.options[0].KEY];
        }
      }
      resolve();
    }).catch(reject);
  });
};
// 联动参数赋值的控件值改变时，相关控件重新拉取列表，并链式检查其是否也是赋值控件
export const onLinkSetHandle = (filter, filterList) => new Promise((resolveAll, rejectAll) => {
  // 找出受影响的条件
  let affected = filterList.filter(item => {
    if (item.enumSource != '2') return false;
    return item.linkFrom == filter.key && item.linkKey;
  });
  let tasks = affected.map(item => new Promise((resolve, reject) => {
    // 清空条件和可选值列表
    item.conditions[0].values = [''];
    item.options = [];
    // 只有当受影响的链式处理完，才算完成
    filterGetEnumData(item, false, filterList,).then(res => {
      if (item.linkSet) {
        onLinkSetHandle(item, filterList).then(resolve);
      } else {
        // 如果是最后一级才算完成
        resolve();
      }
    });
  }));
  Promise.all(tasks).then(resolveAll).catch(rejectAll);
});

export const transLayout = function (layout) {
  let h = 0
  return layout.map(i => {
    h += i.h
    return {
      ...i,
      x: 0,
      y: h - i.h,
      w: 24,
    }
  })
}
