<template>
  <el-card shadow="never">
    <template #header>
      <div class="header">
        <span>{{ title }}</span>
        <div class="right">
          <el-button type="primary" @click="openCreate">新增奖励</el-button>
        </div>
      </div>
    </template>

    <el-form :inline="true" @submit.prevent>
      <el-form-item label="关键词">
        <el-input v-model="query.keyword" clearable placeholder="请输入关键词" @keyup.enter="search" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" clearable style="width: 140px">
          <el-option label="待审批" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已驳回" value="rejected" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker
          v-model="query.range"
          type="daterange"
          value-format="YYYY-MM-DD"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 260px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="active" @tab-change="onTabChange">
      <el-tab-pane label="奖励管理" name="list" />
      <el-tab-pane label="奖金池管理" name="pool" />
      <el-tab-pane label="奖励动态" name="trends" />
    </el-tabs>

    <el-table v-loading="loading" :data="rows" border stripe>
      <el-table-column v-for="col in columns" :key="col.prop" :prop="col.prop" :label="col.label" :min-width="col.minWidth || 120" show-overflow-tooltip />
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="openDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="query.page"
        v-model:page-size="query.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="load"
        @current-change="load"
      />
    </div>
  </el-card>

  <el-dialog v-model="detailVisible" title="奖励详情" width="560px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="奖励名称">{{ detail.title || '-' }}</el-descriptions-item>
      <el-descriptions-item label="申请人">{{ detail.ownerName || '-' }}</el-descriptions-item>
      <el-descriptions-item label="金额">{{ detail.amount || '-' }}</el-descriptions-item>
      <el-descriptions-item label="状态">{{ detail.statusLabel || '-' }}</el-descriptions-item>
      <el-descriptions-item label="备注" :span="2">{{ detail.remark || '-' }}</el-descriptions-item>
    </el-descriptions>
  </el-dialog>

  <el-dialog v-model="createVisible" title="新增奖励" width="620px">
    <el-form label-width="90px">
      <el-form-item label="奖励名称">
        <el-input v-model="createForm.title" />
      </el-form-item>
      <el-form-item label="申请人">
        <el-input v-model="createForm.ownerName" />
      </el-form-item>
      <el-form-item label="金额">
        <el-input-number v-model="createForm.amount" :min="0" :step="100" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="createForm.remark" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="createVisible = false">取消</el-button>
      <el-button type="primary" :loading="creating" @click="submitCreate">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { awardAdd, awardGet, awardList, awardPoolList, awardTrendsList } from '@/api/otr/award/core'

type Scene = 'list' | 'pool' | 'trends'
const props = defineProps<{ title: string; scene: Scene }>()
const router = useRouter()
const route = useRoute()

const active = ref<Scene>(props.scene)
const loading = ref(false)
const rows = ref<any[]>([])
const total = ref(0)
const detailVisible = ref(false)
const detail = reactive<Record<string, any>>({})
const createVisible = ref(false)
const creating = ref(false)
const createForm = reactive({
  title: '',
  ownerName: '',
  amount: 0,
  remark: '',
})

const query = reactive({
  page: 1,
  pageSize: 10,
  keyword: '',
  status: '',
  range: [] as string[],
})

const columns = computed(() => {
  if (active.value === 'pool') {
    return [
      { prop: 'poolName', label: '奖金池', minWidth: 220 },
      { prop: 'amount', label: '余额' },
      { prop: 'updatedAt', label: '更新时间', minWidth: 160 },
    ]
  }
  if (active.value === 'trends') {
    return [
      { prop: 'title', label: '动态标题', minWidth: 240 },
      { prop: 'operator', label: '操作人' },
      { prop: 'createdAt', label: '时间', minWidth: 160 },
    ]
  }
  return [
    { prop: 'title', label: '奖励名称', minWidth: 220 },
    { prop: 'ownerName', label: '申请人' },
    { prop: 'amount', label: '奖励金额' },
    { prop: 'statusLabel', label: '状态' },
  ]
})

function buildParams() {
  return {
    page: query.page,
    pageSize: query.pageSize,
    keyword: query.keyword,
    status: query.status,
    start: query.range?.[0] || '',
    end: query.range?.[1] || '',
  }
}

async function load() {
  loading.value = true
  try {
    const params = buildParams()
    let res: any
    if (active.value === 'pool') res = await awardPoolList(params)
    else if (active.value === 'trends') res = await awardTrendsList(params)
    else res = await awardList(params)
    const rt = res?.result ?? {}
    rows.value = rt.records ?? rt.list ?? []
    total.value = Number(rt.total ?? rows.value.length)
  } finally {
    loading.value = false
  }
}

function search() {
  query.page = 1
  load()
}

function reset() {
  query.page = 1
  query.pageSize = 10
  query.keyword = ''
  query.status = ''
  query.range = []
  load()
}

function onTabChange(name: string | number) {
  const tab = String(name) as Scene
  const map: Record<Scene, string> = {
    list: '/otr/award/list',
    pool: '/otr/award/pool',
    trends: '/otr/award/trends',
  }
  router.push(map[tab])
}

async function openDetail(row: any) {
  const id = row?.id ?? 1
  const res: any = await awardGet(id)
  Object.assign(detail, res?.result || row || {})
  detailVisible.value = true
}

function openCreate() {
  createVisible.value = true
}

async function submitCreate() {
  if (!createForm.title) {
    ElMessage.warning('请填写奖励名称')
    return
  }
  creating.value = true
  try {
    await awardAdd({ ...createForm })
    ElMessage.success('新增成功')
    createVisible.value = false
    createForm.title = ''
    createForm.ownerName = ''
    createForm.amount = 0
    createForm.remark = ''
    load()
  } finally {
    creating.value = false
  }
}

onMounted(() => {
  if (route.path.includes('/otr/award/pool')) active.value = 'pool'
  if (route.path.includes('/otr/award/trends')) active.value = 'trends'
  load()
})
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>
