<template>
  <div class="personal-center">
    <el-card class="box-card">

      <el-descriptions title="个人中心" border :column="3">
          <template #extra>
            <el-button type="primary" @click="passwordChangeVisible=true">修改密码</el-button>
            <!-- <el-button type="primary" @click="infoChangeVisible=true">修改信息</el-button> -->
          </template>
        <!-- <el-descriptions-item :rowspan="3" :width="120" label="头像">
          <el-avatar align="center" style="width: 100px; height: 100px" :src="user.userAvatar"/>
        </el-descriptions-item> -->
        <el-descriptions-item label="姓名">{{ user.name }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          {{ user.role == 'STUDENT' ? '学生' : '教师'}}
          <!-- <el-tag size="small">{{ user.role == 'STUDENT' ? '学生' : '教师'}}</el-tag> -->
        </el-descriptions-item>
        <el-descriptions-item label="账号">{{ user.officialNumber }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ user.officialEmail }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>

  <el-dialog v-model="passwordChangeVisible" title="修改密码">
    <el-form :rules="rules" :model="passwordChangeDTO" label-width="auto" ref="formRef">
      <!--邮箱-->
      <!-- <el-form-item prop="officialEmail">
        <el-input v-model="passwordChangeDTO.officialEmail" placeholder="请输入邮箱"></el-input>
      </el-form-item> -->
      <!--密码-->
      <el-form-item prop="password1">
        <el-input v-model="passwordChangeDTO.password1" placeholder="请输入新密码" show-password></el-input>
      </el-form-item>
      <!--再次输入密码-->
      <el-form-item prop="password2">
        <el-input v-model="passwordChangeDTO.password2" placeholder="请再次输入密码" show-password></el-input>
      </el-form-item>
      <!--输入验证码-->
      <el-form-item prop="verifyCode">
        <el-input v-model="passwordChangeDTO.verifyCode" placeholder="向邮箱发生验证码，输入验证码">
          <template #suffix>
            <el-button type="text" @click="sendPasswordChangeVerifyCode" :disabled="isStart">
              {{ isStart ? countdown : '获取验证码' }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="passwordChangeVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword(formRef)">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="infoChangeVisible" title="编辑">
    <el-form :model="userUpdateDTO" label-width="auto" ref="formRef">
      <el-form-item label="头像">
        <el-upload
            ref="uploadRef"
            drag
            action="/api/file"
            multiple
            v-model:file-list="fileList"
            :limit="1"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            list-type="picture-card"
            accept=".png, .jpg"
            :auto-upload="false"
        >
          <div class="el-upload__text">
            拖拽上传或<em>点击此处上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png 文件不大于 500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="姓名" >
        <el-input v-model="user.name" placeholder="请输入名称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="infoChangeVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import {onMounted, reactive, ref} from 'vue';
  import {
    ElCard,
    ElRow,
    ElCol,
    ElAvatar,
    ElButton,
    ElDescriptions,
    ElDescriptionsItem,
    ElTable,
    ElTableColumn,
    ElMessage, 
    type FormRules,
    type UploadUserFile, type UploadProps, type UploadFile, type UploadFiles, type FormInstance
  } from 'element-plus';
    import useApis from "@/apis";
    import {useStore} from "@/store";
  import type {IUser} from "@/types/user";
  import {convertIUserToUserUpdateDTO} from "@/utils/convertUtil";
  import type {UserUpdateDTO} from "@/types/dto";
  import {useFormatDate} from "@/hooks/useFormatDate";
  import { useCountdown } from '@/hooks/useCountdown';

  const apis = useApis()
  const store = useStore()
  const { start, isStart, countdown } = useCountdown();

  const rules = reactive<FormRules<passwordChangeDTO>>({
    officialEmail: [
      {
        required: true,
        message: "邮箱不能为空",
        trigger: 'blur'
      }
    ],
    password1: [
      {
        required: true,
        message: "请输入密码",
        trigger: 'blur'
      }
    ],
    password2: [
      {
        required: true,
        message: "请再次输入密码",
        trigger: 'blur'
      }
    ],
    verifyCode: [
      {
        required: true,
        message: "验证码不能为空",
        trigger: 'blur'
      }
    ]
  })

  const formRef = ref<FormInstance>()
  type passwordChangeDTO = {
    officialEmail: "",
    password1: "",
    password2: "",
    verifyCode: ""
  }
  let passwordChangeDTO = reactive<passwordChangeDTO>({} as passwordChangeDTO)

  const user = reactive<IUser>({} as IUser)
  let userUpdateDTO = reactive<UserUpdateDTO>({} as UserUpdateDTO)
  let infoChangeVisible = ref(false)
  let passwordChangeVisible = ref(false)
  const uploadRef = ref()
  // 用于编辑头像展示预览图片
  const fileList = ref<UploadUserFile[]>([])

  const fetchUserData = () => {
    apis.findUserById(store.user.id)
        .then((res:any) => {
          let data = res.data.data.records[0]
          Object.assign(user, data)
          Object.assign(userUpdateDTO, convertIUserToUserUpdateDTO(user))
          if(user.userAvatar == null) {
            user.userAvatar = "https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
          }
        })
        .catch((err:any) => {
          ElMessage({message: "获取用户信息失败:"+err, type: "error"})
        })
  }


  const handleSubmit = () => {
    console.log(userUpdateDTO)
    return
    apis.updateUser(user.id, userUpdateDTO)
        .then((res:any) => {
          ElMessage({message: "个人信息修改成功", type: "success"})
          fetchUserData()
        })
        .catch((err:any) => {
          ElMessage({message: "个人信息修改失败", type: "error"})
          console.log(err)
        })
        .finally(() => {
          infoChangeVisible.value = false
        })
  }

  const handleSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.log("上传成功", response.data)
    userUpdateDTO.userAvatar = response.data
  }

  const handleError: UploadProps['onError'] = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.log("上传失败", error)
    console.log(error, uploadFile, uploadFiles)
  }

  const handleExceed = (files, fileList) => {
    uploadRef.value.clearFiles()  //清空上传文件（限制一个，所以直接清空即可）
    const file = files[0]
    uploadRef.value.handleStart(file)  //重新上传
  }

  //选择文件
  const handleChange = (file,fileList) => {
    const fileImgType = file.name.match(/\.([^\.]+)$/)[1];  //匹配文件格式（最后一个'.'后的格式）或者匹配file.raw.type
    const isImageType = ['png','jpg'];
    const isLt5KB = file.size / 1024  < 500;  //判断图片格式与大小
    if (isImageType.indexOf(fileImgType)==-1) {
      ElMessage.error('文件仅支持png、jpg格式')  //限制文件类型
      uploadRef.value.clearFiles()  //清空上传文件
      return false;
    }
    if (!isLt5KB) {
      ElMessage.error('文件不能超过500kb!')  //限制文件大小
      uploadRef.value.clearFiles()  //清空上传文件
      return false;
    }
    ElMessage.warning('请等待头像上传成功后，再保存信息')
    apis.uploadFile(file.raw)
        .then((res) => {
          userUpdateDTO.userAvatar = res.data.data.split('?')[0]
          ElMessage.success('头像上传成功')
        })
        .catch((err) => {
          console.log(err)
          ElMessage.error('头像上传失败')
        })
  }

  onMounted(() => {
    fetchUserData()
  })

  const sendPasswordChangeVerifyCode = () => {
    passwordChangeDTO.officialEmail = JSON.parse(localStorage.getItem("User")).officialEmail
    start();
    console.log(passwordChangeDTO)
    apis.sendPasswordChangeVerifyCode(passwordChangeDTO.officialEmail)
    .then((res: any) => {
      if (res.data.code === 200) {
        ElMessage({message: '验证码发送成功，请前往您的邮箱查看',type: 'success'})
      } else {
        ElMessage({message: '验证码发送失败' + res.data.msg, type: 'error'})
      }
    })
    .catch((err: any) => {
      ElMessage({message: '验证码发送失败',type: 'error'})
      console.log(err)
    })
    .finally(() => {});
  }

  const changePassword = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        if(passwordChangeDTO.password1 != passwordChangeDTO.password2) {
          ElMessage({message: '两次输入密码不一致', type: 'error'})
          return
        } 
        let data = {
          officialEmail: passwordChangeDTO.officialEmail,
          password: passwordChangeDTO.password1,
          verifyCode: passwordChangeDTO.verifyCode
        }
        apis.updatePassword(data).then((res: any) => {
          if (res.data.code === 200) {
            ElMessage({message: '密码修改成功',type: 'success'})
            passwordChangeVisible.value = false
            passwordChangeDTO.password1 = ''
            passwordChangeDTO.password2 = ''
            passwordChangeDTO.verifyCode = ''
          } else {
            ElMessage({message: '密码修改失败' + res.data.msg, type: 'error'})
          }
        }).catch((err: any) => {
          ElMessage({message: '网络错误',type: 'error'})
          console.log(err)
        }).finally(() => {});
      } else {
        ElMessage({message: '请将信息填写完整',type: 'warning'})
      }
    })
  }
    
</script>

<style scoped>
.personal-center {
  padding: 20px;
}

.box-card {
  width: 1000px;
  margin: 0 auto;
}

.main-info div {
  margin: 20px 0
}
</style>