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

      <Form ref="formInline" :model="param.seachOption" inline :label-width="80">
        <FormItem label="筛选">
          <Select v-model="param.seachOption.key" style="width: 120px" @on-change="onSearchKeyChange">
            <Option value="user_id">用户</Option>
            <Option value="status">状态</Option>
          </Select>
        </FormItem>
        <FormItem v-if="param.seachOption.key === 'user_id'">
          <Select
            v-model="param.seachOption.value"
            filterable
            clearable
            placeholder="选择用户"
            style="width: 260px"
            class="ml10"
          >
            <Option v-for="u in bizUserOptions" :key="u.id" :value="String(u.id)">{{ bizUserLabel(u) }}</Option>
          </Select>
        </FormItem>
        <FormItem v-else>
          <Input v-model="param.seachOption.value" style="width: 160px" placeholder="状态" class="ml10" />
        </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="用户">
          <Select v-model="createForm.user_id" filterable clearable placeholder="请选择" style="width: 100%">
            <Option v-for="u in bizUserOptions" :key="u.id" :value="u.id">{{ bizUserLabel(u) }}</Option>
          </Select>
        </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'
import subscriptionRelations from '@/mixins/subscriptionRelations.js'

export default {
  name: 'SubscriptionTokens',
  mixins: [subscriptionRelations],
  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),
                },
              },
              '吊销'
            ),
        },
      ]
    },
  },
  async mounted() {
    await this.loadBizRelationOptions()
    this.load(1)
  },
  methods: {
    onSearchKeyChange() {
      this.param.seachOption.value = ''
    },
    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: undefined, token_name: 'default', expire_at: fmt }
      this.createModal = true
    },
    submitCreate() {
      const uid = this.createForm.user_id
      if (uid === undefined || uid === null || uid === '') {
        this.$Message.warning('请选择用户')
        return false
      }
      this.saving = true
      this._submitCreate()
      return false
    },
    async _submitCreate() {
      const uid = this.createForm.user_id
      try {
        const res = await tokenServer.create({
          user_id: Number(uid),
          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: flex-end;
  margin-bottom: 12px;
}

.ml10 {
  margin-left: 10px;
}

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