<template>
    <div class="search">
        <!-- 1.1.表单输入 -->
        <el-form :model="searchForm" ref="formRef"
            :label-width="searchConfig.labelWidth ? searchConfig.labelWidth : 100" size="large">
            <el-row :gutter="16">
                <template v-for="item in searchConfig.formItems" :key="item.prop">
                    <el-col :span="8">
                        <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]" :placeholder="item.placeholder"
                                    :disabled="item.disabled">
                                    <template v-for="i in item.options" :key="i.label">
                                        <el-option :label="i.label" :value="i.value" />
                                    </template>
                                </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>
                        </el-form-item>
                    </el-col>
                </template>
                <!-- 1.2.搜索按钮  -->
                <el-col :span="spanLength" class="flex-b">
                    <div></div>
                    <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 } 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 userStore = useUserStore().userInfo.userName === 'admin' ? '' : useUserStore().userInfo.userId;

interface IProps {
    searchConfig: {
        pageName: string;
        status: string;
        createUser: string;
        oneself: number;
        formItems: any[];
        labelWidth?: number;
        pageListParams?: {};
    };
}
const props = defineProps<IProps>();
const emit = defineEmits(['datePickerChange', 'handleSure']);
// 请求数据
const systemStore = useSystemStore();
const sharedValueStore = useSharedValueStore();
const { searchObj } = storeToRefs(systemStore);
function updateValue(newVal: any) {
    sharedValueStore.updateSharedValue(newVal);
}
const pageNumValue = computed(() => sharedValueStore.pageNum);
const pageSizeValue = computed(() => sharedValueStore.pageSize);
const pageNum = systemStore.pageInfo.pageNum;
const pageSize = systemStore.pageInfo.pageSize;
const energyDates = ref([]);
// 禁用早于当前月份的选项
const disabledDate = (date) => {
    // 获取当前时间的年月
    const current = new Date();
    const currentYear = current.getFullYear();
    const currentMonth = current.getMonth(); // 月份范围 0-11

    // 传入的日期（月份选择器会传入该月的第一天，如 2023-10-01）
    const year = date.getFullYear();
    const month = date.getMonth();

    // 判断逻辑：年份小于当前年，或同年且月份小于当前月
    return year > currentYear || (year === currentYear && month >= currentMonth);
};
// 获取列表
function fetchPageListData(queryInfo: any = {}) {

    systemStore.pageInfo.pageNum = 1;
    // 2.发生网络请求
    systemStore.getPageListDataAction(props.searchConfig.pageName, {
        pageNum: 1,
        pageSize: pageSize,
        userId: userStore,
        status: props.searchConfig.status,
        createUser: props.searchConfig.createUser,
        oneself: props.searchConfig.oneself,
        ...queryInfo,
        ...props.searchConfig.pageListParams,
    });
}

// 1.创建表单的数据
const initialForm: any = {};
for (const item of props.searchConfig.formItems) {
    initialForm[item['prop']] = item['initialValue'] ?? '';
}
let searchForm = reactive(initialForm);

if (props.searchConfig.status !== '') {
    for (const item of props.searchConfig.formItems) {
        if (item['prop'] === 'status') {
            searchForm[item['prop']] = props.searchConfig.status;
        }
    }
}

// 2.监听按钮的点击
const formRef = ref<InstanceType<typeof ElForm>>();
function handleResetClick() {
    formRef.value?.resetFields();
    fetchPageListData();
    sharedValueStore.upDatePageNum(2);
}

function parseTimeWithCheck(value) {
    // 如果已经是期望的格式（8 位数字），则直接返回
    if (/^\d{8}$/.test(value)) {
        return value;
    }
    return parseTime(value)?.slice(0, 10).replaceAll('-', '');
}
async function handleQueryClick() {
    updateValue(searchForm);
    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]);
        }
    });
    props.searchConfig.formItems.forEach(item => {
        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');
}

const spanLength = computed(() => {
    const length = ref(0);
    if (props.searchConfig.formItems.length % 3 === 0) {
        length.value = 24;
    } else if (props.searchConfig.formItems.length % 3 === 1) {
        length.value = 16;
    } else if (props.searchConfig.formItems.length % 3 === 2) {
        length.value = 8;
    }
    return length.value;
});

const onDatePickerChange = (date: any) => {
    emit('datePickerChange', date);
};
const getMonthDate = (ent: any, prop: any) => {
};
defineExpose({
    searchForm,
    fetchPageListData,
    handleResetClick,
    handleQueryClick,
});
</script>

<style scoped lang="scss">
.search {
    background-color: #fff;
    // margin-top: 20px;
    padding-bottom: 20px;
    border-radius: 5px;

    .el-form-item {
        padding: 15px 20px;
        margin-bottom: 0;
    }

    .el-select--large {
        width: 22vw;
    }
}

.btns {
    margin-top: 19px;
    text-align: right;
    padding-right: 20px !important;
}
</style>
