<script setup lang="ts">
import { useNowUser } from '@/stores/now-user.js'
import UserPasswordModal from '@/components/admin/UserPasswordModal.vue'
import { h, ref } from 'vue'
import { api } from '@/tools/web.ts'
import { type DataTableColumn, NTag, NText } from 'naive-ui'
import InDev from '@/components/InDev.vue'
import { useHead } from '@unhead/vue'

useHead({
  title: '用户安全',
})

const NOWUSER = useNowUser()

const showPasswordModal = ref(false)

interface SecureChange {
  created_at: number
  type: 'login' | 'change_password' | 'change_email' | 'change_phone'
  old: string | null
  new: string | null
}

const secureChanges = ref<SecureChange[]>([])

const columns = [
  {
    title: '记录时间',
    key: 'created_at',
    render(row) {
      const date = new Date(row.created_at * 1000)
      return h(NText, {}, { default: () => date.toLocaleString() })
    },
  },
  {
    title: '类型',
    key: 'type',
    render: (row) => {
      return h(
        NTag,
        {
          type: 'info',
        },
        { default: () => row.type },
      )
    },
  },
  {
    title: '事件之前',
    key: 'old',
  },
  {
    title: '事件之后',
    key: 'new',
  },
] as DataTableColumn<SecureChange>[]

function loadSecureChanges() {
  api
    .get('/admin/me/secure_changes/')
    .then((res) => (secureChanges.value = res.data as SecureChange[]))
}
</script>

<template>
  <n-card>
    <template #header>
      <n-h3 prefix="bar" style="margin: 0">密码</n-h3>
    </template>

    <n-flex vertical>
      <n-alert type="warning" v-if="NOWUSER.id === 1">
        您正在使用 NyaHome 初始化时创建的管理员账号，此账号的默认密码为 admin。
        <strong>您应该及时修改默认密码。</strong><br />
        如果您已修改密码，请忽略。
      </n-alert>
      <n-flex>
        <n-button type="error" @click="showPasswordModal = true">修改密码</n-button>
        <n-button type="warning">忘记密码</n-button>
      </n-flex>
    </n-flex>

    <user-password-modal v-model:show-modal="showPasswordModal" />
  </n-card>

  <n-card>
    <template #header>
      <n-h3 prefix="bar" style="margin: 0">其他登录方式</n-h3>
    </template>

    <n-flex vertical>
      <n-alert type="info">
        在这里连接第三方账户之后，可以使用它们进行登录。<br />
        <strong>必须先在这里连接后才能使用第三方账户进行登录。</strong>
      </n-alert>

      <in-dev />
    </n-flex>
  </n-card>

  <n-card>
    <template #header>
      <n-h3 prefix="bar" style="margin: 0">两步验证</n-h3>
    </template>

    <n-flex vertical>
      <n-alert type="info">
        启用两步验证可以更好地保护您的账户，这会强制此账号在登录时进行额外验证。
      </n-alert>

      <in-dev />
    </n-flex>
  </n-card>

  <n-card>
    <template #header>
      <n-h3 prefix="bar" style="margin: 0">安全事件记录</n-h3>
    </template>
    <n-flex vertical>
      <n-data-table :columns :data="secureChanges" />
      <n-button secondary type="warning" @click="loadSecureChanges()">查询（更新）</n-button>
    </n-flex>
  </n-card>
</template>

<style scoped></style>
