<template>
  <div class="p-20px">
    <p class="mb-30px font-bold text-20px">微信授权登陆</p>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="auto">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入密码" show-password type="password" />
      </el-form-item>
    </el-form>
    <el-button type="primary" :disabled="formLoading" class="w-full" @click="onSubmit">
      授权登陆
    </el-button>
  </div>
</template>

<script setup name="MPLogin">
import { bindWx } from '@/api/login'

const message = useMessage() // 消息弹窗

const form = ref({
  code: undefined,
  username: undefined,
  password: undefined
})
const formRef = ref()
const rules = {
  username: { required: true, message: '用户名不可为空', trigger: 'blur' },
  password: { required: true, message: '密码不可为空', trigger: 'blur' }
}

// 微信授权登陆地址
const WX_AUTH_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?'
// 重定向参数-固定写法
const REDIRECT = '#wechat_redirect'

const params = ref({
  appid: 'wxf87aa1f474c0494f', // 公众号 APP ID
  redirect_uri: ``, // 授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
  response_type: 'code', // 固定写法
  scope: 'snsapi_base' // snsapi_base 静默授权获取 open id ；snsapi_userinfo 需要用户授权，获取详细信息
  // state:'code', // a-zA-Z0-9的参数值，最多128字节
})

const formLoading = ref(false)
async function onSubmit() {
  // 这些需要判断没有 code 情况拉起授权登陆，有就结束放在重复拉起授权登陆
  if (!form.value.code) {
    const access_url = WX_AUTH_URL + `${new URLSearchParams(params.value)}` + REDIRECT
    location.href = access_url
  } else {
    // 校验表单
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return
    // 提交请求
    formLoading.value = true
    try {
      await bindWx(form.value)
      message.success('绑定成功')
      window.close()
    } catch (error) {
      console.log(error)
    } finally {
      formLoading.value = false
    }
  }
}

onMounted(() => {
  const uri = location.origin + location.pathname
  params.value.redirect_uri = encodeURI(uri)
  // 获取地址参数
  const param = new URLSearchParams(location.search)
  form.value.code = param.get('code')

  if (!form.value.code) {
    const access_url = WX_AUTH_URL + `${new URLSearchParams(params.value)}` + REDIRECT
    location.href = access_url
  }
})
</script>

<style lang="scss" scoped></style>
