<template>
    <div class="user-center-container">
      <!-- 用户信息模块 -->
      <el-card class="user-info-card">
        <template #header>
          <div class="card-header">个人信息</div>
        </template>
  
        <!-- 基本信息表单 -->
        <el-form
          ref="userFormRef"
          :model="userForm"
          label-width="100px"
          :rules="userRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" />
          </el-form-item>
          
          <el-form-item label="创建时间" prop="createtime"> 
              <el-date-picker
                v-model="userForm.createtime"
                type="datetime"
                disabled
                format="YYYY/MM/DD HH:mm:ss"
              />
          </el-form-item>

          <el-form-item label="昵称" prop="displayname">
              <el-input v-model="userForm.displayname" />
          </el-form-item>

          <el-form-item label="身份" prop="identity">
            <div class="bind-info">
              <el-input v-model="userForm.identity" disabled/>
            </div>
          </el-form-item>
          
          <el-form-item label="最后登录时间" prop="lastlogin">
            <el-date-picker
                v-model="userForm.lastlogin"
                type="datetime"
                disabled
                format="YYYY/MM/DD HH:mm:ss"
              />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitUserForm">保存修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 账户安全模块 -->
      <el-card class="security-card">
        <template #header>
          <div class="card-header">账户安全</div>
        </template>
        <el-form
          ref="pwdFormRef"
          :model="pwdForm"
          label-width="100px"
          :rules="pwdRules"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="pwdForm.oldPassword"
              type="password"
              show-password
            />
          </el-form-item>
  
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="pwdForm.newPassword"
              type="password"
              show-password
            />
          </el-form-item>
  
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="pwdForm.confirmPassword"
              type="password"
              show-password
            />
          </el-form-item>
  
          <el-form-item>
            <el-button type="primary" @click="submitPwdForm">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { onMounted, ref, computed, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import { getData, postData, deleteData, postFile } from '@/api/axios.js'
  
  // 用户信息数据 
  const userInfo = reactive({
    username: '',
    createtime: '',
    displayname: '',
    identity: '',
    lastlogin: ''
  })
  
  // 用户信息表单
  const userFormRef = ref()
  const userForm = reactive({
    username: '',
    createtime: '',
    displayname: '',
    identity: '',
    lastlogin: ''
  })
  let pastUserForm = {}

  // 密码修改表单
  const pwdFormRef = ref()
  const pwdForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  const userRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 12, message: '长度在2到12个字符', trigger: 'blur' }
    ],
    displayname: [
      { message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 12, message: '长度在2到12个字符', trigger: 'blur' }
    ],
    identity: [
      { required: true, message: '请输入身份', trigger: 'blur' },
    ]
  }
  
  const pwdRules = {
    oldPassword: [
      { required: true, message: '请输入原密码', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { validator: checkPasswordStrength, trigger: 'blur' }
    ],
    confirmPassword: [
      { validator: (rule, value, callback) => {
        if (value !== pwdForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
    ]
  }
  // 获取初始数据
  onMounted(async () => {
    try {
      const response = await getData('/selectUser/')
      console.log(response)
      if(response.status == 'success')
      {
        userForm.username = response.data.username,
        userForm.createtime = new Date(response.data.createtime).toLocaleString('zh-CN');
        userForm.displayname = response.data.displayname,
        userForm.identity = response.data.identity,
        userForm.lastlogin = new Date(response.data.lastlogin).toLocaleString('zh-CN');
        pastUserForm = userForm
      }else{
        ElMessage.error('个人信息查询失败')
      }
    } catch (e){
      ElMessage.error('个人信息查询失败')
    }
  })

  // 密码强度校验
  function checkPasswordStrength(rule, value, callback) {
  if (value.length < 6 || value.length > 20) { // 使用参数 value
    callback(new Error('密码长度需为6-20位'))
  } else {
    callback()
  }
  }
  
  // 提交表单
  const submitUserForm = async () => {
    try {
      await userFormRef.value.validate()
      // 调用API保存数据
      const response = await postData('/updateUser/',{
        displayname:userForm.displayname,
        identity:userForm.identity
      })
      if(response.status == 'success')
      {
        userForm.username = response.data.username,
        userForm.createtime = new Date(response.data.createtime).toLocaleString('zh-CN');
        userForm.displayname = response.data.displayname,
        userForm.identity = response.data.identity,
        userForm.lastlogin = new Date(response.data.lastlogin).toLocaleString('zh-CN');
        pastUserForm = userForm
        ElMessage.success('个人信息更新成功')
      }else
      {
        userForm.username = pastUserForm.username,
        userForm.createtime = new Date(pastUserForm.createtime).toLocaleString('zh-CN');
        userForm.displayname = pastUserForm.displayname,
        userForm.identity = pastUserForm.identity,
        userForm.lastlogin = new Date(pastUserForm.lastlogin).toLocaleString('zh-CN');
        ElMessage.error('个人信息更新失败')
      }
    } catch (e) {
      userForm.username = pastUserForm.username,
      userForm.createtime = new Date(pastUserForm.createtime).toLocaleString('zh-CN');
      userForm.displayname = pastUserForm.displayname,
      userForm.identity = pastUserForm.identity,
      userForm.lastlogin = new Date(pastUserForm.lastlogin).toLocaleString('zh-CN');
      ElMessage.error('个人信息更新失败')
    }
  }
  
  const submitPwdForm = async () => {
    try {
      await pwdFormRef.value.validate()
      // 调用API修改密码
      const response = await postData('/updatePass/',{
        oldPassword: pwdForm.oldPassword,
        newPassword: pwdForm.oldPassword,
      })
      if(response.status == 'success')
      {
        ElMessage.success('密码修改成功')
        pwdFormRef.value.resetFields();
      }
    } catch (error) {
      console.error('密码修改失败', error)
      pwdForm.oldPassword = ''
      pwdForm.newPassword = ''
      pwdForm.confirmPassword = ''
      ElMessage.error("密码修改失败：" + error.response.data.message)
    }
  }
  </script>
  
  <style scoped>
  .user-center-container {
    max-width: 800px;
    margin: 20px auto;
  }
  
  .avatar-uploader {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
  }
  
  .avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
  }
  
  .bind-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }
  
  .security-card {
    margin-top: 20px;
  }
  </style>