<template>
    <div class="container" :style="{ backgroundImage: 'url(' + require('../assets/login_bg.jpg') + ')' }">
        <transition :name="`slide-${register ? 'in' : 'out'}`">
            <div class="login-wrapper" @keyup.enter="doRegister" v-if="register" key="register">
                <div class="title">南京市社会艺术水平考级管理服务系统注册</div>
                <el-page-header @back="register = false" title="登录" style="width: 380px; line-height: 55px">
                    <div class="register-title" slot="content">注册账号</div>
                </el-page-header>

                <el-form :model="registerInfo" :rules="registerRule" style="width: 460px" ref="registerForm">
                    <el-form-item
                        prop="username"
                        label="用户名"
                        :rules="{ required: true, message: '请输入用户名', trigger: 'blur' }"
                    >
                        <el-input class="input-width" v-model="registerInfo.username" placeholder="用户名(账号)">
                        </el-input>
                    </el-form-item>
                    <el-form-item
                        prop="password"
                        label="密码"
                        :rules="{ required: true, message: '请输入密码', trigger: 'blur' }"
                    >
                        <el-input
                            class="input-width"
                            v-model="registerInfo.password"
                            placeholder="密码"
                            type="password"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="password1" label="确认密码">
                        <el-input
                            class="input-width"
                            v-model="registerInfo.password1"
                            placeholder="密码"
                            type="password"
                        ></el-input>
                    </el-form-item>

                    <el-form-item
                        prop="organizationName"
                        label="承办单位名称"
                        :rules="{
                            required: true,
                            message: '请填营业执照或组织机构代码证上的名称、全称',
                            trigger: 'blur'
                        }"
                    >
                        <el-input
                            class="input-width"
                            v-model="registerInfo.organizationName"
                            placeholder="营业执照或组织机构代码证上的名称、全称"
                        >
                        </el-input>
                    </el-form-item>
                    <el-form-item
                        prop="phone"
                        label="手机号"
                        :rules="{
                            required: true,
                            message: '请输入正确的手机号',
                            pattern: /^1[3-9]\d{9}$/,
                            trigger: 'blur'
                        }"
                    >
                        <el-input class="input-width" v-model="registerInfo.phone" placeholder="手机号"> </el-input>
                    </el-form-item>
                    <el-form-item
                        prop="email"
                        label="电子邮箱"
                        :rules="{
                            required: true,
                            message: '请输入正确的电子邮箱',
                            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                            trigger: 'blur'
                        }"
                    >
                        <el-input class="input-width" v-model="registerInfo.email" placeholder="电子邮箱"> </el-input>
                    </el-form-item>
                    <el-form-item prop="gradingOrganizationId" label="所属考级机构">
                        <el-select
                            v-model="registerInfo.gradingOrganizationId"
                            placeholder="请选择所属考级机构"
                            style="width: 350px"
                            multiple
                            @change="setGradingCode"
                        >
                            <el-option
                                v-for="(item, index) in examination"
                                :key="index"
                                :value="item.value"
                                :label="item.label"
                            ></el-option>
                        </el-select>
                        <!-- <el-input v-model="registerInfo.organizationName" placeholder="发证机构"> </el-input> -->
                    </el-form-item>
                    <el-form-item
                        prop="district"
                        label="注册地址"
                        :rules="{ required: true, message: '请选择注册地址', trigger: 'blur' }"
                    >
                        <!-- <district-choose v-model="registerInfo.district"></district-choose> -->
                        <el-select
                            v-model="registerInfo.district"
                            placeholder="请选择注册地址"
                            style="width: 350px"
                            @change="setDistrictCode"
                        >
                            <el-option
                                v-for="(item, index) in districtOptions"
                                :key="index"
                                :value="item.label"
                                :label="item.label"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="是否加入联盟"
                        :rules="{ required: true, message: '请选择是否加入联盟', trigger: 'blur' }"
                    >
                        <el-select v-model="alliance" style="width: 350px" placeholder="请选择是否加入联盟">
                            <el-option label="已加入" :value="true"></el-option>
                            <el-option label="未加入" :value="false"></el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item
                        prop="businessLicense"
                        :rules="{ required: true, message: '请上传营业执照', trigger: 'blur' }"
                    >
                        <single-upload v-model="registerInfo.businessLicense"></single-upload>
                    </el-form-item> -->
                    <el-form-item class="login-btn">
                        <el-button :loading="loading" @click="doRegister" type="primary" style="width: 100%"
                            >注册</el-button
                        >
                    </el-form-item>
                </el-form>
            </div>
            <div class="login-wrapper" @keyup.enter="login" v-else key="login">
                <div class="title">南京市社会艺术水平考级管理服务系统</div>
                <el-tabs v-model="activeName" stretch class="tab-list">
                    <el-tab-pane label="用户名登陆" name="first">
                        <el-form size="medium" :model="userInfo" style="width: 380px" ref="form">
                            <el-form-item
                                prop="username"
                                :rules="{ required: true, message: '请输入用户名', trigger: 'blur' }"
                            >
                                <el-input v-model="userInfo.username" placeholder="用户名"> </el-input>
                            </el-form-item>
                            <el-form-item
                                prop="password"
                                :rules="{ required: true, message: '请输入密码', trigger: 'blur' }"
                            >
                                <el-input v-model="userInfo.password" placeholder="密码" type="password"></el-input>
                            </el-form-item>
                            <el-form-item class="login-btn">
                                <el-button :loading="loading" @click="login" type="primary" style="width: 100%"
                                    >登录
                                </el-button>
                            </el-form-item>
                            <!-- <el-form-item>
                                <el-button :loading="loading"
                                    @click="phonelogin" type="primary"
                                    style="width: 100%;">手机登录</el-button>
                            </el-form-item> -->
                            <el-form-item label="">
                                <el-checkbox v-model="rememberMe">7天内免登录 </el-checkbox>
                                <el-button type="text" style="float: right" @click="register = true"
                                    >注册账号
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="验证码登陆" name="second">
                        <el-form size="medium" :model="userInfo" style="width: 380px" ref="form2">
                            <el-form-item
                                prop="phone"
                                :rules="{ required: true, message: '请输入手机号', trigger: 'blur' }"
                            >
                                <el-input v-model="userInfo.phone" name="phone" placeholder="手机号"> </el-input>
                            </el-form-item>
                            <el-form-item prop="code" :rules="{ required: true, message: '验证码', trigger: 'blur' }">
                                <div class="code">
                                    <el-input v-model="userInfo.code" placeholder="请输入验证码"></el-input>

                                    <el-button
                                        :loading="sending"
                                        @click="sendMsg"
                                        type="primary"
                                        :disabled="time !== 0"
                                    >
                                        {{ time === 0 ? '发送验证码' : `重新发送（${time}s）` }}
                                    </el-button>
                                </div>
                            </el-form-item>
                            <!-- <el-form-item>
                                <el-button :loading="loading" @click="login"
                                    type="primary" style="width: 100%;">登录
                                </el-button>
                            </el-form-item> -->
                            <el-form-item class="login-btn">
                                <el-button
                                    size="medium"
                                    :loading="loading"
                                    @click="phonelogin"
                                    type="primary"
                                    style="width: 100%"
                                    >手机登录</el-button
                                >
                            </el-form-item>
                            <el-form-item label="">
                                <el-checkbox v-model="rememberMe">7天内免登录 </el-checkbox>
                                <el-button type="text" style="float: right" @click="register = true"
                                    >注册账号
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </transition>
    </div>
</template>
<script>
export default {
    data() {
        return {
            rememberMe: false,
            loading: false,
            userInfo: {
                username: '',
                password: '',
                phone: '',
                code: ''
            },
            register: false,
            registerInfo: {
                username: '',
                password: '',
                password1: '',
                businessLicense: '',
                districtCode: ''
            },
            activeName: 'first',
            time: 0,
            sending: false,
            districtOptions: [],
            examination: [],
            rules: {
                password: [{ validator: validatePass, trigger: 'blur' }],
                password1: [{ validator: validatePass2, trigger: 'blur' }]
            },
            registerRule: {
                password1: [
                    {
                        validator: (rule, value, callback) => {
                            if (value !== this.registerInfo.password) {
                                callback(new Error('两次密码输入不一致'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    },
                    { required: true, message: '请再次输入密码', trigger: 'blur' }
                ]
            },
            alliance: ''
        };
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm.pass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
    },
    created() {
        this.$http
            // .get('/district/NJ', { size: 1000, query: { del: false } })
            .post('/setting/byFlag', { flag: 2 })
            .then(res => {
                if (res.length > 0) {
                    res.forEach(item => {
                        this.districtOptions.push({
                            label: item.name,
                            value: item.id
                        });
                    });
                }
            })
            .catch(e => {
                console.log(e);
                this.$message.error(e.error);
            });
        this.$http
            .post('/gradingOrganization/all', { size: 1000 }, { body: 'json' })
            .then(res => {
                if (res.content.length > 0) {
                    res.content.forEach(item => {
                        this.examination.push({
                            label: item.name,
                            value: item.id,
                            code: item.code
                        });
                    });
                }
            })
            .catch(e => {
                console.log(e);
                this.$message.error(e.error);
            });
    },
    methods: {
        login() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$http
                        .post('/auth/login', {
                            username: this.userInfo.username,
                            password: this.userInfo.password,
                            remember: this.rememberMe
                        })
                        .then(res => {
                            sessionStorage.setItem('token', res);
                            return this.$store.dispatch('getUserInfo');
                        })
                        .then(res => {
                            this.$store.commit('updatepsdEsay', this.userInfo.password === '123456');
                            this.$nextTick(() => {
                                this.loading = false;
                                this.$router.replace({
                                    name: this.$route.params.name || 'dashboard'
                                });
                            });
                        })
                        .catch(e => {
                            console.log(e);
                            this.loading = false;
                            this.$message.error(e.error);
                        });
                }
            });
        },
        phonelogin() {
            this.$refs.form2.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$http
                        .get('/sms/verify', {
                            phone: this.userInfo.phone,
                            code: this.userInfo.code
                        })
                        .then(() => {
                            return this.$http.post('/auth/phoneLogin', {
                                phone: this.userInfo.phone
                            });
                        })
                        .catch(e => {
                            return Promise.reject(e);
                        })
                        .then(res => {
                            sessionStorage.setItem('token', res);
                            return this.$store.dispatch('getUserInfo');
                        })
                        .then(res => {
                            this.$nextTick(() => {
                                this.loading = false;
                                this.$router.replace({
                                    name: this.$route.params.name || 'dashboard'
                                });
                            });
                        })
                        .catch(e => {
                            console.log(e);
                            this.loading = false;
                            this.$message.error(e.error);
                        });
                }
            });
        },
        doRegister() {
            this.$refs.registerForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$http
                        .post(
                            '/user/regOrganization',
                            // {
                            // username: this.registerInfo.username,
                            // password: this.registerInfo.password
                            // },
                            this.registerInfo,
                            { body: 'json' }
                        )
                        .then(res => {
                            this.loading = false;
                            this.$message.success('注册成功');
                            this.register = false;
                        })
                        .catch(e => {
                            console.log(e);
                            this.loading = false;
                            this.$message.error(e.error);
                        });
                }
            });
        },
        sendMsg() {
            if (!/^1[3-9]\d{9}$/.test(this.userInfo.phone)) {
                this.$message.warning('手机号格式错误');
                return;
            }
            this.sending = true;
            this.$http
                .get('/sms/sendVerify', {
                    phone: this.userInfo.phone
                })
                .then(res => {
                    this.sending = false;
                    this.checkTime();
                })
                .catch(e => {
                    this.sending = false;
                    console.log(e);
                    this.$message.error(e.error);
                });
        },
        checkTime() {
            this.time = 60;
            let i = setInterval(() => {
                this.time--;
                if (this.time === 0) {
                    clearInterval(i);
                }
            }, 1000);
        },
        setDistrictCode(res) {
            let data = this.districtOptions.find(item => {
                return item.label == res;
            });
            this.registerInfo.districtCode = data.value;
        },
        setGradingCode(res) {
            let index = res;
            if (res.length > 1) {
                index = res[0];
            }
            let data = this.examination.find(item => {
                return item.value == index;
            });
            console.log(data.code);
            this.registerInfo.gradingCode = data.code;
        }
    }
};
</script>
<style lang="less" scoped>
.container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ebebeb;
    background-image: url('https://microball.oss-cn-hangzhou.aliyuncs.com/izouma/application/rawpixel-com-565462-unsplash%20%281%29.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    position: relative;
    overflow: hidden;
}

.login-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: white;
    border: 1px #eaeaea solid;
    position: absolute;
    right: 16vw;
    top: 50%;
    width: 540px;
    transform: translateY(-50%);
    border-radius: 20px;

    .title {
        font-size: 25px;
        font-weight: bold;
        color: #313233;
        line-height: 33px;
        text-align: center;
        padding: 45px 0 40px;
    }
    .register-title {
        color: #20a0ff;
        font-weight: bold;
        font-size: 15px;
    }
}
.el-tab-pane {
    padding: 15px 0 15px;
}
@media screen and (max-width: 600px) {
    .login-wrapper {
        right: 0;
        left: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        height: 265px;
        width: calc(100vw - 30px);
    }
}
.slide-in-enter {
    opacity: 0;
    transform: translateX(50%);
}
.slide-in-enter-active {
    transition: all 0.3s;
}
.slide-in-leave-active {
    opacity: 0;
    transform: translateX(-50%);
    transition: all 0.3s;
}
.slide-out-enter {
    opacity: 0;
    transform: translateX(-50%);
}
.slide-out-enter-active {
    transition: all 0.3s;
}
.slide-out-leave-active {
    opacity: 0;
    transform: translateX(50%);
    transition: all 0.3s;
}

.tab-list {
    width: 380px;
}

/deep/ .el-button--text {
    margin-left: 220px;
}
/deep/ .el-form-item__label {
    width: 110px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 44px;
}
/deep/ .el-form-item__content {
    display: flex;
    align-items: center;
}

.code {
    display: flex;
    width: 100%;
    .el-button {
        margin-left: 15px;
        min-width: 120px;
    }

    .el-input {
        flex-grow: 1;
    }
}
.el-form-item {
    margin-bottom: 16px;
}

.login-btn {
    padding-top: 8px;
    margin-bottom: 60px;
    .el-button {
        padding: 14px 12px;
    }
}
// .input-width {
//     width: 285px;
// }
</style>
<style lang="less">
.login-wrapper {
    .el-input {
        input {
            background: #f5f7fa;
            border-radius: 8px;
            border-width: 0px;
            height: 44px;
            line-height: 44px;
        }
    }
}
</style>
