<script setup lang="ts">
import { ref } from "vue";
import { BasicForm } from "/@/components/BasicForm";
import { useRenderIcon } from "../../ReIcon/src/hooks";
import { createFormData } from "./utils/create-form-data";
import { useAppStoreHook } from "/@/store/modules/app";
import { searchFormProps } from "./types";

const props = defineProps(searchFormProps);
const emit = defineEmits(["searchBtnClick", "resetBtnClick"]);

const { searchParams = {} as any } = useAppStoreHook();

//初始表格数据
const defaultFormData = createFormData(props.formConfig.formItems);

const formData = ref({
  ...(searchParams.basic ? searchParams.basic : defaultFormData)
});

//重置搜索
function handleResetClick() {
  formData.value = createFormData(props.formConfig.formItems);
  emit("resetBtnClick");
}

//搜索
function handleSearchClick() {
  emit("searchBtnClick", formData.value);
}

if (searchParams.basic) {
  const { formConfig } = props;
  const { formItems } = formConfig;
  formItems.forEach(item => {
    const { field, otherOptions = {} } = item;
    const { startProp, endProp } = otherOptions;

    if (item.type === "input_group") {
      const origin = new Set(
        item.otherOptions?.inputGroupOptions.map(({ value }) => value)
      );

      const keys = new Set(Object.keys(searchParams.basic));

      const interset = [...new Set([...origin].filter(x => keys.has(x)))];

      if (interset.length === 0) {
        formData.value[item.type_field] =
          item.otherOptions?.inputGroupOptions[0]?.value;
        formData.value[item.field] = "";
      } else {
        formData.value[item.type_field] = interset[0];
        formData.value[item.field] = searchParams.basic[interset[0] as any];
      }
    }

    if (startProp || endProp) {
      formData.value[field] = [
        searchParams.basic[startProp],
        searchParams.basic[endProp]
      ];

      delete formData.value[startProp];
      delete formData.value[endProp];
    }
  });
}
</script>

<template>
  <div class="bg-white pl-4 pt-4 page-search">
    <BasicForm v-bind="formConfig" v-model:form-data="formData" size="small" @trigger-blur="handleSearchClick">
      <slot name="custom" />

      <template #action>
        <div style="width: 100%" flex gap-2>
          <el-button type="primary" :icon="useRenderIcon('refresh-right')" @click="handleSearchClick">
            刷新
          </el-button>

          <el-button :icon="useRenderIcon('refresh')" @click="handleResetClick">
            重置
          </el-button>

          <slot name="action" />
        </div>
      </template>
    </BasicForm>
  </div>
</template>
