import { chartType, fieldsNames, searchCompType } from '.';
import { getFormTemplate } from '/@/api/form/design';
import { noHaveField } from '/@/components/Designer';
import { httpRequest } from '/@/api/sys/api';
import { getToken } from '/@/utils/auth';
import { getRequestData } from '/@/utils/event/pagetool';
import { cloneDeep } from 'lodash-es';

export const getTableComponents = (list, formList) => {
  list.forEach((item) => {
    if (['vertical', 'horizontal', 'normal', 'collapse', 'panel', 'tab'].includes(item.type)) {
      for (const child of item.layout!) {
        getTableComponents(child.list, formList);
      }
    } else if (item.type === 'table-layout') {
      for (const child of item.layout!) {
        for (const list of child.list) {
          getTableComponents(list.children, formList);
        }
      }
    } else {
      formList.push(item);
    }
  });
};

export const getComponents = (list, returnArr, parentKey?) => {
  list.forEach((item) => {
    if (['grid', 'card', 'tab'].includes(item.type)) {
      for (const child of item.layout!) {
        getComponents(child.list, returnArr, parentKey);
      }
    } else if (item.type === 'table-layout') {
      for (const child of item.layout!) {
        for (const list of child.list) {
          getComponents(list.children, returnArr, parentKey);
        }
      }
    } else if (!noHaveField.includes(item.type)) {
      returnArr.push({
        label: item.label,
        value: JSON.stringify({
          bindField: item.bindField,
          parentKey: parentKey,
        }),
      });
    }
  });
};

export const getCurPageComponents = (
  formList,
  tableComp,
  searchComp,
  formsComp,
  treeComp,
  refreshComponent?,
  isFilter = true,
) => {
  formList.forEach((item: any) => {
    let flag = isFilter ? false : true;
    if (refreshComponent) flag = refreshComponent?.includes(item.key);
    if (item.type == 'list' && flag) {
      const columns = item.options.columns || [];
      const newColumn = columns.map((o) => {
        return {
          label: o.title,
          value: JSON.stringify({
            dataIndex: o.dataIndex,
            parentKey: item.key,
          }),
        };
      });
      tableComp?.push({
        label: item.options.label,
        value: item.key,
        disabled: true,
        children: newColumn || [],
      });
    } else if (item.type == 'search' && flag) {
      const schemas = item.options.config || [];
      const newSchemas: any = [];
      schemas.map((o) => {
        const newO = cloneDeep(o);
        newO.parentKey = item.key;
        delete newO.name;
        if (o.type == searchCompType.cycle) {
          const obj = { ...o, bindField: o.bindField + 'Start' };
          newSchemas.push({
            label: o.name + '开始时间',
            value: JSON.stringify(obj),
          });
          const obj1 = { ...o, bindField: o.bindField + 'End' };
          newSchemas.push({
            label: o.name + '结束时间',
            value: JSON.stringify(obj1),
          });
        } else {
          newSchemas.push({
            label: o.name,
            value: JSON.stringify(newO),
          });
        }
      });
      searchComp?.push({
        label: item.options.label,
        value: item.key,
        disabled: true,
        children: newSchemas || [],
      });
    } else if (item.type == 'form' && flag) {
      if (item.options.formId) {
        try {
          getFormTemplate(item.options.formId).then((templateResult) => {
            const formJson = JSON.parse(templateResult.formJson);
            const schemas = [];
            getComponents(formJson.formJson.list, schemas, item.key);
            formsComp?.push({
              label: item.options.label,
              value: item.options.formId,
              disabled: true,
              children: schemas || [],
            });
          });
        } catch (error) {}
      }
    } else if (item.type == 'tree' && flag) {
      const newSchemas = fieldsNames.value?.map((o) => {
        o.parentKey = item.key;
        return {
          label: o.label,
          value: JSON.stringify(o),
        };
      });
      treeComp?.push({
        label: item.options.label,
        value: item.options.formId,
        disabled: true,
        children: newSchemas,
      });
    }
  });
};

export async function changePageDesignApiOptions(val, widgetFormModel?) {
  if (val.path) {
    try {
      const headers = { Authorization: `Bearer ${getToken()}` };
      if (val.requestHeaderConfigs.length > 0) {
        val.requestHeaderConfigs.forEach((element) => {
          if (element.name) headers[element.name] = getRequestData(element, widgetFormModel, true);
        });
      }
      let path = val.path;
      if (val.requestParamsConfigs.length > 0) {
        path += '?';
        val.requestParamsConfigs.forEach((element) => {
          if (element.name) path += `${element.name}=${getRequestData(element, widgetFormModel)}&`;
        });
      }
      const apiData = {};
      if (val.requestBodyConfigs.length > 0) {
        val.requestBodyConfigs.forEach((element) => {
          if (element.name) apiData[element.name] = getRequestData(element, widgetFormModel);
        });
      }
      const res = await httpRequest(
        {
          requestUrl: path,
          requestType: val.method,
        },
        {
          headers,
          data: apiData,
        },
      );

      return res;
    } catch (error) {}
  }
}

export async function refreshChart(apiConfig, config, widgetFormModel) {
  if (apiConfig?.path) {
    config.apiData = [];
    if (config.chartType === chartType.funnel) {
      config.echarts.legend.data = [];
      config.echarts.series[0].data = [];
    }
    if (apiConfig) {
      const res = await changePageDesignApiOptions(apiConfig, widgetFormModel);
      if (res.list && Array.isArray(res.list)) {
        config.apiData = res.list;
      }
    }
  }
}
