import { show } from "@/api/system/customForm";
import { listdept } from "@/api/system/department";
import { getparameter } from "@/api/system/dictionary";
import { index as baseFormIndex } from "@/api/system/baseForm";

export async function resolveFormInfo(customFormId,filterType = 'table') {
  const res = await show({ id: customFormId }, false);

  //字段处理
  //初始表白名单
  let baseTable = new Map([
    [
      "departments",
      async () => {
        const res = await listdept();
        return res;
      },
    ],
    ["admins", []],
  ]);
  let { fields, relation } = res;
  let fieldRes = fields.filter(i => {
    if (filterType === 'table') {
      return i.list_show;
    } else {
      return i.form_show;
    }
  }).sort((a, b) => a.sort - b.sort);
  if (
    !fields ||
    !relation ||
    !fields instanceof Array ||
    !relation instanceof Array
  ) {
    throw new Error("fields或relation格式错误");
  }
  fieldRes?.forEach((i, index) => {
    i._relations = relation.find(
      (j) => j.custom_form_field === i.field
    );
    if (i.select_item && typeof i.select_item === "object") {
      let keys = Object.keys(i.select_item);
      i._params = keys.map((key) => {
        return {
          key,
          value: /^\d*$/.test(i.select_item[key])
            ? Number(i.select_item[key])
            : i.select_item[key],
        };
      });
    }
    if (i.edit_input === "file" || i.edit_input === "files") {
      return;
    }
    if (i._relations) {
      if (baseTable.get(i._relations.link_table_name)) {
        baseTable
          .get(i._relations.link_table_name)()
          .then((res) => {
            i._params = res;
          });
      } else {
        i._params = i._relations.parameter_id
          ? getparameter({ id: i._relations.parameter_id }, false).then(
              (res) => {
                i._params = res.detail;
              }
            )
          : baseFormIndex({
              table_name: i._relations.link_table_name,
              page: 1,
              page_size: 9999,
            }).then((res) => {
              i._params = res.data;
            });
      }
    }
  });

  return fieldRes;
}
