<template>
    <el-form :model="formData" ref="formRef" label-width="auto" :rules="rules">
        <div class="flex items-baseline flex-col">
            <el-form-item label="请选择开始和结束时间:" prop="endTime" class="mt-6">
                <el-time-picker
                    v-model="formData.startTime"
                    placeholder="开始时间"
                    value-format="HH:mm"
                    format="HH:mm"
                    class="h-[45px]"
                />
                <el-time-picker
                    v-model="formData.endTime"
                    placeholder="结束时间"
                    value-format="HH:mm"
                    format="HH:mm"
                    class="h-[45px]"
                />
            </el-form-item>
            <el-form-item label="请输入时间段:" prop="timeDuation" class="ml-7 mt-10">
                <el-input
                    class="w-[400px] ls-input h-[45px]"
                    v-model.trim="formData.timeDuation"
                    placeholder="时间段"
                >
                    <template #append>
                        <span>分</span>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="请输入间隔时间:" prop="timeInterval" class="ml-7 mt-10">
                <el-input
                    class="w-[400px] ls-input h-[45px]"
                    v-model.trim="formData.timeInterval"
                    placeholder="间隔时间"
                >
                    <template #append>
                        <span>分</span>
                    </template>
                </el-input>
            </el-form-item>
        </div>
    </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, toRaw } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { validateGoodsTime } from '@/utils/validate'
const props = withDefaults(
    defineProps<{
        orderTimeList?: any
    }>(),
    {
        orderTimeList: {}
    }
)
const formData = ref({
    startTime: '',
    endTime: '',
    timeDuation: '',
    timeInterval: ''
})

// 表单验证
const rules = reactive<FormRules>({
    endTime: [
        { required: true, trigger: 'blur', message: '请选择开始时间和结束时间' },
        {
            validator: (...args) => validTime(args),
            trigger: 'blur'
        }
    ],
    timeDuation: [
        { required: true, trigger: 'blur', message: '请输入时间段' },
        { validator: (...args) => validateGoodsTime(args), trigger: 'blur' }
    ],
    timeInterval: [
        { required: true, trigger: 'blur', message: '请输入间隔时间' },
        { validator: (...args) => validateGoodsTime(args), trigger: 'blur' }
    ]
})
const validTime = args => {
    const [, value, callback] = args
    if (!formData.value.startTime || !formData.value.endTime) {
        callback('请选择时间')
    } else if (formData.value.startTime > formData.value.endTime) {
        callback('结束时间不能小于开始时间')
    } else {
        callback()
    }
}

const getMinutes = (val: string) => {
    const [hour, minutes] = val.split(':')
    return parseInt(hour * 60) + parseInt(minutes)
}

const switchMinuteToHour = (val: number) => {
    return `${Math.floor(val / 60)}:${(val % 60).toString().padEnd(2, '0')}`
}

const getTimeArray = () => {
    const data = toRaw(formData.value)
    const parseIntTimeduration = parseInt(data.timeDuation)
    let s_time = getMinutes(data.startTime)
    let e_time = getMinutes(data.endTime)
    const t_interval = parseInt(data.timeInterval)
    let arr = []
    while (s_time + parseIntTimeduration <= e_time) {
        arr.push({
            startTime: switchMinuteToHour(s_time),
            endTime: switchMinuteToHour(s_time + parseIntTimeduration)
        })
        s_time += t_interval
    }
    return arr
}

const emit = defineEmits(['update:orderTimeList'])

watch(formData.value, val => {
    const keys = Object.keys(formData.value)
    const isEmpty = keys.some(i => !formData.value[i])
    let newArr: Array<Object> = []
    if (!isEmpty) {
        newArr = getTimeArray()
    }
    const formValue = toRaw(formData.value)
    emit('update:orderTimeList', {
        orderTimeList: newArr,
        serviceTime: formValue.timeDuation || '',
        endTime: formValue.endTime || '',
        intervalTime: formValue.timeInterval || '',
        startTime: formValue.startTime || ''
    })
})
watch(
    () => props.orderTimeList,
    val => {
        formData.value.startTime = val?.startTime
        formData.value.endTime = val?.endTime
        formData.value.timeDuation = val?.serviceTime
        formData.value.timeInterval = val?.intervalTime
    },
    {
        deep: true,
        immediate: true
    }
)

// 保存时校验，不通过时显示提示
const formRef = ref()
const validateData = () => {
    formRef.value?.validate()
}

defineExpose({
    validateData
})
</script>
<style scoped lang="scss">
:deep(.el-date-editor.el-input) {
    width: 224px;
    margin-right: 10px;
    .el-input__wrapper {
        width: 100%;
    }
}
:deep(.el-form-item__label) {
    height: 45px;
    line-height: 45px;
}
:deep(.el-date-editor.el-input .el-input__wrapper) {
    height: 45px;
}
:deep(.el-date-editor.el-input) {
    height: 45px;
}
</style>
