<template>
  <div class="personal-info">
    <div class="name">个人信息</div>
    <el-form
      :model="userInfoForm"
      :rules="userInfoRules"
      label-width="100px"
      class="userInfoForm"
      ref="userInfoForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          size="small"
          v-if="isEditing"
          v-model="userInfoForm.username"
        ></el-input>
        <div class="value" v-else>
          {{ userInfoForm.username || "暂未填写" }}
        </div>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
          size="small"
          v-if="isEditing"
          v-model="userInfoForm.nickName"
        ></el-input>
        <div class="value" v-else>
          {{ userInfoForm.nickName || "暂未填写" }}
        </div>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          size="small"
          v-if="isEditing"
          v-model="userInfoForm.phone"
        ></el-input>
        <div class="value" v-else>
          {{ userInfoForm.phone || "暂未填写" }}
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          class="edit-button"
          v-if="!isEditing"
          @click.native="handleEdit('userInfo')"
        >
          修改个人信息
        </el-button>
        <el-button
          class="edit-button"
          v-if="!isEditing"
          @click.native="handleEdit('pwd')"
        >
          修改密码
        </el-button>
        <el-button
          class="edit-button"
          v-if="isEditing"
          @click.native="handleCancelUserInfo"
        >
          取消修改
        </el-button>
        <el-button
          class="edit-button"
          v-if="isEditing"
          @click.native="handleSubmit"
        >
          保存
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="修改密码"
      :visible="dialogFormVisible"
      width="400px"
      append-to-body
      @close="handleCloseChangePwd"
    >
      <el-form
        :model="pwdForm"
        label-position="right"
        label-width="80px"
        :rules="pwdRules"
        ref="pwdForm"
      >
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="pwdForm.oldPwd" type="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="pwdForm.newPwd" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input v-model="pwdForm.checkPass" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelPwd">取 消</el-button>
        <el-button type="primary" @click="handleChangePwd">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { editUserInfo, editUserPwd } from "@/api/user";
import { setUserInfo } from "@/utils/auth";
export default {
  name: "Info",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        var pattern =
          /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/;
        if (!pattern.test(value)) {
          callback(
            new Error(
              "密码长度至少8位，至少含数字,大写字母,小写字母,特殊符其中三种"
            )
          );
        }
        if (this.pwdForm.checkPass !== "") {
          this.$refs.pwdForm.validateField("checkPass");
        }
        callback();
      }
    };

    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.pwdForm.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      dialogFormVisible: false,
      isEditBasicInfo: true,
      isEditing: false,
      userInfoForm: {},
      pwdForm: {
        oldPwd: "",
        newPwd: "",
        repeatPwd: "",
      },
      pwdRules: {
        oldPwd: [
          { trigger: "blur", required: true, message: "请输入当前密码" },
        ],
        newPwd: [{ validator: validatePass, trigger: "blur", required: true }],
        checkPass: [
          { validator: validatePass2, trigger: "blur", required: true },
        ],
      },
      userInfoRules: {
        username: [
          {
            required: true,
            message: "请填写用户名",
            trigger: "blur",
          },
        ],
        nickName: [
          {
            required: true,
            message: "请填写昵称",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请填写手机号",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },

  mounted() {
    this.userInfoForm = JSON.parse(JSON.stringify(this.userInfo));
  },
  methods: {
    handleEdit(type) {
      switch (type) {
        case "userInfo":
          this.isEditing = true;
          break;
        case "pwd":
          if (this.isEditing) {
            this.isEditing = false;
          }
          this.dialogFormVisible = true;
          break;
      }
    },

    handleSubmit(type) {
      this.$refs.userInfoForm.validate(async (valid) => {
        if (valid) {
          let res = await editUserInfo(this.userInfoForm);
          if (res.code == "0") {
            this.$message.success("修改成功！");
            this.$store.commit("user/SET_USERINFO", this.userInfoForm);
            setUserInfo(this.userInfoForm);
          }
          this.isEditing = false;
        }
      });
    },

    handleCancelUserInfo() {
      this.isEditing = false;
      this.userInfoForm = this.userInfo;
      this.$refs.userInfoForm.resetFields();
    },

    async handleChangePwd() {
      this.$refs.pwdForm.validate(async (valid) => {
        if (valid) {
          const { newPwd, oldPwd } = this.pwdForm;
          const params = {
            newPwd,
            oldPwd,
          };
          let res = await editUserPwd(params);
          if (res.code == "0") {
            let path = this.$route.fullPath;
            if (path.indexOf("/personal") != -1) {
              this.$router.push("/");
            }
            this.$message.success("修改成功，请重新登录！");
            setTimeout(async () => {
              await this.$store.dispatch("user/logout");
              this.$store.commit("app/OPEN_LOGIN_DIALOG", true);
            }, 2000);
          }
        }
      });
    },

    handleCloseChangePwd() {
      this.dialogFormVisible = false;
    },

    handleCancelPwd() {
      this.dialogFormVisible = false;
      this.$refs.pwdForm.resetFields();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-tabs__header.is-left {
  margin-right: 50px;
}
::v-deep .el-descriptions__extra {
  .el-button {
    background-color: #2069c4;
    border-radius: 0;
    border: none;
  }
}

::v-deep .el-dialog__body {
  padding: 30px 40px 10px 20px;
}
.userInfoForm {
  width: 400px;
}
.personal-info {
  margin-left: 40px;
  .name {
    margin-bottom: 40px;
    font-weight: bold;
  }
  .info-item {
    display: flex;
    margin-bottom: 30px;
    border-bottom: 1px solid #f3f5f6;
    padding-bottom: 30px;
    .label {
      width: 100px;
      color: #666;
    }
    .value {
      color: #333;
    }
  }
  .buttons {
    display: flex;
    .edit-button {
      width: 160px;
      height: 50px;
      background-color: #2069c4;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      margin-right: 10px;
      cursor: pointer;
      &:hover {
        filter: brightness(0.9);
      }
    }
  }
}
</style>