<template>
  <el-dialog
    :title="$t('ftlOne.changePassword')"
    :visible.sync="dialogVisible"
    width="40%"
    append-to-body
    :close-on-click-modal="false"
    :show-close="!passwordExpirationFlag"
    :close-on-press-escape="!passwordExpirationFlag"
    @close="cancel"
  >
    <div class="ftlOne-changePasswordDialog">
      <div style="margin-left: 60px; margin-bottom: 20px">
        <h3>
          {{ username }},
          {{ passwordExpirationFlag ? $t("ftlOne.changePassword.holder1") : $t("ftlOne.changePassword.holder2") }}
        </h3>
      </div>
      <el-form ref="passwordForm" :model="passwordForm" label-width="145px">
        <el-form-item
          :label="$t('ftlOne.changePassword.oldPassword')"
          prop="oldPassword"
          :rules="[
            {
              required: true,
              message: $t('ftlOne.changePassword.oldPassword.placeholder'),
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="passwordForm.oldPassword"
            show-password
            :placeholder="$t('ftlOne.changePassword.oldPassword.placeholder')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('ftlOne.changePassword.newPassword')"
          prop="newPassword"
          :rules="[
            {
              required: true,
              message: $t('ftlOne.changePassword.newPassword.placeholder'),
              trigger: 'blur',
            },
            {
              pattern: /^(?=.*?[a-z])(?=.*?[A-Z])(?!\D+$)/,
              message: $t('ftlOne.changePassword.newPassword.error1'),
              trigger: 'blur',
            },
            {
              min: 8,
              max: 16,
              message: $t('ftlOne.changePassword.newPassword.error2'),
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="passwordForm.newPassword"
            show-password
            :placeholder="$t('ftlOne.changePassword.newPassword.placeholder')"
          />
        </el-form-item>

        <el-form-item prop="confirmPassword" :rules="[{ validator: validateConfirmPass, trigger: 'blur' }]">
          <div slot="label" class="require_label">{{ $t("ftlOne.changePassword.confirmPassword") }}</div>
          <el-input
            v-model="passwordForm.confirmPassword"
            show-password
            :placeholder="$t('ftlOne.changePassword.confirmPassword.placeholder')"
          />
        </el-form-item>

        <div class="mt15 tr">
          <el-button @click="cancel" v-if="!passwordExpirationFlag">{{ $t("ftlOne.changePassword.cancel") }}</el-button>
          <el-button type="primary" @click="saveChangePassword">{{ $t("ftlOne.changePassword.save") }}</el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>
<script>
import { mapState } from "vuex";
import axios from "axios";
export default {
  name: "FtlPasswordDialog",
  props: {
    authBaseUrl: {
      type: String,
      default: "https://gateway-staging.ftlapp.io",
    },
  },
  data() {
    var validateConfirmPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("ftlOne.changePassword.confirmPassword.placeholder")));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error(this.$t("ftlOne.changePassword.confirmPassword.error1")));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      passwordForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      validateConfirmPass,
      passwordExpirationFlag: false,
    };
  },
  computed: {
    ...mapState({
      username: (state) => state.auth.username,
    }),
  },
  mounted() {
    this.$bus?.$on("getFlag", this.getPasswordExpirationFlag);
    this.$bus?.$on("setFlag", this.setFlag);
  },
  beforeDestroy() {
    this.$bus?.$off("toGetFlag");
    this.$bus?.$off("setFlag");
  },
  methods: {
    // 设置为强制更改密码
    setFlag() {
      this.passwordExpirationFlag = true;
      this.dialogVisible = true;
    },
    // 获取自己账号信息
    async getPasswordExpirationFlag() {
      const token = localStorage.getItem("token") || "";
      let res = await axios({
        url: `${this.authBaseUrl}/api/accounts/me`,
        method: "get",
        headers: {
          Authorization: token,
        },
      });
      this.passwordExpirationFlag = res.data.passwordExpirationFlag;
      if (this.passwordExpirationFlag) {
        this.dialogVisible = true;
      }
    },
    // 修改密码
    saveChangePassword() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (valid) {
          const loadingInstance = this.$loading({
            target: document.querySelector(".ftlOne-changePasswordDialog"),
          });
          const token = localStorage.getItem("token") || "";
          try {
            await axios({
              url: `${this.authBaseUrl}/api/accounts/me/changePassword`,
              method: "post",
              headers: {
                Authorization: token,
              },
              data: this.passwordForm,
            });
            this.$message.success("success");
            loadingInstance.close();
            this.dialogVisible = false;
            this.passwordForm.oldPassword = "";
            this.passwordForm.newPassword = "";
            this.passwordForm.confirmPassword = "";
            this.passwordExpirationFlag = false;
            this.$nextTick(() => {
              this.$refs.passwordForm.clearValidate();
              this.$bus && this.$bus.$emit("changeWordSuccess");
            });
          } catch (error) {
            loadingInstance.close();
            this.$message.error(error?.response?.data?.i18n || error?.response?.data?.message);
          }
        }
      });
    },
    cancel() {
      this.dialogVisible = false;
      this.passwordForm.oldPassword = "";
      this.passwordForm.newPassword = "";
      this.passwordForm.confirmPassword = "";
      this.passwordExpirationFlag = false;
      this.$nextTick(() => {
        this.$refs.passwordForm.clearValidate();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.require_label {
  &::before {
    content: "*";
    color: #f36c6c;
    margin-right: 4px;
  }
}
</style>
