<template>
  <div class="search">
    <el-form
      ref="formRef"
      :model="searchForm"
      :label-width="searchConfig.labelWidth || 100"
      size="large"
      class="search-form"
    >
      <!-- 第一行：筛选项（自动换行，每行3列） -->
      <el-row :gutter="12" class="form-row">
        <template v-for="item in searchConfig.formItems" :key="item.prop">
          <!-- 响应式列：大屏3列，中屏2列，小屏1列 -->
          <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, computed } 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';

// 初始化数据
const formRef = ref<InstanceType<typeof ElForm>>();
const systemStore = useSystemStore();
const sharedValueStore = useSharedValueStore();
const { searchObj } = storeToRefs(systemStore);
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 initialForm: Record<string, any> = {};
for (const item of props.searchConfig.formItems) {
  initialForm[item.prop] = item.initialValue ?? '';
}
const searchForm = reactive<Record<string, any>>(initialForm);

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

// 重置表单
const handleResetClick = () => {
  formRef.value?.resetFields();
  // 重置为初始值
  Object.assign(searchForm, initialForm);
  fetchPageListData();
  sharedValueStore.upDatePageNum(2);
};

// 查询表单
const handleQueryClick = async () => {
  // 格式化日期范围（如需要）
  props.searchConfig.formItems.forEach(item => {
    if (item.type === 'date-picker' && searchForm[item.prop]) {
      searchForm[item.prop][0] = parseTimeWithCheck(searchForm[item.prop][0]);
      searchForm[item.prop][1] = parseTimeWithCheck(searchForm[item.prop][1]);
    }
    if (item.type === 'date-month' && searchForm[item.prop]) {
      searchForm[item.prop][0] = dayjs(searchForm[item.prop][0]).format('YYYY-MM');
      searchForm[item.prop][1] = dayjs(searchForm[item.prop][1]).format('YYYY-MM');
    }
  });

  await fetchPageListData(searchForm);
  searchObj.value = { ...searchForm };
  sharedValueStore.upDatePageNum(2);
  emit('handleSure');
};

// 请求列表数据
function fetchPageListData(queryInfo: Record<string, any> = {}) {
  systemStore.pageInfo.pageNum = 1;
  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,
  });
}

// 工具函数：格式化时间
function parseTimeWithCheck(value: any) {
  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; /* 微调列间距，避免 gutter 过大 */
  }

  /* 表单项目样式 */
  .el-form-item {
    margin-bottom: 0;
    padding: 5px 0; /* 减少内部 padding，避免行高过大 */

    .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>