<template>
    <el-dropdown @command="send" :disabled="leftTime > 0 && leftTime < 60">
      <el-button type="primary">
        {{ text }}<i class="el-icon-arrow-down el-icon--right"></i>
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="1">SMS</el-dropdown-item>
        <el-dropdown-item command="2">WhatsApp</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
</template>
<script>
import {sendSmsCode} from '@/api/ecw/orderCargoControl'
let timeout = null
export default {
    props:{
        form: Object
    },
    data(){
        return {
            leftTime: 60,
            loading: false
        }
    },
    computed:{
        text(){
            if(this.leftTime === 60){
                return this.$t('发送验证码')
            }
            if(this.leftTime > 0){
                return this.leftTime + this.$t('秒')
            }
            return this.$t('重新发送')
        }
    },
    destroyed(){
        if(timeout)clearTimeout(timeout)
    },
    methods:{
        send(messageType){
            if(this.loading || (this.leftTime > 0 && this.leftTime < 60)) return false
            this.loading = true
            this.form['messageType'] = messageType
            sendSmsCode(this.form).then(res => {
                this.$message.success(this.$t('发送成功'))
                this.countDown()
            }).finally(res => {
                this.loading = false
            })
        },
        countDown(){
            this.leftTime --
            if(this.leftTime <= 0){
                return false
            }
            timeout = setTimeout(this.countDown, 1000)
        }
    }
}
</script>
