<template>
  <div>
    <div class="userInfoBox">
      <tableTitle :name="tableDivTitle"/>
      <div class="userInfoTabs">
        <el-tabs :tab-position="tabPosition" style="height:350px" class="demo-tabs">
          <el-tab-pane label="用户信息">
            <el-form :model="infoform" ref="infoform" :rules="infoFormRules" autocomplete="off" label-position="left">
              <div class="infoBox">
                <div>
                  <!-- <img :src="user.avatar" class="avatar"> -->
                  <el-form-item label="头像：" prop="avatar" :label-width="formLabelWidth" :class="['custom-form-item']" class="custom-align-right">
                    <div class="uploaderBox">
                      <!--图片上传组件 start ------------------------------------------------------------>
                      <div class="avatar-upload-container" @mouseenter="hovering = true" @mouseleave="hovering = false">
                        <!-- 上传组件 -->
                        <el-upload
                          class="avatar-uploader"
                          action="#"
                          :show-file-list="false"
                          :before-upload="beforeAvatarUpload"
                        >
                          <!-- 预览图片 -->
                          <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
                          <!-- 上传图标 -->
                          <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                          <div v-else class="chooseImgDiv">
                            <div>
                              <img src="@/assets/public/upload/noImage.png">
                              <div>选择图片</div>
                            </div>
                          </div>
                          <input type="hidden" v-model="infoform.avatar">
                        </el-upload>
                        <!-- 删除按钮，当鼠标悬浮时显示 -->
                        <div v-if="hovering && avatarUrl" class="delete-button" @click="handleDelete">
                          <i class="el-icon-delete"></i>
                        </div>
                      </div>
                      <!--图片上传组件 end ------------------------------------------------------------>
                    </div>
                  </el-form-item>
                  <el-form-item label="昵称：" :label-width="formLabelWidth" prop="nickname" class="custom-align-right">
                    <el-input v-model="infoform.nickname" autocomplete="off" placeholder="请输入用户昵称.."></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-form>
            <div class="infoBtnBox">
              <el-button type="primary" @click="changeInfo">保存</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane label="修改密码">
            <el-form ref="form" :model="form" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
              <!--现有密码 start------------------------------------------>
              <el-tooltip v-model="capsTooltip1" content="大小写已开启！" placement="right" manual>
                <div class="PasswordBox">
                  <div class="PasswordTitle">现有密码：</div>
                  <el-form-item prop="password">
                    <div class="PasswordBody">
                      <el-input
                        :key="passwordType1"
                        ref="password1"
                        v-model="form.password"
                        :type="passwordType1"
                        placeholder="请输入密码"
                        name="password"
                        tabindex="2"
                        autocomplete="off"
                        @blur="capsTooltip1 = false"
                      />
                      <span class="show-pwd" @click="showPwd(1)">
                        <svg-icon :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'" />
                      </span>
                    </div>
                  </el-form-item>
                </div>
              </el-tooltip>
              <!--现有密码 end------------------------------------------>
              <!--新密码 start------------------------------------------>
              <el-tooltip v-model="capsTooltip2" content="大小写已开启！" placement="right" manual>
                <div class="PasswordBox">
                  <div class="PasswordTitle">新密码：</div>
                  <el-form-item prop="new_password">
                    <div class="PasswordBody">
                      <el-input
                        :key="passwordType2"
                        ref="password2"
                        v-model="form.new_password"
                        :type="passwordType2"
                        placeholder="请输入密码"
                        name="password"
                        tabindex="2"
                        autocomplete="off"
                        @blur="capsTooltip2 = false"
                      />
                      <span class="show-pwd" @click="showPwd(2)">
                        <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
                      </span>
                    </div>
                  </el-form-item>
                </div>
              </el-tooltip>
              <!--新密码 end------------------------------------------>
              <!--新密码 start------------------------------------------>
              <el-tooltip v-model="capsTooltip3" content="大小写已开启！" placement="right" manual>
                <div class="PasswordBox">
                  <div class="PasswordTitle">确认新密码：</div>
                  <el-form-item prop="new_password1">
                    <div class="PasswordBody">
                      <el-input
                        :key="passwordType3"
                        ref="password3"
                        v-model="form.new_password1"
                        :type="passwordType3"
                        placeholder="请输入密码"
                        name="password"
                        tabindex="2"
                        autocomplete="off"
                        @blur="capsTooltip3 = false"
                      />
                      <span class="show-pwd" @click="showPwd(3)">
                        <svg-icon :icon-class="passwordType3 === 'password' ? 'eye' : 'eye-open'" />
                      </span>
                    </div>
                  </el-form-item>
                </div>
              </el-tooltip>
              <!--新密码 end------------------------------------------>
            </el-form>
            <div class="infoBtnBox">
              <!-- <el-button type="info" @click="clearInput">重置</el-button> -->
              <el-button type="primary" @click="changePassword">保存</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
//引入公用样式
import '@/styles/global.less';
//表格标题
import tableTitle from './components/tableTitle';

export default {
  components: {
    tableTitle,//表格标题
  },
  data() {
    // 配置验证规则：用于表单验证
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能低于6位！'))
      } else {
        callback()
      }
    }
    const validateEmpty = (rule,value,callback) => {
      if (!value || value.trim() === "") {
        callback(new Error('该项不能为空！'));
      } else {
        callback();
      }
    }
    return {
      tableDivTitle:"修改个人信息",
      tabPosition:"left",
      formLabelWidth:"120px",
      //修改用户信息
      infoform:{
        avatar:"",
        nickname:""
      },
      avatarUrl:"",//头像缩略图
      hovering:false,//鼠标悬浮状态
      infoFormRules:{
        avatar: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        nickname: [{ required: true, trigger: 'blur', validator: validateEmpty }]
      },
      //修改密码
      form:{
        password:"",
        new_password:"",
        new_password1:""
      },
      capsTooltip1: false,//显示大小写提示
      capsTooltip2: false,
      capsTooltip3: false,
      passwordType1: 'password',//密码域默认type 当显示密码的时候改为text
      passwordType2: 'password',//密码域默认type 当显示密码的时候改为text
      passwordType3: 'password',//密码域默认type 当显示密码的时候改为text
      loginRules: { //配置from表单验证规则
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        new_password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        new_password1: [{ required: true, trigger: 'blur', validator: validatePassword }]
      }
    }
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    //0.全局操作 start ---------------------------------------->
    //获取用户身份信息
    getUserInfo(){
      this.$store.dispatch('public/getInfo').then(res=> {
        console.log(res)
        this.avatarUrl = res.data.avatar;
        this.infoform.avatar = res.data.avatar;
        this.infoform.nickname = res.data.nickname;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //0.全局操作 end ---------------------------------------->
    //1.修改密码 start ---------------------------------------->
    //1.1 修改用户密码
    changePassword(){
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('public/changePassword',this.form).then(res=> {
            //console.log(res)
            if(res.code == 200){
              this.$message({
                type: 'success',
                message: "密码修改成功！"
              });
              this.clearInput();
            }else{
              this.$message({
                type: 'warning',
                message: res.message
              });
            } 
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }else{
          this.$message.error('请填写完整信息！');
        }
      })
    },
    // 切换密码框的显示与隐藏
    showPwd(num) {
      const passwordTypeKey = 'passwordType' + num; // 动态生成 passwordType 的键
      const passwordRefKey = 'password' + num; // 动态生成 password 的引用

      // 切换密码类型
      if (this[passwordTypeKey] === 'password') {
        this[passwordTypeKey] = ''; // 显示密码
      } else {
        this[passwordTypeKey] = 'password'; // 隐藏密码
      }

      // 使用 $nextTick 聚焦到对应的密码输入框
      this.$nextTick(() => {
        this.$refs[passwordRefKey].focus(); // 聚焦到对应的密码输入框
      });
    },
    //清空输入列表
    clearInput(){
      this.form = {
        password:"",
        new_password:"",
        new_password1:""
      }
    },
    //1.修改密码 end ---------------------------------------->
    //2.修改头像和昵称 start ---------------------------------------->
    //2.1上传图片操作
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }

      const formData = new FormData();
      formData.append('file', file);

      this.$store.dispatch('pool/uploadFile',formData).then(res=> {
        this.avatarUrl = res.data.imgUrl;//显示缩略图
        this.infoform.avatar = res.data.imgUrl;//提供表单地址
        console.log(res.data.imgUrl)
        console.log(this.infoform.avatar)
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '网络错误，请重试！'
        });
      })

      // 阻止默认的上传行为
      return false;
    },
    //2.2 删除图片
    handleDelete() {
      // 删除图片
      this.avatarUrl = ''; // 清空图片 URL
    },
    //2.3 修改用户信息
    changeInfo(){
      console.log(this.infoform)
      this.$refs.infoform.validate(valid => {
        if (valid) {
          this.$store.dispatch('user/updateUserAvatarNickname',this.infoform).then(res=> {
            if(res.code == 200){
              this.$message.success("修改成功！");
              //更新store中的头像和昵称
              this.$store.commit('user/SET_AVATAR', this.infoform.avatar);
              this.$store.commit('user/SET_NAME', this.infoform.nickname);
            }
          }).catch(() => {  
            this.$message.error('网络错误，请重试！');
          })
        }else{
          this.$message.error('请填写完整信息！');
        }
      })
    }
    //2.修改头像和昵称 end ---------------------------------------->
  }
}
</script>

<style scoped lang="less">
  @avatarBorderColor:#E1E2E9;
  @spacingPx:30px;

  .userInfoBox {
    margin: @spacingPx;
    border-radius: 20px;
    background: #fff;
    border: 1px solid #E9EDF7;
    padding: @spacingPx - 10px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding-bottom: @spacingPx;
    .userInfoTabs {
      padding: 20px 40px 20px 0;
      background: #F5F7FB
    }
    .avatar {
      border-radius: 50%;
      width: 140px;
      height: 140px;
      border: 1px solid @avatarBorderColor;
      border-radius: 12px;
      padding:15px;
    }
    .show-pwd{
      margin-left: @spacingPx;
    }
    .infoBox {
      margin-top: @spacingPx;
    }
    
    .infoInput {
      flex: 1;
    }
    .infoPassword {
      display: flex;
      align-items: center;
    }
  }

  .inputBox {
    margin-bottom: @spacingPx;
    .inputIcon {
      width: 24px;
      height: 24px;
      margin: 0 @spacingPx - 10px;
    }
    .inputIconSmall {
      width: 18px;
      height: 18px;
    }
  }
  .PasswordBox {
    display: flex;
    align-items: center;
    margin-top: @spacingPx;
    .el-form-item {
      flex: 1;
    }
    .PasswordTitle {
      width:120px;
      text-align: right;
      margin-right: 10px;
      margin-bottom:22px;
      font-size: 14px;
      color: #666;
      font-weight: bold;
    }
    .PasswordBody {
      flex: 1;
      display: flex;
      align-items: center;
    }
  }
  .infoBtnBox {
    margin-top: @spacingPx;
    padding-bottom: @spacingPx;
    text-align: center;
  }

  //执行v-deep穿透scope选择器 start------------------------------------------------------------>*/
  ::v-deep .custom-form-item > .el-form-item__label {
    line-height: 140px !important;
  }
  ::v-deep .custom-textarea .el-textarea__inner {
    resize: none; /* 禁止用户拖拽调整大小 */
  }
  ::v-deep .custom-align-right .el-form-item__label {
    text-align: right; /* 设置标签文字右对齐 */
  }
  //执行v-deep穿透scope选择器 end------------------------------------------------------------>*/
</style>