<template>
  <div class="content-view">
    <div class="table-head-tool">
      <div class="table-title-row">
        <h2 class="table-title">API Token</h2>
        <Button type="primary" @click="openCreate">创建 Token</Button>
      </div>

      <Form ref="formInline" :model="param.seachOption" inline :label-width="80">
        <FormItem label="用户ID">
          <Input v-model="param.seachOption.value" style="width: 140px" class="ml10" />
        </FormItem>
        <FormItem>
          <Select v-model="param.seachOption.key" style="width: 120px">
            <Option value="user_id">用户ID</Option>
            <Option value="status">状态</Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="load(1)">查询</Button>
          <Button type="default" @click="resetQuery" class="ml10">重置</Button>
          <Button type="default" @click="doExport" class="ml10">导出 CSV</Button>
        </FormItem>
      </Form>
    </div>

    <div class="table-body">
      <Table :columns="columns" :data="rows" border stripe />
      <div class="table-page-bar">
        <Page
          :total="total"
          :current="param.pageOption.page"
          :page-size="param.pageOption.pageSize"
          show-total
          @on-change="onPage"
          @on-page-size-change="onSize"
        />
      </div>
    </div>

    <Modal v-model="createModal" title="创建 Token" width="560" :loading="saving" @on-ok="submitCreate">
      <Form :label-width="100">
        <FormItem label="用户ID"><Input v-model="createForm.user_id" type="number" /></FormItem>
        <FormItem label="名称"><Input v-model="createForm.token_name" placeholder="default" /></FormItem>
        <FormItem label="过期时间"><Input v-model="createForm.expire_at" placeholder="2026-12-31 23:59:59" /></FormItem>
      </Form>
    </Modal>

    <Modal v-model="plainModal" title="请立即保存 Token 明文" width="560" :closable="false">
      <Alert type="error">仅此一次展示，关闭后无法再次查看明文。</Alert>
      <Input type="textarea" :rows="4" v-model="plainToken" readonly />
      <div slot="footer">
        <Button type="primary" @click="plainModal = false">已保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import tokenServer from '@/api/subscription/token_server.js'
import { downloadCsvFromRows } from '@/utils/csvExport.js'

export default {
  name: 'SubscriptionTokens',
  data() {
    return {
      rows: [],
      total: 0,
      param: {
        seachOption: { key: 'user_id', value: '' },
        pageOption: { page: 1, pageSize: 20, total: 0 },
      },
      createModal: false,
      plainModal: false,
      plainToken: '',
      saving: false,
      createForm: {},
    }
  },
  computed: {
    columns() {
      return [
        { title: 'ID', key: 'id', width: 70 },
        { title: '用户', key: 'user_id', width: 90 },
        { title: '套餐', key: 'plan_id', width: 90 },
        { title: '名称', key: 'token_name', width: 120 },
        { title: '状态', key: 'status', width: 90 },
        { title: '过期', key: 'expire_at', minWidth: 150 },
        { title: '最后使用', key: 'last_used_at', minWidth: 150 },
        {
          title: '操作',
          key: 'a',
          width: 100,
          render: (h, p) =>
            h(
              'Button',
              {
                props: { type: 'error', size: 'small' },
                on: {
                  click: () => this.doRevoke(p.row),
                },
              },
              '吊销'
            ),
        },
      ]
    },
  },
  mounted() {
    this.load(1)
  },
  methods: {
    async load(page) {
      if (page) this.param.pageOption.page = page
      const res = await tokenServer.page({ param: this.param })
      if (res && res.code === 0) {
        this.rows = res.data.rows || []
        this.total = res.data.count || 0
      } else {
        this.$Message.error((res && res.message) || '加载失败')
      }
    },
    onPage(p) {
      this.param.pageOption.page = p
      this.load()
    },
    onSize(s) {
      this.param.pageOption.pageSize = s
      this.load(1)
    },
    openCreate() {
      const d = new Date()
      d.setFullYear(d.getFullYear() + 1)
      const fmt = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(
        2,
        '0'
      )} 23:59:59`
      this.createForm = { user_id: '', token_name: 'default', expire_at: fmt }
      this.createModal = true
    },
    async submitCreate() {
      this.saving = true
      try {
        const res = await tokenServer.create({
          user_id: Number(this.createForm.user_id),
          token_name: this.createForm.token_name || 'default',
          expire_at: this.createForm.expire_at,
        })
        if (res && res.code === 0) {
          if (res.data.warn) this.$Message.warning(res.data.warn)
          this.createModal = false
          this.plainToken = res.data.plain_token
          this.plainModal = true
          this.load(1)
        } else {
          this.$Message.error((res && res.message) || '创建失败')
        }
      } finally {
        this.saving = false
      }
    },
    doRevoke(row) {
      this.$Modal.confirm({
        title: '吊销 Token',
        content: '确认吊销？',
        onOk: async () => {
          const res = await tokenServer.revoke({ id: row.id })
          if (res && res.code === 0) {
            this.$Message.success('已吊销')
            this.load(1)
          } else {
            this.$Message.error((res && res.message) || '失败')
          }
        },
      })
    },
    async doExport() {
      const res = await tokenServer.exportRows({ param: this.param })
      if (res && res.code === 0 && res.data && res.data.rows) {
        downloadCsvFromRows(res.data.rows, 'api_tokens.csv')
        this.$Message.success('已导出')
      } else {
        this.$Message.error((res && res.message) || '导出失败')
      }
    },
    resetQuery() {
      this.param.seachOption = { key: 'user_id', value: '' }
      this.load(1)
    },
  },
}
</script>

<style lang="less" scoped>
.content-view {
  width: 100%;
  max-width: 1720px;
  margin: 0 auto;
  padding: 26px 36px 36px;
  box-sizing: border-box;
}

.table-head-tool {
  margin-bottom: 16px;
}

.table-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.table-title {
  margin: 0;
  font-size: 18px;
}

.ml10 {
  margin-left: 10px;
}

.table-page-bar {
  margin-top: 12px;
  text-align: right;
}
</style>
