/**
 * 通用「重发冷却」mixin。
 *
 * 把"剩余秒数 / 启停 / 自动清理"内聚成单一关注点，避免每个页面重复写 setInterval。
 *
 * 使用：
 *   import resendCooldown from '@/common/mixins/resend-cooldown'
 *   mixins: [resendCooldown]
 *   // this.coolLeft   剩余秒数 (0 表示空闲)
 *   // this.coolReady  是否可重新点击
 *   // this.coolStart(60)  启动
 *   // this.coolStop()      强行停止
 */

const DEFAULT_SPAN = 60

export default {
	data() {
		return {
			coolLeft: 0,
			coolHandle: null
		}
	},
	computed: {
		coolReady() {
			return this.coolLeft <= 0
		}
	},
	beforeDestroy() {
		this.coolStop()
	},
	methods: {
		coolStart(span = DEFAULT_SPAN) {
			this.coolStop()
			this.coolLeft = Math.max(1, Math.floor(span))
			this.coolHandle = setInterval(() => {
				if (this.coolLeft <= 1) {
					this.coolStop()
					return
				}
				this.coolLeft = this.coolLeft - 1
			}, 1000)
		},
		coolStop() {
			if (this.coolHandle) {
				clearInterval(this.coolHandle)
				this.coolHandle = null
			}
			this.coolLeft = 0
		}
	}
}
