import {Component, Vue, Watch} from 'vue-property-decorator';
import {LoginData} from '@/types/views/login.interface';
import Sidentify from './identify.vue'
import {host, http} from '@/config';
import router from '@/router';
import Utils from '@/extend/Utils';
import Http from '@/extend/Http';
import {Message} from "element-ui";

@Component({
    components: {
        Sidentify
    }
})
export default class Login extends Vue {

    // data
    data: any = {
        verifyImg: host + '/captcha.html',
        infonam: 'hint',
        type: 'mobile',
        identifyCodes: '1234567890',
        identifyCode: '',
        mobile: '',
        imgVerify: '',
        codeVerify: '',
        errorType: {
            mobile: '',
            imgVerify: '',
            codeVerify: '',
        },
        verifyBtnActive: true,
        verifyBtnText: '获取验证码',
        inviter_code:'',
        // 是否是城镇户口 true-是城镇
        // is_town: true
    };
    private timers: any;
    private urlParams: any;

    @Watch('data.mobile') mobileWatch(newVal: string, oldVal: string) {
        this.data.errorType.mobile = Utils.getInstance().isMobile(newVal);
    }

    @Watch('data.imgVerify') imgVerifyWatch(newVal: string, oldVal: string) {
        this.data.errorType.imgVerify = /^[0-9a-zA-Z]{4}$/.test(this.data.imgVerify);
    }

    @Watch('data.codeVerify') codeVerifyWatch(newVal: string, oldVal: string) {
        this.data.errorType.codeVerify = /^[0-9]{6}$/.test(this.data.codeVerify);
    }

    // 验证码
   randomNum (min, max) {
        return Math.floor(Math.random() * (max - min) + min)
    }
   refreshCode () {
        this.data.identifyCode = ''
        this.makeCode(this.data.identifyCodes, 4)
    }
   makeCode (o,l) {
        for (let i = 0; i < l; i++) {
            this.data.identifyCode += this.data.identifyCodes[this.randomNum(0, this.data.identifyCodes.length)]
        }
    }

    async created() {
        this.data.mobile = localStorage.getItem('phone')
        if (!localStorage.getItem('refresh_token')) {
            let ua = window.navigator.userAgent.toLowerCase();
            this.urlParams = Utils.getInstance().getParams(location.href);
            if (this.urlParams.inviter_code ) {
                this.data.inviter_code = this.urlParams.inviter_code;
            }else {
                this.data.inviter_code ='';
            }
            this.data.identifyCode = ''
            this.makeCode(this.data.identifyCodes, 4)
            // this.refreshCode()
            console.log( this.data.inviter_code )
            // if (ua.match(/MicroMessenger/i) && !this.urlParams.code) {
            //     this.data.type = 'weixin';
            //     location.href = host + '/dev?platform=weixin&callback=' + location.href;
            // } else if (this.urlParams.code) {
            //     let data = await Http.getInstance().sns(Object.assign({platform: 'weixin'}, this.urlParams));
            //     this.loginCallBack(data);
            // }
        }else{
            Message({
                message: '您已登录', duration: 2000, type: "success"
            });
            this.$router.push('/user')
        }

    }

    async loginform(event: any) {
        this.data.errorType = [];
        if (!Utils.getInstance().isMobile(this.data.mobile)) {
            this.data.errorType.push('mobile');
            Message({
                message: '手机号有误', duration: 2000, type: "error"
            });
            return false;
        }
        if (/^[0-9a-zA-Z]{4}$/.test(this.data.imgVerify) === false) {
            this.data.errorType.push('imgVerify');
            Message({
                message: '图形验证码有误', duration: 2000, type: "error"
            });
            return false;
        }
        if (/^[0-9]{6}$/.test(this.data.codeVerify) === false) {
            this.data.errorType.push('codeVerify');
            Message({
                message: '手机验证码有误', duration: 2000, type: "error"
            });
            return false;
        }
        let post = Object.assign(this.urlParams,Utils.getInstance().serialize(document.getElementById('form-data')));
        let data = await Http.getInstance().login(post);
        (<any>window)._agl  &&  (<any>window)._agl.push(['track',  ['success',  {t:  3}]])
        if(data.errcode == 11 || data.errcode == 12 ){
            Message({
                message: data.msg, duration: 2000, type: "error"
            });
            return false
        }
        this.loginCallBack(data);
        return false;
    }

    async loginCallBack(data: any) {
        console.log('data',data);
        if (data.code === 1) {
            for (let index in data.data) {
                localStorage.setItem(index, data.data[index]);
            }
            router.replace('index');
        } else if (data.code === '20201') {
            this.data.errorType.push('mobile');
        } else if (data.code.toString() === '20202') {
            this.data.errorType.push('imgVerify');
        } else if (data.code.toString() === '20203') {
            this.data.errorType.push('codeVerify');
        } else {
            alert(data.msg);
            return false
        }
    }

    reloadVerify(event: any) {
        let src = event.target.getAttribute('src');
        if (src && src.indexOf('?') > 0) {
            event.target.setAttribute('src', src + '&random=' + Math.random());
        } else if (src) {
            event.target.setAttribute('src', src.replace(/\?.*$/, '') + '?' + Math.random());
        }
    }

    getMobileVerify(event: any) {
        if (!Utils.getInstance().isMobile(this.data.mobile)) {
            this.data.errorType.push('mobile');
            alert('手机号有误')
            return false;

        }
        if( this.data.imgVerify != this.data.identifyCode ){
            alert('验证码有误')
            return false
        }
        Http.getInstance().getVerifyCode({
            mobile:  this.data.mobile
        });
        this.data.verifyBtnActive = false;
        this.data.verifyBtnText = '60 s';
        this.timers = this.countDown();
    }

    private countDown() {
        return setInterval(() => {
            let number = parseInt(this.data.verifyBtnText, 10);
            if (number <= 0) {
                clearInterval(this.timers);
                this.data.verifyBtnActive = true;
                this.data.verifyBtnText = '获取验证码';
            } else {
                this.data.verifyBtnText = number - 1 + ' s';
            }
        }, 1000);
    }

}
