<template>
    <div class="userInfoWarp">
        <div class="left">
            <div class="avater">
                <el-upload
                    v-if="isEdit"
                    :show-file-list="false"
                    :http-request="customRequest"
                    :before-upload="beforeAvatarUpload"
                    :limit="1"
                >
                    <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
                <img
                    v-else
                    :src="originForm.avatar"
                    alt=""
                />
            </div>
            <div class="desc">你好，尊敬的用户 {{ originForm.name }}</div>
            <div class="info">
                <div class="info_item">
                    <div class="item_icon">
                        <img src="../../assets/images/Slice12x.png" alt="" />
                    </div>
                    <div class="">用户名：{{ originForm.name }}</div>
                </div>
                <div class="info_item">
                    <div class="item_icon">
                        <img src="../../assets/images/Slice22x.png" alt="" />
                    </div>
                    <div class="">用户ID：{{ originForm.userName }}</div>
                </div>
                <div class="info_item">
                    <div class="item_icon">
                        <img src="../../assets/images/Slice32x.png" alt="" />
                    </div>
                    <div class="">性别：隐藏</div>
                </div>
                <div class="info_item">
                    <div class="item_icon">
                        <img src="../../assets/images/Slice42x.png" alt="" />
                    </div>
                    <div class="">登录时间：{{ originForm.lastLoginDate }}</div>
                </div>
            </div>
        </div>
        <div class="middle"></div>
        <div class="right">
            <div class="title">
                <div class="titlemodf"></div>
                <div>账号信息</div>
            </div>
            <div class="setWarp">
                <div class="setInput">
                    <div class="name">姓名</div>
                    <div class="gk"></div>
                    <div class="ipt">
                        <input v-if="isEdit" v-model="form.name" placeholder="请输入姓名" type="text" />
                        <p v-else>{{ form.name || '--' }}</p>
                    </div>
                    <template v-if="!isEdit">
                        <div v-if="form.name" class="idft">已设置</div>
                        <div v-else class="idft red">未设置</div>
                    </template>
                </div>
                <div class="setInput">
                    <div class="name">安全手机</div>
                    <div class="gk"></div>
                    <div class="ipt">
                        <input v-if="isEdit" v-model="form.mobile" placeholder="请输入手机号" type="text" />
                        <p v-else>{{ form.mobile || '--' }}</p>
                    </div>
                    <template v-if="!isEdit">
                        <div v-if="form.mobile" class="idft">已设置</div>
                        <div v-else class="idft red">未设置</div>
                    </template>
                </div>
                <div class="setInput">
                    <div class="name">安全邮箱</div>
                    <div class="gk"></div>
                    <div class="ipt">
                        <input v-if="isEdit" v-model="form.email" placeholder="请输入安全邮箱" type="text" />
                        <p v-else>{{ form.email || '--' }}</p>
                    </div>
                    <template v-if="!isEdit">
                        <div v-if="form.email" class="idft">已设置</div>
                        <div v-else class="idft red">未设置</div>
                    </template>
                </div>
            </div>
            <div class="btnWarp">
                <div class="editBtn" @click="changeInfo">{{ isEdit ? '保存' : '编辑用户信息' }}</div>
                <div v-if="isEdit" class="editBtn cancel" @click="cancelInfo">取消</div>
                <div class="modBtn" @click="isPwdDialogVisible = true">修改密码</div>
            </div>
        </div>

        <el-dialog v-model="isPwdDialogVisible" title="修改密码" width="500">
            <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="120px">
                <el-form-item label="旧密码" prop="oldPassword">
                    <el-input v-model="pwdForm.oldPassword" type="password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="pwdForm.newPassword" type="password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="enterPassword">
                    <el-input v-model="pwdForm.enterPassword" type="password" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelPassword">取消</el-button>
                    <el-button type="primary" @click="changePassword">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getUserInfo, upChangePassword, updateUserInfo } from '@/api/system/person'
import Folder from "@/api/folder.js";
import { Encrypt } from '@/utils/aes'
import { useUserStore } from '@/store/user.js'
import router from '@/router'

const pwdFormRef = ref(null)
const isPwdDialogVisible = ref(false)
const isEdit = ref(false)
const pwdForm = ref({
    oldPassword: '',
    newPassword: '',
    enterPassword: ''
})
const originForm = ref({
    avatar: null,
    email: '',
    mobile: '',
    userName: '',
    name: ''
})
const form = ref({
    avatar: null,
    email: '',
    mobile: '',
    name: ''
})

const pwdRules = ref({
    oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    enterPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
        // 添加一个自定义校验规则来确保新密码和确认密码一致
        {
            validator: (rule, value, callback) => {
                if (value !== pwdForm.value.newPassword) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            }, trigger: 'blur'
        }
    ]
})

onMounted(() => {
    getList()
})

function getList() {
    getUserInfo().then((res) => {
        if (res.code == 200) {
            originForm.value = res.data
            form.value = { ...originForm.value }
        } else {
            ElMessage({
                message: res.msg,
                type: 'error'
            })
        }
    })
}

function changeInfo() {
    if (!isEdit.value) {
        form.value = { ...originForm.value }
        form.value.avatar = null
        isEdit.value = true
    } else {
        console.log('保存了')
        // 保存
        if (!form.value.mobile.length || !form.value.name.length || !form.value.email.length) {
            ElMessage({
                message: '信息填写不完整',
                type: 'warning'
            })
        } else {
            let { avatar, email, mobile, name } = form.value
            updateUserInfo({
                avatar,
                email,
                mobile,
                name
            }
            ).then((res) => {
                if (res.code == 200) {
                    isEdit.value = false
                    getList()
                    ElMessage({
                        message: '修改成功',
                        type: 'success'
                    })
                }
            })
        }
    }
}

function cancelInfo() {
    isEdit.value = false
    form.value = { ...originForm.value }
}

function changePassword() {
    pwdFormRef.value.validate((valid) => {
        if (valid) {
            // 执行密码修改逻辑
            upChangePassword({
                oldPassword: Encrypt(pwdForm.value.oldPassword),
                newPassword: Encrypt(pwdForm.value.newPassword),
                enterPassword: Encrypt(pwdForm.value.enterPassword)
            }).then((res) => {
                if (res.code == 200) {
                    console.log('密码修改成功', pwdForm.value)
                    cancelPassword()
                    ElMessage.success('密码修改成功')
                    useUserStore().logOut().then(() => {
                        router.push('/login')
                    })
                } else {
                    ElMessage.error(res.msg)
                }
            })
        } else {
            ElMessage.error('表单数据有误，请按提示修改后再提交')
            return false
        }
    })
}

function cancelPassword() {
    pwdForm.value = {
        oldPassword: '',
        newPassword: '',
        enterPassword: ''
    }
    isPwdDialogVisible.value = false
}

function customRequest(content) {
    const dFormData = new FormData()
    dFormData.append('file', content.file)
    Folder.up(dFormData).then((res) => {
        if (res.code == '200') {
            form.value.avatar = res.data.link
        }
    })
}

function beforeAvatarUpload(rawFile) {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') { // 允许JPG和PNG格式
        ElMessage.error('只能上传JPG或PNG格式的图片!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像尺寸不可以大于2MB!')
        return false
    }
    return true
}
</script>

<style lang='scss' scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 113px;
  height: 113px;
  text-align: center;
}

.userInfoWarp {
  width: 100%;
  background: #ffffff;
  display: flex;

  .left {
    width: 40%;
    display: flex;
    flex-direction: column;
    align-items: center;

    font-family: Alibaba PuHuiTi 3, Alibaba PuHuiTi 30;
    font-weight: normal;
    font-size: 16px;
    color: #000000;

    .avater {
      width: 113px;
      height: 113px;
      border-radius: 50%;
      overflow: hidden;
      margin-top: 60px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .desc {
      margin-top: 24px;
    }

    .info {
      margin-top: 96px;

      .info_item {
        display: flex;
        align-items: center;
        margin-bottom: 50px;

        .item_icon {
          width: 32px;
          height: 32px;
          overflow: hidden;
          margin-right: 68px;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }

  .middle {
    height: 600px;
    width: 1px;
    background: #ccc;
    margin: 60px 0;
  }

  .right {
    width: 60%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .title {
      width: 564px;
      text-align: left;
      margin-top: 85px;
      display: flex;
      align-items: center;
      font-family: Alibaba PuHuiTi 3, Alibaba PuHuiTi 30;
      font-weight: normal;
      font-size: 20px;
      color: #000000;

      .titlemodf {
        width: 10px;
        height: 23px;
        background: #0071bb;
        border-radius: 0px 0px 0px 0px;
        margin-right: 17px;
      }
    }

    .setWarp {
      margin-top: 55px;
      margin-bottom: 90px;

      .setInput {
        position: relative;
        width: 564px;
        height: 66px;
        background: #f5f5f5;
        border-radius: 10px 10px 10px 10px;
        margin-bottom: 34px;
        display: flex;
        align-items: center;

        .name {
          font-weight: normal;
          font-size: 16px;
          color: #7b7b7b;
          padding-left: 47px;
          width: 105px;
        }

        .gk {
          width: 1px;
          height: 28px;
          margin-right: 50px;
          background: #cccccc;
        }

        .ipt {
          margin-right: 50px;

          input {
            border: none;
            outline: none;
            height: 22px;
            font-size: 16px;
            color: grey;
            background: #f5f5f5;
            border-bottom: 1px solid #ccc;
          }
        }

        .idft {
          position: absolute;
          right: 20px;
          width: 70px;
          height: 30px;
          line-height: 30px;
          background: #5bd458;
          border-radius: 17px 17px 17px 17px;
          font-size: 14px;
          color: #ffffff;
          text-align: center;

          &.red {
            background: red;
          }
        }
      }
    }

    .btnWarp {
      display: flex;

      .editBtn {
        width: 146px;
        height: 54px;
        line-height: 54px;
        color: #ffffff;
        text-align: center;
        background: #4a75d9;
        border-radius: 10px 10px 10px 10px;
        margin-right: 40px;

        &.cancel {
          background: grey;
        }
      }

      .modBtn {
        width: 146px;
        height: 54px;
        line-height: 54px;
        color: #ffffff;
        text-align: center;
        background: #ff954b;
        border-radius: 10px 10px 10px 10px;
      }
    }
  }
}
</style>