<template>
  <div>
    <h2>账户设置</h2>
    <hr>

    <div>
      <h4>设置邮箱</h4>
      <div>
        当前邮箱：
      </div>
      <div>
        <strong v-if="current_email">{{ current_email }}</strong>
        <span v-else>无</span>
      </div>
      <div>
        新邮箱： <input type="text" class="form-control w-25" v-model="new_email" />
      </div>
      <div v-if="set_email_result" class="alert alert-info my-1">
        {{ set_email_result }}
      </div>
      <button class="my-1 btn btn-primary" @click="set_email">设置</button>
    </div>

    <hr>
    <div v-if="$root.is_admin">
      <h4>设置重复验证预警</h4>
      <p>
        如果在
        <input type="number" v-model="time_window_seconds" />
        秒内，重复验证同一序列号
        <input type="number" v-model="repeat_threshold" />
        次，则触发预警。
        （发送系统消息和邮件通知）
      </p>
      <p>
        设置为0时禁用。
      </p>
      <div v-if="set_alert_rule_result" class="alert alert-info my-1">
        {{ set_alert_rule_result }}
      </div>
      <button class="my-1 btn btn-primary" @click="set_alert_rule">设置</button>
    </div>

    <hr>
    <div>
      <h4>重置密码</h4>
      <ResetPassword />
    </div>

  </div>
</template>

<script>
import ResetPassword from '../components/reset-password';

export default {
  name: 'Settings',
  props: [],
  components: {
    ResetPassword,
  },
  data: function () {
    return {
      current_email: null,
      new_email: '',
      set_email_result: null,
      time_window_seconds: 0,
      repeat_threshold: 0,
      set_alert_rule_result: null,
    };
  },
  computed: {
  },
  methods: {
    set_alert_rule: async function() {
      this.set_alert_rule_result = '正在更新...';
      await this.$root.api_post("/api/v1/qr-verify-alert/", {
        time_window_seconds: this.time_window_seconds,
        repeat_threshold: this.repeat_threshold,
      });
      this.set_alert_rule_result = "设置成功";
    },
    set_email: async function() {
      this.set_email_result = '正在更新...';
      await this.$root.api_post("/api/v1/set-email/", {
        email: this.new_email,
      });
      this.set_email_result = "设置成功";
      this.reload();
    },
    reload: async function() {
      var r = await this.$root.api_get("/api/v1/userinfo/");
      this.current_email = r.data.email;

      r = await this.$root.api_get("/api/v1/qr-verify-alert/");
      if (r.data) {
        this.time_window_seconds = r.data.time_window_seconds;
        this.repeat_threshold = r.data.repeat_threshold;
      }
    },
  },
  mounted() {
    this.reload();
  },
}
</script>

<style scoped>
h4 {
  margin-bottom: 1rem;
}
</style>

