import verification from '$utils/verification';

import { InstructionsMessageType } from '$utils/request';

export default <LibMixins>{

    data(){
        return {
            timeConfig:{
                default:'获取验证码',
                format:'还剩',
                afterFormat:'s',
                time:60
            },
            timeFormat:''
        }
    },

    methods:{

        // 获取验证码
        triggerTimeDate(item:LibData,data:LibDataArray){

            if (this.timeFormat) return;


            let resultData:LibData = undefined;
            for (let i=0,count=data.length;i<count;i++) {
                if (item.code === data[i].key) {
                    resultData = {
                        ...data[i]
                    };
                    break;
                }
            }

            if (resultData) {
                resultData.key = 'mobile';
                verification.verificationPromise(resultData,true).then((data)=>{

                    data.type = item.codeType;

                    this.$request({
                        url:'login/send_sms',
                        data,
                        message:InstructionsMessageType.other,
                        failMessage:true
                    }).catch(()=>{
                        // 如果发生错误触发
                        this.endTimeDate = 0
                    });

                    return this.triggerTimeType();
                });


            }

        },

        // 触发倒计时
        triggerTimeType(){

            clearTimeout(this._time_format);

            if (this.endTimeDate === undefined) {
                this.endTimeDate = this.getTimeDate() + this.timeConfig.time;
            }

            let diff = this.endTimeDate - this.getTimeDate();

            if (diff <= 0) {
                this.timeFormat = '';
                this.endTimeDate = undefined;
            } else {
                this.timeFormat = this.timeConfig.format + diff + this.timeConfig.afterFormat;

                this._time_format = setTimeout(()=> this.triggerTimeType(),1000);
            }

        },

        // 获取时间
        getTimeDate(){
            return Math.ceil(new Date().getTime() / 1000);
        }

    },
    beforeUnmount() {
        clearTimeout(this._time_format);
    }
}