<template>
  <div class="content-view">
    <div class="table-head-tool">
      <div class="table-title-row">
        <Button type="primary" @click="openEdit(null)">新增</Button>
      </div>

      <Form ref="formInline" :model="param.seachOption" inline :label-width="80" class="usage-query-form">
        <FormItem label="条件">
          <Select v-model="param.seachOption.key" class="usage-select" @on-change="onSearchKeyChange">
            <Option value="user_id">用户</Option>
            <Option value="stat_month">月份</Option>
            <Option value="plan_id">套餐</Option>
          </Select>
          <Select
            v-if="param.seachOption.key === 'user_id'"
            v-model="param.seachOption.value"
            filterable
            clearable
            placeholder="选择用户"
            class="ml10 usage-search-input"
          >
            <Option v-for="u in bizUserOptions" :key="u.id" :value="String(u.id)">{{ bizUserLabel(u) }}</Option>
          </Select>
          <Select
            v-else-if="param.seachOption.key === 'plan_id'"
            v-model="param.seachOption.value"
            filterable
            clearable
            placeholder="选择套餐"
            class="ml10 usage-search-input"
          >
            <Option v-for="p in bizPlanOptions" :key="p.id" :value="String(p.id)">{{ bizPlanLabel(p) }}</Option>
          </Select>
          <Input
            v-else
            v-model="param.seachOption.value"
            class="ml10 usage-search-input"
            placeholder="YYYY-MM"
          />
        </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-scroll">
      <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="modal" :title="form.id ? '编辑用量' : '新增用量'" width="640" :loading="saving" @on-ok="save">
      <Form ref="formRef" :model="form" :rules="rules" :label-width="120">
        <FormItem label="用户" prop="user_id">
          <Select v-model="form.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="套餐" prop="plan_id">
          <Select v-model="form.plan_id" filterable clearable placeholder="请选择" style="width: 100%">
            <Option v-for="p in bizPlanOptions" :key="p.id" :value="p.id">{{ bizPlanLabel(p) }}</Option>
          </Select>
        </FormItem>
        <FormItem label="月份 YYYY-MM" prop="stat_month"><Input v-model="form.stat_month" placeholder="2025-03" /></FormItem>
        <FormItem label="msg_count"><Input v-model="form.msg_count" type="number" /></FormItem>
        <FormItem label="mass_count"><Input v-model="form.mass_count" type="number" /></FormItem>
        <FormItem label="friend_count"><Input v-model="form.friend_count" type="number" /></FormItem>
        <FormItem label="sns_count"><Input v-model="form.sns_count" type="number" /></FormItem>
        <FormItem label="active_user_count"><Input v-model="form.active_user_count" type="number" /></FormItem>
        <FormItem label="api_call_count（转发调用）"><Input v-model="form.api_call_count" type="number" /></FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import usageServer from '@/api/subscription/usage_server.js'
import { downloadCsvFromRows } from '@/utils/csvExport.js'
import subscriptionRelations from '@/mixins/subscriptionRelations.js'

export default {
  name: 'SubscriptionUsage',
  mixins: [subscriptionRelations],
  data() {
    return {
      rows: [],
      total: 0,
      param: {
        seachOption: { key: 'stat_month', value: '' },
        pageOption: { page: 1, pageSize: 20, total: 0 },
      },
      modal: false,
      saving: false,
      form: {},
      rules: {
        user_id: [{ required: true, type: 'number', message: '请选择用户', trigger: 'change' }],
        plan_id: [{ required: true, type: 'number', message: '请选择套餐', trigger: 'change' }],
        stat_month: [{ required: true, message: '必填', trigger: 'blur' }],
      },
    }
  },
  computed: {
    columns() {
      return [
        { title: 'ID', key: 'id', minWidth: 64 },
        { title: '用户', key: 'user_id', minWidth: 80 },
        { title: '套餐', key: 'plan_id', minWidth: 80 },
        { title: '月份', key: 'stat_month', minWidth: 96 },
        { title: 'msg', key: 'msg_count', minWidth: 72 },
        { title: 'mass', key: 'mass_count', minWidth: 72 },
        { title: 'friend', key: 'friend_count', minWidth: 72 },
        { title: 'sns', key: 'sns_count', minWidth: 72 },
        { title: 'active_user', key: 'active_user_count', minWidth: 100 },
        { title: 'api_calls', key: 'api_call_count', minWidth: 88 },
        {
          title: '操作',
          key: 'a',
          minWidth: 132,
          render: (h, p) =>
            h('div', [
              h('Button', { props: { type: 'info', size: 'small' }, on: { click: () => this.openEdit(p.row) } }, '编辑'),
              h('Button', { props: { type: 'error', size: 'small' }, class: { ml8: true }, on: { click: () => this.doDel(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 usageServer.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)
    },
    openEdit(row) {
      if (row) {
        this.form = {
          ...row,
          user_id: row.user_id != null && row.user_id !== '' ? Number(row.user_id) : undefined,
          plan_id: row.plan_id != null && row.plan_id !== '' ? Number(row.plan_id) : undefined,
        }
      } else {
        this.form = {
          user_id: undefined,
          plan_id: undefined,
          stat_month: '',
          msg_count: 0,
          mass_count: 0,
          friend_count: 0,
          sns_count: 0,
          active_user_count: 0,
          api_call_count: 0,
        }
      }
      this.modal = true
    },
    save() {
      this.saving = true
      this.$refs.formRef.validate(async (ok) => {
        if (!ok) {
          this.saving = false
          return
        }
        const payload = { ...this.form }
        payload.user_id = Number(payload.user_id)
        payload.plan_id = Number(payload.plan_id)
        try {
          const res = this.form.id ? await usageServer.edit(payload) : await usageServer.add(payload)
          if (res && res.code === 0) {
            this.$Message.success('保存成功')
            this.modal = false
            this.load(1)
          } else {
            this.$Message.error((res && res.message) || '失败')
          }
        } finally {
          this.saving = false
        }
      })
    },
    doDel(row) {
      this.$Modal.confirm({
        title: '删除',
        content: '确认删除该用量记录？',
        onOk: async () => {
          const res = await usageServer.del({ 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 usageServer.exportRows({ param: this.param })
      if (res && res.code === 0 && res.data && res.data.rows) {
        downloadCsvFromRows(res.data.rows, 'usage_monthly.csv')
        this.$Message.success('已导出')
      } else {
        this.$Message.error((res && res.message) || '导出失败')
      }
    },
    resetQuery() {
      this.param.seachOption = { key: 'stat_month', 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;
}

.usage-query-form {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 8px 0;
}

.usage-select {
  width: 140px;
  max-width: 100%;
}

.usage-search-input {
  width: 200px;
  max-width: 100%;
}

.table-scroll {
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;

  :deep(.ivu-table) {
    min-width: 720px;
  }
}

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

.table-title-row {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 14px;
}

.ml10 {
  margin-left: 10px;
}

.ml8 {
  margin-left: 8px;
}

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