<template>
  <div class="user-info-part">
    <div class="header-box">
      <h3>个人信息</h3>
      <el-icon @click="close">
        <Close/>
      </el-icon>
    </div>
    <div class="custom-tabs">
      <div class="tabs-item" v-for="(item, index) in ['基础信息', '安全信息']" :key="item"
           :class="{ 'active': tabActive === index }" @click="tabActive = index">{{ item }}
      </div>
    </div>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="60">
      <template v-if="tabActive === 0">
        <el-upload action="#" :limit="1" :http-request="handleUpload" ref="uploadRef"
                   :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="formData.avatar" :src="'/api' + formData.avatar" class="avatar"/>
          <img v-else src="@/assets/imgs/home/avatar.png" class="avatar"/>
        </el-upload>
        <el-form-item label="用户名" prop="account">
          <el-input v-model="formData.account" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mailbox">
          <el-input v-model="formData.mailbox" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="密码" prop="password" label-width="100">
          <el-input v-model="formData.password" type="password" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" label-width="100">
          <el-input v-model="formData.newPassword" type="password" show-password placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" label-width="100">
          <el-input v-model="formData.confirmPassword" type="password" show-password
                    placeholder="请输入新密码"></el-input>
        </el-form-item>
      </template>
    </el-form>
    <div class="submit-box">
      <el-button type="primary" @click="submitForm">{{ tabActive === 0 ? '更新个人信息' : '修改密码' }}</el-button>
    </div>
  </div>
</template>

<script lang='ts' setup>
import {onMounted, reactive, ref, toRefs, watch} from 'vue'
import {ElMessage} from 'element-plus'
import type {UploadProps} from 'element-plus'
import {useLoginStore} from '@/stores/user-info-store'
import {editPassword, getUserInfo, updateUserInfo} from "@/api/acl/user";
import {handleHttpUpload} from "@/api/file-upload";

const emit = defineEmits(['close'])

// const userInfo = useLoginStore().getlogin()

const formRef = ref()
const uploadRef = ref()

onMounted(() => {
  getUserInfo().then((res: any) => {
    if (res.data) {
      formData.value.account = res.data.sysUser.username
      formData.value.name = res.data.sysUser.name
      formData.value.phone = res.data.sysUser.phone
      formData.value.mailbox = res.data.sysUser.email
      formData.value.avatar = res.data.sysUser.avatar
    }
  })
})

const validatePassword = (rule: any, value: any, callback: any) => {
  if (formData.value.newPassword !== formData.value.confirmPassword) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}

//自定义校验规则函数
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.length >= 6) {
    callback();
  } else {
    callback(new Error('密码长度至少6位'));
  }
}

const validatorPhone = (rule: any, value: any, callback: any) => {
  var isPhone = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;


  if (value.indexOf('****') >= 0) {
    return callback().trim();
  }

  if (!isPhone.test(value)) {
    callback(new Error('请输入合法手机号'));
  } else {
    callback();
  }
}

const rules = reactive({
  phone: [
    {required: true, validator: validatorPhone, trigger: 'blur'},
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
  ],
  mailbox: [
    {type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change']},
  ],
  password: [
    {required: true, validator: validatorPassword, trigger: 'change'},
  ],
  newPassword: [
    {required: true, validator: validatorPassword, trigger: 'change'},
    //{ validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    {required: true, message: '请输入密码', trigger: 'change'},
    {validator: validatePassword, trigger: 'blur'}
  ]
})
const tabActive = ref(0)
const formData = ref({
  avatar: '',
  account: "",
  phone: '',
  name: "",
  mailbox: '',
  password: '',
  newPassword: '',
  confirmPassword: ''
})

const close = () => {
  emit('close')
}
function handleAvatarSuccess(uploadFile: any) {
}

function handleUpload(options: any) {
  handleHttpUpload(options).then((res: any) => {
    console.log(res)
    if (res && res.code == 0) {
      formData.value.avatar = res.data.url
      const param = {
        avatar: formData.value.avatar,
        username: formData.value.account
      }
      updateUserInfo(param).then((res: any) => {
        uploadRef.value.clearFiles();
        if (res && res.code != 0) {
          ElMessage.error(res.msg)
        }
      })
    } else {
      ElMessage.error('图片格式错误')
    }

  }).catch(err => {
    ElMessage.error('图片格式错误')
    options.onError(err);
  })
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须为jpg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不得超过2MB!')
    return false
  }
  return true
}
const submitForm = async () => {
  await formRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      // console.log('submit!')
      // 更改用户名
      // useLoginStore().setlogin('name', formData.value.name)
      if (tabActive.value == 0) {
        const param = {
          name: formData.value.name,
          phone: formData.value.phone,
          email: formData.value.mailbox,
          username: formData.value.account
        }
        updateUserInfo(param).then((res: any) => {
          if (res && res.code == 0) {
            ElMessage.success('更新成功')
            close()
          } else {
            ElMessage.error(res.msg)
          }
        })
      } else {
        editPassword({
          password: formData.value.password,
          newpassword1: formData.value.newPassword
        }).then((res: any) => {
          if (res && res.code == 0) {
            formRef.value.resetFields(['password', 'newPassword', 'confirmPassword'])
            ElMessage.success("修改密码成功")
            close()
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    } else {
      // console.log('error submit!', fields)
    }
  })
}

</script>

<style lang='scss' scoped>
.user-info-part {
  width: 100%;
  height: 100%;
  padding: 30px;

  .header-box {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      color: $main-color;
      font-size: 20px;
    }

    .el-icon {
      cursor: pointer;
      color: #606266;
    }
  }

  img.avatar {
    width: 128px;
    height: 148px;
    object-fit: contain;
    margin: 0 0 20px 60px;
  }

  .submit-box {
    padding-left: 60px;
  }
}
</style>
