<template>
    <div style="padding:0 24px 0 24px;">
        <div class="stepContent">
            <certificationStep :list='stepList' :nowStep='nowStep'></certificationStep>
        </div>

        <div class="content">
            <template v-if="nowStep==1">
                <el-form :model="formData" :rules="rules" ref="form" label-width="100px" label-position="right" style="max-width: 420px;margin-top:20px;margin:auto">

                    <el-form-item prop="phone" label="手机号码">
                        <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11"></el-input>
                    </el-form-item>
                    <el-form-item prop="imgCode" label="图片验证码">
                        <el-input v-model="formData.imgCode" placeholder="请输入验证码" style="width:137px;vertical-align: middle;"></el-input>
                        <img style="widdth:108px;height:39px;vertical-align: middle;margin-left:30px;" :src="baseUrl+'/auth/image?'+autoString" alt="">
                        <el-button type="text" @click="randomString" style="vertical-align: middle;">换一张</el-button>
                    </el-form-item>
                    <el-form-item prop="code" label="短信验证码">
                        <el-input v-model="formData.code" placeholder="请输入验证码" style="width:204px;"></el-input>
                        <el-button plain style="width:110px;" :disabled='isSend' @click="startSend">{{isSend?'已发送('+startNum+'S)':'获取验证码'}}</el-button>
                    </el-form-item>

                    <el-form-item label="">
                        <el-button type="primary" style="width:204px" @click="onSave">下一步</el-button>
                    </el-form-item>

                </el-form>
            </template>
            <template v-if="nowStep==2">
                <el-form :model="formData2" :rules="rules2" ref="form2" label-width="100px" label-position="right" style="max-width: 420px;margin-top:20px;margin:auto">
                    <el-form-item prop="phone2" label="手机号码">
                        <el-input v-model="formData2.phone2" placeholder="请输入手机号码" maxlength="11"></el-input>
                    </el-form-item>
                    <el-form-item prop="code2" label="短信验证码">
                        <el-input v-model="formData2.code2" placeholder="请输入验证码" style="width:204px;"></el-input>
                        <el-button plain style="width:110px;" :disabled='isSend' @click="startSendChange">{{isSend?'已发送('+startNum+'S)':'获取验证码'}}</el-button>
                    </el-form-item>

                    <el-form-item label="">
                        <el-button type="primary" :loading="loading" style="width:320px" @click="onSave2">提交修改</el-button>
                    </el-form-item>

                </el-form>
            </template>

            <template v-if="nowStep==3">

                <systemState style="margin:auto" class="certain" :next='"index"' :type='"success"' :title="'手机号绑定成功'" :subtitle='""'></systemState>
            </template>

        </div>

    </div>
</template>
<script>
import formValidator from '../formValidator'
import systemState from '../pagesPre/SystemState'
import certificationStep from '../components/CertificationStep'
import { mapState } from 'vuex'

const baseUrl = process.env.NODE_ENV === 'production' ? '../' : `http://${location.hostname}:8080`;
export default {
    created() {
        this.randomString()
        // this.getNext(5)
    },
    data() {
        return {
            baseUrl,
            imgCode: {},
            autoString: '',
            stepList: ['输入手机号码', '绑定新手机号', '完成'],
            nowStep: 1,
            saving: false,
            formData: {
                isRead: false,
            },
            formData2: {},
            rules: {

                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入手机号'));
                            } else if (this.userInfo.phone == value) {
                                callback();
                            } else {
                                callback(new Error('手机号与用户不匹配'));
                            }
                        }, trigger: 'blur'
                    }
                ],
                code: [
                    { required: true, message: '请输入短信验证码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入图片验证码'));
                            }
                            else if (!this.backCode) {
                                callback(new Error('请发送验证码'));
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
                imgCode: [
                    { required: true, message: '请输入图片验证码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入图片验证码'));
                            } else {
                                this.$http.get({
                                    url: '/auth/verify',
                                    data: {
                                        code: value,
                                    }
                                }).then(res => {
                                    if (res.success) {
                                        callback();
                                    } else {
                                        callback(new Error('验证码错误'));
                                    }
                                });
                            }
                        }, trigger: 'blur'
                    }
                ]
            },
            rules2: {

                phone2: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入手机号'));
                            }
                            else if (/^1[3-9]\d{9}$/.test(value)) {
                                callback();
                            } else {
                                callback(new Error('请输入正确的手机号'));
                            }
                        }, trigger: 'blur'
                    }
                ],
                code2: [
                    { required: true, message: '请输入短信验证码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入图片验证码'));
                            }
                            else if (!this.backCode) {
                                callback(new Error('请发送验证码'));
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],

            },
            roles: [],
            departs: [],
            backCode: '',
            startNum: 60,
            isSend: false,
            isSuccess: false,
            isSuccess1: false,
            loading: false,
            nowIndex: 5
        }
    },
    computed: {
        ...mapState(['msgCode', 'userInfo']),
    },
    methods: {
        onSave() {
            this.loading = true
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.nowStep == 1) {
                        this.checkMes(this.formData.code).then((result) => {
                            this.loading = false
                            if (result) {
                                this.nowStep++
                                this.backCode = ''
                                this.startNum = 60
                                this.isSend = false
                            }
                        })
                    }
                    else {
                        // this.submit()
                    }


                } else {
                    return false;
                }
            });
        },
        onSave2() {
            this.loading = true
            this.$refs.form2.validate((valid) => {
                if (valid) {
                    this.checkMes(this.formData2.code2).then((result) => {
                        this.loading = false
                        if (result) {
                            this.submit()
                        }
                    })


                } else {
                    return false;
                }
            });
        },
        submit() {

            var data = {};
            data.id = this.userInfo.id
            data.phone = this.formData2.phone2
            this.$http.post({
                url: '/userInfo/update',
                data: data
            }).then(res => {
                if (res.success) {
                    this.$message.success('成功');
                    this.nowStep++
                    // this.getNext(5)
                    this.$http.get({
                        url: '/userInfo/getUserInfo',
                        data: {}
                    }).then(res => {
                        if (res.success) {
                            this.$store.commit('updateUserInfo', res.data);
                        }
                    })
                } else {
                    this.$message.warning('失败')
                }
            });


        },
        getNext(i) {
            this.nowIndex = i
            if (i == 0) {
                this.$router.go(-1)
            }
            else {
                setTimeout(() => {
                    this.getNext(i - 1)
                }, 1000)
            }
        },
        startSend() {
            if (this.formData.phone != this.userInfo.phone) {
                this.$message.warning('手机号与用户不匹配')
                return
            }



            this.checkHas({ phone: this.formData.phone }).then((result) => {
                console.log(result)
                if (result) {
                    this.sendMeg(this.formData.phone, this.msgCode['身份验证']).then((json) => {
                        if (json.success) {
                            this.$message.success('发送成功')
                            this.backCode = json.data
                            this.startNum = 61
                            this.isSend = true
                            this.setTime()
                        }
                        else {
                            this.$message.warning(json.error)
                        }
                    })
                }
                else {
                    this.$message.warning('该手机号未绑定用户')
                }
            })


        },
        startSendChange() {
            if (!this.checkPhone(this.formData2.phone2)) {
                this.$message.warning('手机号格式错误')
                return
            }



            this.checkHas({ phone: this.formData2.phone2 }).then((result) => {
                console.log(result)
                if (result) {
                    this.$message.warning('该手机号已绑定用户')
                }
                else {
                    this.sendMeg(this.formData2.phone2, this.msgCode['信息变更']).then((json) => {
                        if (json.success) {
                            this.$message.success('发送成功')
                            this.backCode = json.data
                            this.startNum = 61
                            this.isSend = true
                            this.setTime()
                        }
                        else {
                            this.$message.warning(json.error)
                        }
                    })

                }
            })
        },
        setTime() {
            if (this.startNum == 0) {
                this.isSend = false
                return
            }
            this.startNum--
            setTimeout(() => {
                this.setTime()
            }, 1000)
        },
        checkMes(code) {
            return new Promise((resolve, reject) => {
                if (!this.backCode) {
                    this.$message.warning('请发送验证码')
                    resolve(false)
                }
                else if (!code) {
                    this.$message.warning('请输入验证码')
                    resolve(false)
                }
                else {
                    this.$http.get({
                        url: '/aliapi/verifyMsgCode',
                        data: {
                            // sessionId: this.backCode,
                            code: code
                        }
                    }).then(res => {
                        if (res.success) {
                            resolve(true)
                        } else {
                            this.$message.warning(res.error)
                            resolve(false)
                        }
                    });
                }

            })


        },
        randomString(len) {
            var pwd = Math.random().toString(36).substr(2);

            console.log(pwd)
            this.autoString = pwd
        }
    },
    components: {
        systemState, certificationStep
    }
}
</script>
<style lang="less" scoped>
.stepContent {
    padding: 90px 300px 49px;
}
</style>
