<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 = {} } = useAppStoreHook();

//初始表格数据
const defaultFormData = createFormData(props.formConfig.formItems);
const isHide = props.formConfig.isHide;
const formData = ref({
  ...(searchParams.basic ? searchParams.basic : defaultFormData)
});

//重置搜索
function handleResetClick() {
  formData.value = { ...defaultFormData };
  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 (startProp || endProp) {
      formData.value[field] = [
        searchParams.basic[startProp],
        searchParams.basic[endProp]
      ];

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

<template>
  <div class="w-99/100">
    <div class="bg-white pl-4 pt-4 page-search" v-show="!isHide">
      <BasicForm v-bind="formConfig" v-model:form-data="formData">
        <template #action>
          <div style="width: 100%" flex gap-2>
            <el-button
              type="primary"
              :icon="useRenderIcon('search')"
              @click="handleSearchClick"
            >
              搜索
            </el-button>

            <el-button
              :icon="useRenderIcon('refresh')"
              @click="handleResetClick"
            >
              重置
            </el-button>
            <slot name="action" />
          </div>
        </template>
      </BasicForm>
    </div>
  </div>
</template>
