<template>
    <!-- 日期区间 -->
    <el-form label-width="auto" ref="form" :model="formItem.value" :style="{ 'margin-left': `-${labelWidth}` }">
        <el-form-item
            :label="`${listItem.title}：`"
            prop="start"
            :rules="rules('start', listItem.title)"
            :info.prop="info(listItem.title, formItem.value.start, '', formItem.hide)"
        >
            <el-date-picker
                v-model="formItem.value.start"
                :type="dateType[listItem.date.type]"
                :placeholder="listItem.placeholder"
                :format="listItem.date.type"
                :value-format="listItem.date.type"
                :picker-options="{ disabledDate: disabledStart }"
            ></el-date-picker>
        </el-form-item>
        <el-form-item
            :label="`${listItem.title2}：`"
            prop="end"
            :rules="rules('end', listItem.title2)"
            :info.prop="info(listItem.title2, formItem.value.end, '', formItem.hide)"
        >
            <el-date-picker
                v-model="formItem.value.end"
                :type="dateType[listItem.date.type]"
                :placeholder="listItem.placeholder2"
                :format="listItem.date.type"
                :value-format="listItem.date.type"
                :picker-options="{ disabledDate: disabledEnd }"
            ></el-date-picker>
        </el-form-item>
        <el-form-item
            class="time"
            :label="`${listItem.date.title}：`"
            :info.prop="info(listItem.date.title, formItem.value.result, '', formItem.hide)"
            v-if="listItem.date.time"
        >
            {{ formItem.value.result ? formItem.value.result + formItem.value.type : '-' }}
        </el-form-item>
    </el-form>
</template>

<script>
import mixin from '../mixin.js'
import { differ } from '@/assets/utils/time.js'
export default {
    name: 'FormDateRange',
    props: {
        listItem: { type: Object, default: () => ({}) },
        formItem: { type: Object, default: () => ({}) }
    },
    mixins: [mixin],
    data () {
        return {
            timer: null,
            labelWidth: 0,
            dateType: {
                'yyyy/MM/dd HH:mm': 'datetime',
                'yyyy/MM/dd HH': 'datetime',
                'yyyy/MM/dd': 'date',
                'yyyy/MM': 'month',
                'yyyy': 'year'
            },
            time: '', // 时长

            // 单位
            unit: {
                '天': 'd',
                '小时': 'h',
                '分钟': 'm'
            }
        }
    },
    watch: {
        // 监听计算时长
        'formItem.value.start': function () {
            this.calcTime()
        },
        'formItem.value.end': function () {
            this.calcTime()
        },
        // 同步时长
        time (time) {
            if (this.listItem.date.time) this.formItem.value.result = time
        },
        // 被单选隐藏后再次获取 labelWidth
        'formItem.hide': function (hide) {
            if (!this.labelWidth && !hide) {
                setTimeout(() => {
                    this.labelWidth = this.$refs.form.autoLabelWidth
                })
            }
        }
    },
    mounted () {
        // 子表单靠左对齐
        setTimeout(() => {
            this.labelWidth = this.$refs.form.autoLabelWidth
        })
    },
    methods: {
        // 限制开始日期的范围（ - 8.64e7 + 1 为一天）
        disabledStart (pickerDate) {
            const end = new Date(this.formItem.value.end)
            if (this.listItem.verify.startNow) {
                return end > 0
                    ? pickerDate < Date.now() - 8.64e7 + 1 || pickerDate > end
                    : pickerDate < Date.now() - 8.64e7 + 1
            } else {
                return end > 0 ? pickerDate > end : false
            }
        },
        // 限制结束日期的范围（ - 8.64e7 + 1 为一天）
        disabledEnd (pickerDate) {
            const start = new Date(this.formItem.value.start)
            if (this.listItem.verify.startNow) {
                return start > 0
                    ? pickerDate < Math.max(start - 8.64e7 + 1, Date.now() - 8.64e7 + 1)
                    : pickerDate < Date.now() - 8.64e7 + 1
            } else {
                return start > 0 ? pickerDate < start - 8.64e7 + 1 : false
            }
        },
        // 计算时长
        calcTime () {
            if (this.listItem.date.time) {
                const { start, end } = this.formItem.value
                const startTime = new Date(start).getTime()
                const endTime = new Date(end).getTime()
                if (startTime > 0 && endTime > 0) {
                    if (endTime - startTime < 0) {
                        this.time = ''
                    } else if (endTime - startTime === 0) {
                        this.time = '0'
                    } else {
                        const format = this.unit[this.listItem.date.unit]
                        if (!this.listItem.date.removeRest) {
                            this.time = format ? differ({ start, end, format, digit: 1 }) - 0 + '' : ''
                        } else {
                            // 降低请求频率
                            clearTimeout(this.timer)
                            this.timer = setTimeout(() => {
                                this.$api.commonApi.formJudgeLeaveDay({
                                    start_time: start,
                                    end_time: end,
                                    contains_resttime: 1, // 0 包含休息时间, 1 排除休息时间
                                    type: format === 'd' ? 0 : format === 'h' ? 1 : 2 // 0 天, 1 小时, 2 分钟
                                }).then(res => {
                                    this.time = res.data.Status ? res.data.Data + '' : ''
                                })
                            }, 600)
                        }
                    }
                }
            }
        },
        // 获取校验规则
        rules (type, title) {
            const rules = []
            if (this.listItem.verify.required) rules.push(this.required(title)) // mixin
            if (type === 'start') rules.push(this.dateStart())
            if (type === 'end') rules.push(this.dateEnd())
            return rules
        },
        // 开始时间校验
        dateStart () {
            return {
                trigger: ['change', 'blur'],
                validator: (rule, value, callback) => {
                    const start = new Date(this.formItem.value.start)
                    const end = new Date(this.formItem.value.end)
                    const { title, title2 } = this.listItem
                    start > 0 && end > 0 && start > end
                        ? callback(new Error(title + '不能晚于' + title2))
                        : callback()
                }
            }
        },
        // 结束时间校验
        dateEnd () {
            return {
                trigger: ['change', 'blur'],
                validator: (rule, value, callback) => {
                    const start = new Date(this.formItem.value.start)
                    const end = new Date(this.formItem.value.end)
                    const { title, title2 } = this.listItem
                    start > 0 && end > 0 && start > end
                        ? callback(new Error(title2 + '不能早于' + title))
                        : callback()
                }
            }
        },
        // 提交校验
        verify () {
            return new Promise((resolve, reject) => {
                this.$refs.form.validate(valid => {
                    valid ? resolve() : reject(new Error('dateRange 错误'))
                })
            })
        }
    }
}
</script>

<style lang="less" scoped>
.time /deep/ .el-form-item__label::before {
    opacity: 0;
}
</style>
