<template>
  <div class="login" style="text-align: center;width: 100%">
    <el-card class="box-card" style="text-align: center" v-loading="loading">
      <div style="flex:1;margin: 0 auto">
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
        >
            <el-form-item><p style="font-size: 30px">登录</p></el-form-item>
            <el-form-item label="" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入账号"></el-input>
            </el-form-item>
              <el-form-item label="" prop="pass">
                <el-input
                  type="password"
                  v-model="ruleForm.pass"
                  autocomplete="off"
                  placeholder="请输入密码"
                  show-password
                ></el-input>
              </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
              >登录</el-button
              >
              <el-button @click="resetForm('ruleForm')">清空</el-button>
            </el-form-item>

          <el-form-item>
            <el-link target="_blank" @click="$router.push({ path: '/register' })"
            >没有账号?</el-link
            >
            <el-link type="primary" @click="$router.push({ path: '/register' })"
            >去注册</el-link
            >
          </el-form-item>

          <el-form-item>
            <div style="width: 100%">
              <el-divider>其他登录</el-divider>
              <div style="display: flex;width: 100%">
              <div style="width:50%;text-align: center">
                <img src="https://ts2.cn.mm.bing.net/th?id=ODLS.f9daea21-9936-4164-815f-b5209459f3c6&w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2" style="width:10px;line-height: 56px"/>
                <el-link type="primary" @click="thirdLogin('azure')"
                >微软登录（alpha阶段）</el-link
                >
              </div>
              <div style="width:50%;text-align: center">
                <img src="https://sola.gtimg.cn/aoi/sola/20210118201807_hzF9zYwEBj.png" style="width:10px;line-height: 56px"/>
                <el-link type="primary" @click="thirdLogin('qq')"
                >QQ登录</el-link
                >
              </div>
              </div>
            </div>
          </el-form-item>

        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import store from '@/store'
export default {
    name: 'Login',
    data () {
        const checkName = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('账号不能为空'))
            }
            setTimeout(() => {
                if (value.length < 2) {
                    callback(new Error('名字至少两位'))
                } else {
                    callback()
                }
            }, 1000)
        }
        const validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('密码不能为空'))
            } else {
                callback()
            }
        }
        return {
            loading: false,
            // baseUrl:"http://127.0.0.1/user/login/",
            baseUrl: '/api/',
            // baseUrl: 'http://yongma16.xyz/user/login/',
            ruleForm: {
                pass: '',
                // checkPass: '',
                name: ''
            },
            rules: {
                pass: [{ validator: validatePass, trigger: 'blur' }],
                checkPass: [{ validator: validatePass, trigger: 'blur' }],
                name: [{ validator: checkName, trigger: 'blur' }]
            },
            thirdLoginConfig: {
                azureUrl: '',
                qqUrl: '',
                qCode: '',
                qState: '',
                qToken: '',
                qOpenid: '',
                qUserInfo: ''
            }
        }
    },
    mounted () {
        this.getThirdLoginUrl()
    },
    methods: {
        getThirdLoginUrl () {
            console.log('init')
        },
        thirdLogin (type) {
            if (type === 'azure') {
                this.azureLogin()
            } else {
                this.qqLogin()
            }
        },
        async azureLogin () {
            try {
                const that = this
                // qq
                const res = await that.getAzureUrl()
                console.log('res azureLogin', res)
                if (res.data && res.data.data) {
                    const resData = res.data.data
                    console.log('resData', resData)
                    if (res.data.code === 200) {
                        let url = resData
                        console.log('url', url)
                        const openHandle = window.open(url, 'width:800px;height:700px', '_black')
                        console.log('openHandle', openHandle)
                        window.onmessage = async (res) => {
                            const {origin, data} = res
                            if (origin.includes('yongma16.xyz')) {
                                const {code, state} = data
                                console.log('code state', code, state)
                                that.thirdLoginConfig.qCode = code
                                that.thirdLoginConfig.qState = state
                                if (openHandle) {
                                    openHandle.close()
                                }
                                if (code) {
                                    await that.getAzureToken(code)
                                }
                            }
                        }
                    }
                }
                return new Promise(resolve => {
                    resolve(true)
                })
            } catch (e) {
                return new Promise((resolve, reject) => {
                    reject(e)
                })
            }
        },
        getAzureUrl () {
            return new Promise(async (resolve, reject) => {
                try {
                    const azureAuthUrl = '/third-login/getAzureAuthUrl'
                    const azureRes = await this.$axios.get(azureAuthUrl)
                    console.log('azureRes', azureRes)
                    resolve(azureRes)
                } catch (e) {
                    reject(e)
                }
            })
        },
        async getAzureToken (code) {
            try {
                const azureAuthTokenUrl = '/third-login/getAzureToken'
                const params = {
                    code
                }
                const azureRes = await this.$axios.get(azureAuthTokenUrl, {params})
                console.log('azureRes', azureRes)
            } catch (e) {
                console.log('e', e)
            } finally {
                this.$message.info('微软登录还在alpha测试阶段！')
            }
        },
        async qqLogin () {
            try {
                const that = this
                // qq
                const res = await that.$axios
                    .post(that.baseUrl + 'dictModel/index/', {
                        kind: 'qqThirdLogin'
                        // 传入索引
                    })
                console.log('res', res)
                if (res.data && res.data.data) {
                    const resData = res.data.data
                    console.log('resData', resData)
                    if (res.data.code === 200) {
                        let url = resData[0].option
                        console.log('url', url)
                        const openHandle = window.open(url, 'width:800px;height:700px', '_black')
                        console.log('openHandle', openHandle)
                        window.onmessage = async (res) => {
                            const {origin, data} = res
                            if (origin.includes('yongma16.xyz')) {
                                const {code, state} = data
                                console.log('code state', code, state)
                                that.thirdLoginConfig.qCode = code
                                that.thirdLoginConfig.qState = state
                                if (openHandle) {
                                    openHandle.close()
                                }
                                const tokenRes = await that.getAccessToken(code)
                                console.log('tokenRes', tokenRes)
                            }
                        }
                    }
                }
                return new Promise(resolve => {
                    resolve(true)
                })
            } catch (e) {
                return new Promise((resolve, reject) => {
                    reject(e)
                })
            }
        },
        async getAccessToken (code) {
            try {
                const tokenUrl = '/third-login/getToken'
                const params = {
                    code
                }
                const tokenRes = await this.$axios.get(tokenUrl, {params})

                console.log('tokenRes', tokenRes)
                if (tokenRes) {
                    const {access_token, expires_in, refresh_token} = tokenRes.data.data
                    if (access_token) {
                        this.thirdLoginConfig.qToken = access_token
                        await this.getOpenId(access_token)
                    }
                }
            } catch (e) {
                console.log('token error', e)
            }
        },
        async getOpenId (token) {
            try {
                const tokenUrl = '/third-login/getOpenId'
                const params = {
                    access_token: token
                }
                const openIdRes = await this.$axios.get(tokenUrl, {params})
                console.log('openIdRes', openIdRes)
                if (openIdRes) {
                    const {openid} = openIdRes.data.data
                    if (openid) {
                        this.thirdLoginConfig.qOpenid = openid
                        await this.getQUserinfo(this.thirdLoginConfig.qToken, openid)
                    }
                }
            } catch (e) {
                console.log('token error', e)
            }
        },
        async getQUserinfo (token, openId) {
            try {
                const userInfoUrl = '/third-login/getUserInfo'
                const params = {
                    access_token: token,
                    openId: openId
                }
                const userRes = await this.$axios.get(userInfoUrl, {params})
                if (userRes) {
                    this.thirdLoginConfig.qUserInfo = userRes.data.data
                    this.registerThirdLogin()
                }
                console.log('userRes', userRes)
            } catch (e) {
                console.log('token error', e)
            }
        },
        submitForm (formName) {
            localStorage.removeItem('thirdUserInfo')
            const that = this // this指向
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true
                    // 提交数据
                    const loginUrl = that.baseUrl + 'user/login/'
                    const userInfo = {
                        name: that.ruleForm.name,
                        password: that.ruleForm.pass
                    }
                    that.$axios
                        .post(loginUrl, userInfo)
                        .then((res) => {
                            // alter('提交中');
                            if (res.data.code === 1) {
                                localStorage.setItem(
                                    'yma16siteUserInfo',
                                    JSON.stringify({
                                        username: userInfo.name,
                                        password: userInfo.password
                                    })
                                )
                                store.commit('setUserInfo', userInfo) // store信息
                                document.cookie = `user=${that.ruleForm.name}`
                                that.$router.push({ path: '/' })
                                // 添加cookie
                            } else if (res.data.code === 0) {
                                // alter("失败！" res.data.msg)
                                that.$message.error('用户名或密码错误')
                            }
                            that.loading = false
                        })
                        .catch((error) => {
                            that.loading = false
                            that.$message.error(error)
                        })
                } else {
                    return false
                }
            })
        },
        async registerThirdLogin () {
            const that = this
            return new Promise(async (resolve, reject) => {
                const loading = that.$loading({
                    lock: true,
                    text: '登录中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })
                try {
                    const res = await that.$axios
                        .post(that.baseUrl + 'user/register/', {
                            // 传递的名字和密码
                            name: that.thirdLoginConfig.qOpenid,
                            password: that.thirdLoginConfig.qOpenid
                        })
                    if (res.data.code === 0) {
                        console.log('重复注册')
                    }
                    const userInfo = {
                        username: that.thirdLoginConfig.qOpenid,
                        password: that.thirdLoginConfig.qOpenid,
                        thirdUserInfo: that.thirdLoginConfig.qUserInfo
                    }
                    store.commit('setUserInfo', userInfo) // store信息
                    localStorage.setItem(
                        'yma16siteUserInfo',
                        JSON.stringify(userInfo)
                    )
                    localStorage.setItem(
                        'thirdUserInfo',
                        JSON.stringify({
                            qOpenid: that.thirdLoginConfig.qOpenid,
                            nickName: that.thirdLoginConfig.nickName
                        })
                    )
                    that.$router.push({ path: '/' })
                    loading.close()
                    resolve(userInfo)
                } catch (e) {
                    console.log('注册三方账号失败')
                    loading.close()
                    reject(e)
                }
            })
        },
        resetForm (formName) {
            this.$refs[formName].resetFields()
        }
    }
}
</script>

<style scoped>
.login {
  position: relative;
  width: 100%;
  height: auto;
}
.box-card {
  position: relative;
  display: flex;
  max-width: 450px;
  margin: 0 auto;
  margin-top: 80px;
  background-color: rgba(255,255,255,.95);
  box-sizing: border-box;
}
/deep/ .el-card__body{
  width: 100% !important;
}

  /deep/ .el-divider__text{
    background-color: transparent !important;
  }
</style>
