<template>
    <simple-form-modal
        title="新增下架任务"
        labelWidth="120px"
        :items="formItems"
        ref="editRef"
        :baseUrl="baseUrl"
        @success="(data) => emit('success', data)"
        :formatData="formatData"
    >
        <template #maxOrderNum> 时拆分任务 </template>
        <template #customSelect="{ item, model, updateValue }">
            <div class="flex items-center gap-2 w-full">
                <el-select
                    class="w-[100px] flex-1"
                    v-model="model.timeType"
                    :placeholder="item.label"
                    @change="updateValue"
                >
                    <el-option
                        v-for="option in item.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                    />
                </el-select>
                <el-radio-group
                    v-model="formData.timeRangeType"
                    @change="handleTimeRangeChange"
                >
                    <el-radio label="今天" :value="1" />
                    <el-radio label="近7天" :value="2" />
                    <el-radio label="近30天" :value="3" />
                </el-radio-group>
            </div>
        </template>
    </simple-form-modal>
</template>

<script setup>
    import { reactive, ref, defineEmits, getCurrentInstance, watch } from 'vue';
    import SimpleFormModal from '@/components/CommonPage/SimpleFormModal.vue';
    import dayjs from 'dayjs';
    const { proxy } = getCurrentInstance();

    //获取仓库
    const godownList = ref([]);
    const emit = defineEmits(['success']);

    const formItems = computed(() => {
        return [
            {
                type: 'select',
                label: '仓库名称',
                prop: 'godownId',
                required: true,
                options: godownList.value.map((d) => {
                    return { label: d.godownName, value: d.id };
                }),
                props: {
                    placeholder: '请选择或输入搜索',
                    filterable: true
                }
            },
            {
                type: 'select',
                label: '录入员',
                prop: 'taskUser',
                options: [],
                props: {
                    placeholder: '请输入搜索',
                    filterable: true,
                    remote: true,
                    multiple: true,
                    remoteMethod: (query) => {
                        proxy.$http
                            .get('/system/user/list', {
                                params: { pageSize: 200 }
                            })
                            .then((res) => {
                                const users = res.data.rows || [];
                                formItems.value[1].options = users.map(
                                    (user) => ({
                                        label: user.nickName,
                                        value: user.userId
                                    })
                                );
                            });
                    },
                    reserveKeyword: true
                }
            },
            {
                type: 'input',
                label: '任务明细大于',
                prop: 'maxOrderNum',
                required: true,
                slots: {
                    append: 'maxOrderNum'
                },
                props: {
                    min: 1,
                    placeholder: '请输入'
                }
            },
            {
                type: 'radio',
                label: '是否按人员拆分',
                prop: 'splitByUser',
                required: true,
                options: [
                    { label: '是', value: 1 },
                    { label: '否', value: 0 }
                ]
            },
            {
                type: 'customSelect',
                label: '时间类型',
                prop: 'timeType',
                required: true,
                options: [
                    { label: '验货时间', value: 1 },
                    { label: '入库时间', value: 2 },
                    { label: '打款时间', value: 3 }
                ]
            },
            {
                type: 'daterange',
                label: '时间范围',
                prop: 'timeRange',
                required: true,
                props: {
                    valueFormat: 'YYYY-MM-DD HH:mm:ss',
                    format: 'YYYY-MM-DD HH:mm:ss',
                    rangeSeparator: '至',
                    onChange: (value) => {
                        formData.value.startTime = value?.[0] || '';
                        formData.value.endTime = value?.[1] || '';
                    }
                }
            }
        ];
    });

    //默认值
    const baseUrl = reactive({
        add: '/baseinfo/stocktask/add'
    });
    const formData = ref({
        splitByUser: 1,
        timeType: 1,
        taskUser: [],
        timeRangeType: 1,
        timeRange: []
    });

    function handleTimeRangeChange(value) {
        console.log(value);
        const now = dayjs();
        const end = now.endOf('day').format('YYYY-MM-DD HH:mm:ss');

        let start;
        switch (value) {
            case 1: // 今天
                start = now.startOf('day').format('YYYY-MM-DD HH:mm:ss');
                break;
            case 2: // 近7天
                start = now
                    .subtract(6, 'day')
                    .startOf('day')
                    .format('YYYY-MM-DD HH:mm:ss');
                break;
            case 3: // 近30天
                start = now
                    .subtract(29, 'day')
                    .startOf('day')
                    .format('YYYY-MM-DD HH:mm:ss');
                break;
        }

        formData.value.startTime = start;
        formData.value.endTime = end;
        formData.value.timeRange = [start, end];
        editRef.value?.setData(formData.value);
    }

    const editRef = ref(null);

    function handleOpen() {
        getStoreList().then((res) => {
            godownList.value = res.data.data;
        });
        // 加载初始用户数据
        getUserList();
        handleTimeRangeChange(1);
        editRef.value?.handleOpen(formData.value);
    }

    function getStoreList(name = '') {
        return proxy.$http.post(`/baseinfo/godown/searchGodown?name=${name}`);
    }

    const formatData = (data) => {
        let dataCopy = JSON.parse(JSON.stringify(data));
        dataCopy.startTime = data.timeRange[0];
        dataCopy.endTime = data.timeRange[1];
        delete dataCopy.timeRange;
        return dataCopy;
    };

    function getUserList() {
        proxy.$http.get('/system/user/list').then((res) => {
            const users = res.data.rows || [];
            formItems.value[1].options = users.map((user) => ({
                label: user.nickName,
                value: user.userId
            }));
        });
    }

    defineExpose({ handleOpen });
</script>
