<template>
  <div class="top">
    <div class="title">
      <!-- <img src="@/assets/image/img_login_logo.png"> -->
      <h2>中免VR商城</h2>
    </div>
    <div class="oper-btns">
      <div class="info">
        <img src="@/assets/image/top_my.png">
        <span>{{info.nickName}}</span>
        <span>{{info.userName}}</span>
      </div>
      <span @click="data.show = true"><img src="@/assets/image/top_set.png"></span>
      <span @click="logout"><img src="@/assets/image/top_exit.png"></span>
    </div>
  </div>
  
  <com-dialog title="修改密碼" v-model:show="data.show" @submit="updatePsw">
    <el-form ref="form" :model="data" label-width="100px" class="info-from">
      <el-form-item label="舊密碼：" class="mandatory">
        <el-input v-model="data.oldPassword" type="password" placeholder="請輸入當前密碼"></el-input>
      </el-form-item>
      <el-form-item label="新密碼：" class="mandatory">
        <el-input v-model="data.password" type="password" placeholder="必須包含數字、字母，長度8-16個字符"></el-input>
      </el-form-item>
      <el-form-item label="確認密碼：" class="mandatory">
        <el-input v-model="data.confimPsw" type="password" placeholder="必須包含數字、字母，長度8-16個字符"></el-input>
      </el-form-item>
    </el-form>

  </com-dialog>

</template>
<script>
import { encryption } from '@/util'
import comDialog from "@/components/dialog";
import axios from 'axios';
import { updateUserPWD, userLogout } from '@/request/config'
import { setToken, setInfo,setRole } from '@/state/user'
import { computed, ref } from 'vue'
import user from '@/state/user'
import {PSW} from '@/constant/REG'
import { openErrorMsg } from '@/request/errorMsg.js'

export default {
  setup() {
    const data = ref({show: false, oldPassword: '', password: '', confimPsw: ''})
    const info = computed(() => user.value.info)

    return { data, info }
  },
  methods: {
    async updatePsw() {
      if (this.data.oldPassword.length === 0) {
        return this.$alert('請輸入舊密碼', '提示')
      }
      if (this.data.password !== this.data.confimPsw) {
        return this.$alert('兩次密碼不一致！', '提示')
      }
      if (!PSW.REG.test(this.data.password)) {
        return this.$alert(PSW.tip, '提示')
      }
      

      await axios.post(updateUserPWD, {
        oldPassword: encryption(this.data.oldPassword),
        newPassword: encryption(this.data.password)
      })

      this.data.show = false
      this.data.oldPassword = this.data.password = this.data.confimPsw = ''

      openErrorMsg('密碼修改成功，請重新登錄。')

      this._loginout()
    },
    async _loginout() {
      await axios.post(userLogout)
      setToken('')
      setInfo({})
      setRole('')
      this.$router.replace({name: 'login'})
    },
    async logout() {
      if (await this.$confirm('確定要退出登錄嗎？', '提示')) {
        this._loginout()
      }
    }
  },
  components: {
    "com-dialog": comDialog,
  },
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
