<template>
    <div style="padding:0 34px 0 20px;">
        <el-tabs v-model="activeName">
            <el-tab-pane label="商家注册" name="first">
                <el-form v-if="!isSuccess1" :model="formData1" :rules="rules1" ref="form1" label-width="100px" label-position="right" size="small" style="max-width: 420px;margin-top:20px;">
                    <el-form-item prop="username" label="用户名">
                        <el-input v-model="formData1.username" placeholder="请输入用户名" maxlength="15" style="width:204px;"></el-input>
                    </el-form-item>
                    <el-form-item prop="password" label="设置密码">
                        <el-input type="password" name='psd' placeholder="6-11位的字母或者数字（必须包含数字字母的组合）" v-model="formData1.password" maxlength="20"></el-input>
                        <password-level :password='formData1.password'></password-level>
                    </el-form-item>
                    <el-form-item prop="surePassword" label="确认密码">
                        <el-input type="password" name='surepsd' placeholder="请重复输入密码" v-model="formData1.surePassword" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item prop="contacter" label="联系人">
                        <el-input placeholder="请输入联系人" v-model="formData1.contacter" maxlength="8"></el-input>
                    </el-form-item>
                    <el-form-item prop="contactPhone" label="联系人电话">
                        <el-input v-model="formData1.contactPhone" placeholder="请输入手机号码" maxlength="11"></el-input>
                    </el-form-item>
                    <el-form-item prop="code" label="短信验证码">
                        <el-input v-model="formData1.code" placeholder="请输入验证码" style="width:204px;"></el-input>
                        <el-button plain :disabled="isSend" style="width:110px;" @click="startSend">{{isSend?'已发送('+startNum+'S)':'获取验证码'}}</el-button>
                    </el-form-item>
                    <el-form-item prop="companyName" label="企业名称">
                        <el-input v-model="formData1.companyName" placeholder="请输入企业名称" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item prop="companyType" label="企业类型">
                        <el-select v-model="formData1.companyType" placeholder="请选择">
                            <el-option v-for="item in companyTypeList" :key="item.id" :label="item.typeName" :value="item.typeName">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="isRead" label="">
                        <el-checkbox v-model="formData1.isRead">已阅读</el-checkbox>
                        <el-button type="text" style="color:#FB6E08" @click="dialogVisible=true">《用户隐私协议和隐私条款》</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>

                <systemState v-else class="certain" :next='"login"' :type='"success"' :title="'注册成功！'" :subtitle='"请牢记您的用户名和密码，即可登陆。缴纳保证金后也可开店~"'></systemState>

            </el-tab-pane>
            <el-tab-pane label="个人注册" name="second">
                <el-form v-if="!isSuccess" :model="formData" :rules="rules" ref="form" label-width="100px" label-position="right" size="small" style="max-width: 420px;margin-top:20px;">
                    <el-form-item prop="username" label="用户名">
                        <el-input v-model="formData.username" placeholder="请输入用户名" maxlength="15" style="width:204px;"></el-input>
                    </el-form-item>
                    <el-form-item prop="password" label="设置密码">
                        <el-input type="password" name='psd' placeholder="6-20位的字母或者数字（必须包含数字字母的组合）" v-model="formData.password" maxlength="20"></el-input>
                        <password-level :password='formData.password'></password-level>
                    </el-form-item>
                    <el-form-item prop="surePassword" label="确认密码">
                        <el-input type="password" name='surepsd' placeholder="请重复输入密码" v-model="formData.surePassword" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item prop="phone" label="手机号码">
                        <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11"></el-input>
                    </el-form-item>
                    <el-form-item prop="code" label="短信验证码">
                        <el-input v-model="formData.code" placeholder="请输入验证码" style="width:204px;"></el-input>
                        <el-button plain :disabled="isSend" style="width:110px;" @click="startSend">{{isSend?'已发送('+startNum+'S)':'获取验证码'}}</el-button>
                    </el-form-item>

                    <el-form-item prop="isRead" label="">
                        <el-checkbox v-model="formData.isRead">已阅读</el-checkbox>
                        <el-button type="text" style="color:#FB6E08" @click="dialogVisible=true">《用户隐私协议和隐私条款》</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>

                <systemState v-else class="certain" :next='"login"' :type='"success"' :title="'注册成功！'" :subtitle='"请牢记您的用户名和密码，即可登陆。缴纳保证金后也可开店~"'></systemState>
            </el-tab-pane>
        </el-tabs>

        <el-dialog title="用户隐私协议和隐私条款" class="xieyi" :visible.sync="dialogVisible" width="636px">
            <div class="window" v-html="agreement">

            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="readAgree(false)">不同意</el-button>
                <el-button type="primary" @click="readAgree(true)">同 意</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
import formValidator from '../formValidator'
import systemState from '../pagesPre/SystemState'
import passwordLevel from '../components/PasswordLevel'
import { mapState } from 'vuex'
export default {
    created() {

        this.$http.get({
            url: '/companyType/all'
        }).then(res => {
            if (res.success) {
                this.companyTypeList = res.data
            }
        });

        this.$http.get({
            url: '/userAgreement/getOne?id=1',
        }).then(res => {
            if (res.success) {
                if (res.data) {
                    this.agreement = res.data.agreement
                }

            }
        })

    },
    computed: {
        ...mapState(['msgCode']),
    },
    data() {
        return {
            dialogVisible: false,
            agreement: '',
            companyTypeList: [],
            activeName: 'second',
            saving: false,
            formData: {
                isRead: false,
            },
            formData1: {
                isRead: false,
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入用户名'));
                            }
                            else if (/^[0-9]*$/.test(value)) {
                                callback(new Error('用户名必须包含字母或中文字符'));
                            }
                            else if (!/^[\u4E00-\u9FA5A-Za-z0-9_]+$/.test(value)) {//中文，英文，下划线
                                callback(new Error('用户名不能包含特殊字符'));
                            } else {
                                this.checkHas({ username: this.formData.username }).then((result) => {
                                    if (result) {
                                        callback(new Error('已存在该用户名'));
                                    }
                                    else {
                                        callback();
                                    }
                                })
                            }
                        }, trigger: 'blur'
                    }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {

                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入密码'));
                            } else if (!/^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/.test(value)) {
                                callback();
                            } else {
                                callback(new Error('6-20位的字母、数字和特殊字符（必须包含数字母、数字和特殊字符）'));
                            }
                        }, trigger: 'blur'
                    }
                ],
                surePassword: [
                    { required: true, message: '请输入确认密码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入确认密码'));
                            } else if (value == this.formData.password) {
                                callback();
                            } else {
                                callback(new Error('两次密码输入不一致！'));
                            }
                        }, trigger: 'blur'
                    }
                ],
                phone: [
                    { 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'
                    }
                ],
                code: [
                    { required: true, message: '请输入短信验证码', trigger: 'blur' },
                ],
                isRead: [{
                    validator: (rule, value, callback) => {
                        if (!value) {
                            callback(new Error('请阅读并同意协议'));
                        } else {
                            callback();
                        }
                    }, trigger: 'blur'
                }]
            },
            rules1: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入用户名'));
                            }
                            else if (!/^[\u4E00-\u9FA5A-Za-z0-9_]+$/.test(value)) {//中文，英文，下划线
                                callback(new Error('用户名不能包含特殊字符'));
                            }
                            else if (/^[0-9]*$/.test(value)) {
                                callback(new Error('用户名必须包含字母或中文字符'));
                            }
                            else {
                                this.checkHas({ username: this.formData1.username }).then((result) => {
                                    if (result) {
                                        callback(new Error('已存在该用户名'));
                                    }
                                    else {
                                        callback();
                                    }
                                })
                            }
                        }, trigger: 'blur'
                    }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入密码'));
                            } else if (!/^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/.test(value)) {
                                callback();
                            } else {
                                callback(new Error('6-20位的字母、数字和特殊字符（必须包含数字母、数字和特殊字符）'));
                            }
                        }, trigger: 'blur'
                    }
                ],
                surePassword: [
                    { required: true, message: '请输入确认密码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入确认密码'));
                            } else if (value == this.formData1.password) {
                                callback();
                            } else {
                                callback(new Error('两次密码输入不一致！'));
                            }
                        }, trigger: 'blur'
                    }
                ],
                contacter: [
                    { required: true, message: '请输入联系人', trigger: 'blur' }
                ],
                contactPhone: [
                    { 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'
                    }
                ],
                companyName: [
                    { required: true, message: '请输入公司名称', trigger: 'blur' },
                ],
                companyType: [
                    { required: true, message: '请选择公司类型', trigger: 'blur' },
                ],
                code: [
                    { required: true, message: '请输入短信验证码', trigger: 'blur' },
                ],
                isRead: [{
                    validator: (rule, value, callback) => {
                        if (!value) {
                            callback(new Error('请阅读并同意协议'));
                        } else {
                            callback();
                        }
                    }, trigger: 'blur'
                }]
            },
            roles: [],
            departs: [],
            backCode: '',
            startNum: 60,
            isSend: false,
            isSuccess: false,
            isSuccess1: false
        }
    },
    methods: {
        onSave() {
            if (this.activeName == 'first') {
                this.$refs.form1.validate((valid) => {
                    if (valid) {
                        this.checkMes().then((result) => {
                            console.log(result)
                            if (result) {
                                this.submit();
                            }
                        })

                    } else {
                        return false;
                    }
                });
            }
            else {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.checkMes().then((result) => {
                            console.log(result)
                            if (result) {
                                this.submit();
                            }
                        })

                    } else {
                        return false;
                    }
                });
            }

        },
        submit() {
            if (this.activeName == 'second') {
                this.$http.post({
                    url: '/userInfo/register',
                    data: {
                        username: this.formData.username,
                        nickname: this.formData.username,
                        password: this.formData.password,
                        phone: this.formData.phone
                    }
                }).then(res => {
                    if (res.success) {
                        this.$message.success('成功');
                        this.isSuccess = true
                    } else {
                        this.$message.warning('失败')
                    }
                });
            }
            else {

                this.$http.post({
                    url: '/userInfo/register',
                    data: {
                        username: this.formData1.username,
                        nickname: this.formData1.username,
                        password: this.formData1.password,
                        phone: this.formData1.contactPhone,
                        contacter: this.formData1.contacter,
                        companyName: this.formData1.companyName,
                        companyType: this.formData1.companyType,
                        contactPhone: this.formData1.contactPhone,
                        companyFlag: 'Y'

                    }
                }).then(res => {
                    if (res.success) {
                        this.$message.success('成功');
                        this.isSuccess1 = true
                    } else {
                        this.$message.warning('失败')
                    }
                });
            }


        },
        startSend() {
            if (!this.checkPhone(this.formData.phone) && this.activeName == 'second') {
                this.$message.warning('手机号格式错误')
                return
            }
            else if (!this.checkPhone(this.formData1.contactPhone) && this.activeName == 'first') {
                this.$message.warning('手机号格式错误')
                return
            }


            this.checkHas({ phone: (this.activeName == 'first' ? this.formData1.contactPhone : this.formData.phone) }).then((result) => {
                console.log(result)
                if (result) {
                    this.$message.warning('该手机号已经被用户绑定')
                }
                else {
                    this.sendMeg(this.activeName == 'first' ? this.formData1.contactPhone : 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)
                        }
                    })
                }
            })


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

            })


        },
        readAgree(reslut) {
            this.dialogVisible = false
            if (this.activeName == 'second') {
                this.formData.isRead = reslut
            }
            else {
                this.formData1.isRead = reslut
            }
        }
    },
    components: {
        systemState, passwordLevel
    }
}
</script>
<style lang="less" scoped>
.certain {
    margin: 140px auto;
}
.window {
    max-height: 50vh;
    overflow: auto;
    border-top: 1px solid #ebebeb;
    padding-top: 20px;
}
</style>
