<template>
    <div class="add-renewal-wrap">
        <el-form 
            :model="ruleForm" 
            :rules="rules" 
            ref="ruleForm" 
            label-width="100px" 
            class="demo-ruleForm"
        >
            <el-form-item label="运维时间" prop="signDate">
                <el-date-picker
                    v-model="ruleForm.signDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                />
            </el-form-item>
            <el-form-item label="到期时间" prop="expirationDate">
                <el-date-picker
                    v-model="ruleForm.expirationDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                />
            </el-form-item>
            <div style="text-align:center;margin:30px 0">
                <el-button type="primary" plain @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
            </div>
        </el-form>
    </div>
</template>

<script>
export default {
    props:{
        renewalForm:{
            type:Object,
            default:()=>{
                return {}
            }
        }
    },
    watch:{
        renewalForm:{
            handler:function(value){
                if(value.id){
                    this.ruleForm.id = value.id || 0
                    this.ruleForm.signDate = value.signDate || ''
                    this.ruleForm.expirationDate = value.expirationDate || ''
                }
            },
            immediate:true
        }
    },
    data() {
        return {
            rules:{
                signDate:[{required: true, message: '请选择运维时间', trigger: 'change' },],
                expirationDate:[{required: true, message: '请选择到期时间', trigger: 'change' },],
            },
            ruleForm:{
                id:0,
                signDate:'',
                expirationDate:''
            }
        }
    },
    methods: {
        handleSave(){
            this.$refs.ruleForm.validate((valid)=>{
                if(valid){
                    const flag=this.$moment(this.ruleForm.signDate).isBefore(this.ruleForm.expirationDate);
                    if(!flag){
                        this.$message.warning('到期时间不得早于运维时间')
                        return
                    }
                    this.$emit('addRenewal',this.ruleForm)
                    this.initForm()
                }
            })
        },
        initForm(){
            this.ruleForm.id = 0
            this.ruleForm.signDate = ''
            this.ruleForm.expirationDate = ''
            this.$nextTick(()=>{
                this.$refs.ruleForm.clearValidate();
            })
        },
        handleClose(){
            this.initForm()
            this.$emit('close')
        }
    },
}
</script>