<template>
  <div class="search">
    <el-form
      ref="formRef"
      :model="searchForm"
      :label-width="searchConfig.labelWidth || 100"
      size="large"
      class="search-form"
    >
      <!-- 第一行：筛选项 -->
      <el-row :gutter="12" class="form-row">
        <template v-for="item in searchConfig.formItems" :key="item.prop">
          <el-col :span="item.span || 6" class="form-col">
            <el-form-item :label="item.label" :prop="item.prop">
              <template v-if="item.type === 'input'">
                <el-input v-model="searchForm[item.prop]" :placeholder="item.placeholder" />
              </template>
              <template v-if="item.type === 'select'">
                <el-select
                  v-model="searchForm[item.prop]"
                  collapse-tags
                  filterable
                  :multiple="item.multiple || false"
                  :placeholder="item.placeholder"
                  :disabled="item.disabled"
                >
                  <el-option 
                    v-for="i in item.options" 
                    :key="i.value" 
                    :label="i.label" 
                    :value="i.value" 
                  />
                </el-select>
              </template>
              <template v-if="item.type === 'date-picker'">
                <el-date-picker
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  v-model="searchForm[item.prop]"
                  @change="onDatePickerChange"
                />
              </template>
              <template v-if="item.type === 'date-month'">
                <el-date-picker
                  v-model="searchForm[item.prop]"
                  type="monthrange"
                  range-separator="-"
                  :disabled-date="disabledDate"
                  placeholder="请选择费用周期"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  @change="getMonthDate($event, item.prop)"
                />
              </template>
              <template v-if="item.type === 'custom'">
                <slot 
                  :name="item.slotName" 
                  :value="searchForm[item.prop]"
                  @input="(newVal) => searchForm[item.prop] = newVal"
                ></slot>
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>

      <!-- 第二行：按钮区域 -->
      <el-row class="btn-row">
        <el-col :span="24">
          <div class="btns">
            <el-button size="default" @click="handleResetClick">重置</el-button>
            <el-button size="default" type="primary" @click="handleQueryClick">查询</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="page-search">
import type { ElForm } from 'element-plus';
import { reactive, ref, defineProps, defineEmits, watch, nextTick } from 'vue';
import useSystemStore from '@/store/main';
import useUserStore from '@/store/modules/user';
import { parseTime } from '@/utils/ruoyi';
import dayjs from 'dayjs';
import { useSharedValueStore } from './sharedValueStore';
import { storeToRefs } from 'pinia';

// 初始化数据
const formRef = ref<InstanceType<typeof ElForm>>();
const systemStore = useSystemStore();
const sharedValueStore = useSharedValueStore();
const { searchObj, pageList } = storeToRefs(systemStore); // 监听 pageList 变化
const userStore = useUserStore().userInfo.userName === 'admin' ? '' : useUserStore().userInfo.userId;

// Props 定义
interface IProps {
  searchConfig: {
    pageName: string;
    status: string;
    createUser: string;
    oneself: number;
    formItems: Array<{
      prop: string;
      label: string;
      type: 'input' | 'select' | 'date-picker' | 'date-month' | 'custom';
      placeholder?: string;
      initialValue?: any;
      multiple?: boolean;
      disabled?: boolean;
      options?: Array<{ label: string; value: any }>;
      span?: number;
      slotName?: string
    }>;
    labelWidth?: number;
    pageListParams?: Record<string, any>;
  };
}
const props = defineProps<IProps>();
const emit = defineEmits(['datePickerChange', 'handleSure']);

// 动态生成初始值
const generateInitialForm = () => {
  const form: Record<string, any> = {};
  props.searchConfig.formItems.forEach(item => {
    form[item.prop] = item.initialValue === undefined ? '' : structuredClone(item.initialValue);
  });
  return form;
};

// 初始化表单数据
let initialForm = generateInitialForm();
const searchForm = reactive<Record<string, any>>(initialForm);

// 监听表单配置变化，动态更新初始值
watch(
  () => props.searchConfig.formItems,
  () => {
    initialForm = generateInitialForm();
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = initialForm[key];
    });
  },
  { deep: true }
);

// 禁用日期（月份选择器）
const disabledDate = (date: Date) => {
  const current = new Date();
  return date.getFullYear() > current.getFullYear() || 
    (date.getFullYear() === current.getFullYear() && date.getMonth() > current.getMonth());
};

const handleResetClick = async () => {
  if (formRef.value) {
    await formRef.value.resetFields(); 
  }

  const newInitialForm = generateInitialForm();
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = newInitialForm[key]; // 避免直接替换对象导致响应式失效
  });

  // 3. 等待数据更新完成后再请求
  await nextTick(); 
  fetchPageListData(); // 请求初始数据
  sharedValueStore.upDatePageNum(2); // 同步页码状态
};

const handleQueryClick = async () => {
  const formattedSearchForm = { ...searchForm };
  props.searchConfig.formItems.forEach(item => {
    if (item.type === 'date-picker' && formattedSearchForm[item.prop]) {
      formattedSearchForm[item.prop] = [
        parseTimeWithCheck(formattedSearchForm[item.prop][0]),
        parseTimeWithCheck(formattedSearchForm[item.prop][1])
      ];
    }
    if (item.type === 'date-month' && formattedSearchForm[item.prop]) {
      formattedSearchForm[item.prop] = [
        dayjs(formattedSearchForm[item.prop][0]).format('YYYY-MM'),
        dayjs(formattedSearchForm[item.prop][1]).format('YYYY-MM')
      ];
    }
  });

  // 2. 等待数据格式化完成后请求
  await nextTick(); 
  await fetchPageListData(formattedSearchForm); // 等待请求完成
  searchObj.value = { ...formattedSearchForm }; // 解构赋值触发 Pinia 状态更新
  sharedValueStore.upDatePageNum(2);
  emit('handleSure');
};

async function fetchPageListData(queryInfo: Record<string, any> = {}) {
  systemStore.pageInfo.pageNum = 1;

  try {
    const res = await systemStore.getPageListDataAction(
      props.searchConfig.pageName,
      {
        pageNum: 1,
        pageSize: systemStore.pageInfo.pageSize,
        userId: userStore,
        status: props.searchConfig.status,
        createUser: props.searchConfig.createUser,
        oneself: props.searchConfig.oneself,
        ...queryInfo,
        ...props.searchConfig.pageListParams,
      }
    );
    await nextTick(); 
    return res;
  } catch (error) {
    console.error('请求列表数据失败:', error);
    throw error;
  }
}

// 工具函数：格式化时间（带空值检查）
function parseTimeWithCheck(value: any) {
  if (!value) return '';
  if (/^\d{8}$/.test(value)) return value;
  return parseTime(value)?.slice(0, 10).replaceAll('-', '') || '';
}

// 日期选择器change事件
const onDatePickerChange = (date: any) => {
  emit('datePickerChange', date);
};

const getMonthDate = (event: any, prop: string) => {
  // 月份选择器处理逻辑（根据业务需求补充）
};

// 暴露方法
defineExpose({
  searchForm,
  fetchPageListData,
  handleResetClick,
  handleQueryClick,
});
</script>

<style scoped lang="scss">
.search {
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 5px;
  overflow: hidden;

  .search-form {
    width: 100%;
  }

  .form-row {
    margin-bottom: 15px;
  }

  .form-col {
    padding: 0 8px;
  }

  .el-form-item {
    margin-bottom: 0;
    padding: 5px 0;

    .el-form-item__content {
      width: 100%;
    }
  }

  :deep(.el-input--large),
  :deep(.el-select--large) {
    width: 100% !important;
    min-width: 200px;
  }

  .btn-row {
    .btns {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      padding: 10px 0;
    }
  }

  @media (max-width: 768px) {
    .form-col {
      padding: 0 4px;
    }
    .el-form-item {
      padding: 8px 0;
    }
  }
}
</style>