<template>
  <component
    :is="column?.render ?? `el-${column?.el}`"
    v-bind="{ ...handleSearchProps, ...placeholder, searchParam, clearable }"
    v-model.trim="searchParam[column?.key ?? handleProp(field!)]"
    :data="column?.el === 'tree-select' ? columnEnum : []"
    :options="['cascader', 'select-v2'].includes(column?.el!) ? columnEnum : []"
    :enum="enumData"
    :column="column"
    :status="orderStatus"
  >
    <template #default="{ data }" v-if="column?.el === 'cascader'">
      <span>{{ data[fieldNames.label] }}</span>
    </template>
    <template v-if="column?.el === 'select'">
      <component
        :is="`el-option`"
        v-for="(col, index) in columnEnum"
        :key="index"
        :label="col[fieldNames.label]"
        :value="col[fieldNames.value]"
      ></component>
    </template>
    <template v-else-if="column?.el === 'checkbox-group'">
      <component :is="`el-checkbox-button`" v-for="(col, index) in columnEnum" :key="index" :label="col[fieldNames.value]">{{
        col[fieldNames.label]
      }}</component>
    </template>
    <template v-else-if="column?.el === 'radio-group'">
      <component :is="`el-radio-button`" v-for="(col, index) in columnEnum" :key="index" :label="col[fieldNames.value]">{{
        col[fieldNames.label]
      }}</component>
    </template>
    <slot v-else></slot>
    <template #label="scope" v-if="column?.el === 'tree-select'">
      {{ getSimpleParentNodes(scope.value) }}
    </template>
    <template #decrease-icon v-if="column?.el === 'input-number'">
      <el-icon><Minus /></el-icon>
    </template>
    <template #increase-icon v-if="column?.el === 'input-number'">
      <el-icon><Plus /></el-icon>
    </template>
  </component>
</template>

<script setup lang="tsx" name="BaseFormItem">
import { computed, inject, ref } from "vue";
import { handleProp } from "@/utils";
import { isArray, isObject } from "@/utils/is";
// import { ColumnProps } from "../interface";
import { useI18n } from "vue-i18n";
import { FieldNamesProps } from "@/components/LjVxeTable/interface/index";
import { Minus, Plus } from "@element-plus/icons-vue";

const { t } = useI18n();

interface BaseFormItem {
  field?: string | undefined;
  column: any;
  fieldNames?: FieldNamesProps;
  searchParam: { [key: string]: any };
}

const props = withDefaults(defineProps<BaseFormItem>(), {
  fieldNames: () => ({
    label: "label",
    value: "value",
    children: "children"
  })
});

// 判断 fieldNames 设置 label && value && children 的 key 值
// const fieldNames = computed(() => {
//   return {
//     label: props.fieldNames?.label ?? "label",
//     value: props.fieldNames?.value ?? "value",
//     children: props.fieldNames?.children ?? "children"
//   };
// });

// /**
//  * @description 是否可编辑
//  */
// const ifCanEditable = inject("editable");

/**
 * @description 是否可编辑
 */
const orderStatus = inject("orderStatus");

// 接收 enumMap (el 为 select-v2 需单独处理 enumData)
const enumMap = inject("mainEnumMap", ref(new Map()));
const enumData = computed(() => {
  return enumMap.value.get(props.field) ?? [];
});
const columnEnum = computed(() => {
  let enumData = enumMap.value.get(props.field);
  // console.log("enumData :>> ", enumData, props.field, enumMap.value);
  if (!enumData) return [];
  if (props.column?.el === "select-v2" && props.fieldNames) {
    enumData = enumData.map((item: { [key: string]: any }) => {
      return { ...item, label: item[props.fieldNames.label], value: item[props.fieldNames.value] };
    });
  }
  console.log("columnEnum enumData :>> ", enumData, props.field, props.fieldNames, enumMap.value);
  if (isObject(enumData) && enumData.hasOwnProperty("data")) {
    return enumData.data;
  } else {
    return enumData;
  }
});

// 处理透传的 searchProps (el 为 tree-select、cascader 的时候需要给下默认 label && value && children)
const handleSearchProps = computed(() => {
  const label = props.fieldNames.label;
  const value = props.fieldNames.value;
  const children = props.fieldNames.children;
  const searchEl = props.column?.el;
  let searchProps = props.column?.props ?? {};
  if (searchEl === "tree-select") {
    searchProps = { ...searchProps, props: { ...searchProps.props, label, children }, nodeKey: value };
  }
  if (searchEl === "cascader") {
    searchProps = { ...searchProps, props: { ...searchProps.props, label, value, children } };
  }
  return searchProps;
});

// 处理默认 placeholder
const placeholder = computed(() => {
  const search = props.column;
  if (["datetimerange", "daterange", "monthrange"].includes(search?.props?.type) || search?.props?.isRange) {
    return { rangeSeparator: t("common.to"), startPlaceholder: t("common.starttime"), endPlaceholder: t("common.endtime") };
  }
  const placeholder =
    search?.props?.placeholder ?? (search?.el?.includes("input") ? t("common.inputText") : t("common.chooseText"));
  return { placeholder };
});

// 是否有清除按钮 (当搜索项有默认值时，清除按钮不显示)
const clearable = computed(() => {
  const search = props.column;
  return search?.props?.clearable ?? (search?.defaultValue == null || search?.defaultValue == undefined);
});

/**
 * @description 查找父级节点
 * @param tree 数据源
 * @param targetId 目标值
 * @param key 目标字段
 * @param path
 */
const findParentNodes = (tree, targetId, key = "id", path = []) => {
  for (const node of tree) {
    if (node[key] === targetId) {
      return [...path, node];
    }
    if (node.children.length > 0) {
      const result = findParentNodes(node.children, targetId, key, [...path, node]);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

/**
 * @description 显示父级节点名称
 * @param tree 数据源
 * @param targetId 目标值
 * @param key 目标字段
 */
const getSimpleParentNodes = targetId => {
  console.log("getSimpleParentNodes :>> ", columnEnum.value, targetId, props.fieldNames.value);
  let parentNodes = findParentNodes(columnEnum.value, targetId, props.fieldNames.value);
  if (!parentNodes) {
    return null;
  }
  parentNodes = parentNodes.map(node => {
    let item = { ...node };
    delete item.children;
    return item;
  });

  return parentNodes.map(node => node.mtrltype).join(" >> ");
};
</script>
