<template>
    <view>
        <text>{{ item.beforeText }}</text>
        <text v-if="(num > 0 && isEnable) || item.duration">
            <text class="cd-num">{{ num }}</text>
            <text>{{ item.text }}</text>
        </text>
        <text
            class="cd-link"
            :class="num <= 0 && isEnable? (item.color ? item.color : 'green') : ''"
            @tap="onRewrite">{{ item.linkText }}</text>
        <text>{{ item.afterText }}</text>
    </view>
</template>

<script>
/**
 * @file components/im/im-msg
 * @author haoyan
 */
import * as core from '@utils/core';
export default {
    config: {
        component: true
    },
    components: {
    },
    props: {
        item: {
            type: Object,
            default: {}
        },
        isLogin: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            num: Number(this.item && (this.item.number || this.item.duration)),
            orgNum: Number(this.item && (this.item.number || this.item.duration)),
            isEnable: true
        };
    },
    watch: {
        isLogin(value) {
            if (value === true) {
                // 登录后禁用倒计时
                this.isEnable = false;
            }
        }
    },
    lifetimes: {
        attached() {
            // 倒计时
            if (this.item.duration) {
                this.handleCountDownTime();
                return;
            }
            const start = Date.now();
            const timeid = setInterval(() => {
                const dur = Date.now() - start;
                this.num = this.orgNum - parseInt(dur / 1000, 10);
                if (this.num <= 0) {
                    clearInterval(timeid);
                }
            }, 1000);
        }
    },
    methods: {
        // 点击[重新输入手机号]
        onRewrite() {
            if (this.num <= 0) {
                this.$emit('questionReply', {
                    callbackUrl: this.item.callbackUrl
                });
                this.isEnable = false;
            }
        },
        // 倒计时换算成时分秒
        handleCountDownTime() {
            let originNum = this.item.duration;
            this.num = core.fmtCountDown(originNum);
            this.timer = setInterval(() => {
                originNum -= 1;
                this.num = core.fmtCountDown(originNum);
                if (originNum < 0) {
                    clearInterval(this.timer);
                }
            }, 1000);
        }
    }
};
</script>

<style lang="less">
.cd-link {
    &.blue {
        color: #489AF6;
    }
    &.green {
        color: #00b7c8;
    }
}
.cd-num {
    color: #ff6050;
}
</style>