<template>
    <!-- 日期时间 -->
    <datetime
        v-bind="start"
        v-model="formItem.value"
        :format="listItem.date.type"
        :placeholder="listItem.placeholder"
        @on-change="verify().catch(() => {})"
    >
        <template slot="title">
            <div class="label">
                <slot></slot>
            </div>
        </template>
    </datetime>
</template>

<script>
import common from '@/common/formRender/mixin/common.js'
import { Datetime, dateFormat } from 'vux'
export default {
    name: 'FormDate',
    mixins: [common],
    components: { Datetime },
    props: {
        listItem: { type: Object, default: () => ({}) },
        formItem: { type: Object, default: () => ({}) }
    },
    data () {
        // 限制日期范围不能为过去
        return {
            start: {
                'start-date': this.listItem.verify.startNow
                    ? dateFormat(Date.now(), 'YYYY/MM/DD')
                    : dateFormat('1900/01/01', 'YYYY/MM/DD')
            }
        }
    },
    created () {
        this.verifyInit()
        this.listItem.date.type = this.listItem.date.type.replace(/yyyy|dd/g, res => res.toUpperCase())
        // 初始化选中值（1 指定，2 当天，3 日前，4 日后）
        const { type, value, valueType } = this.listItem.date
        if (valueType === 1) this.formItem.value = value || ''
        else if (valueType === 2) this.formItem.value = dateFormat(new Date(), type)
        else if (valueType === 3 && value) this.formItem.value = this.getDate(('-' + value) - 0, type)
        else if (valueType === 4 && value) this.formItem.value = this.getDate(value - 0, type)
    },
    methods: {
        // 获取日前日后多少天
        getDate (day, type) {
            const date = new Date()
            date.setDate(date.getDate() + day)
            return dateFormat(date, type)
        },
        // 校验初始化
        verifyInit () {
            const rules = []
            const { required } = this.listItem.verify
            if (required) rules.push(this.required(this.listItem.title))
            if (rules.length) this.validator = new this.Schema({ value: rules })
        },
        // 校验
        verify () {
            return this.validate({ value: this.formItem.value })
        }
    }
}
</script>

<style lang="less" scoped>
</style>
