<template>
  <el-card shadow="never">
    <template #header>
      <div class="header">
        <span>{{ title }}</span>
        <div class="right">
          <el-button type="primary" @click="goTemplateForm">新建考核模板</el-button>
          <el-button @click="goContentForm">新建考核内容</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="processing" />
          <el-option label="已完成" value="done" />
          <el-option label="待审核" value="review" />
        </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="manage" />
      <el-tab-pane label="我的绩效" name="mine" />
      <el-tab-pane label="绩效看板" name="board" />
      <el-tab-pane label="绩效待办" name="backlog" />
      <el-tab-pane label="绩效模板" name="template" />
    </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="goDetail(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>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { effectBacklogList, effectBoardList, effectManageList, effectMineList, effectTemplateList } from '@/api/otr/effect/core'

type Scene = 'manage' | 'mine' | 'board' | 'backlog' | 'template'
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 query = reactive({
  page: 1,
  pageSize: 10,
  keyword: '',
  status: '',
  range: [] as string[],
})

const columns = computed(() => {
  if (active.value === 'mine') {
    return [
      { prop: 'title', label: '考核名称', minWidth: 220 },
      { prop: 'score', label: '当前得分' },
      { prop: 'rank', label: '排名' },
      { prop: 'statusLabel', label: '状态' },
    ]
  }
  if (active.value === 'board') {
    return [
      { prop: 'ownerName', label: '负责人' },
      { prop: 'deptName', label: '部门' },
      { prop: 'targetCount', label: '考核数' },
      { prop: 'avgScore', label: '平均得分' },
    ]
  }
  if (active.value === 'backlog') {
    return [
      { prop: 'title', label: '待办标题', minWidth: 220 },
      { prop: 'ownerName', label: '负责人' },
      { prop: 'deadline', label: '截止时间', minWidth: 160 },
      { prop: 'statusLabel', label: '状态' },
    ]
  }
  if (active.value === 'template') {
    return [
      { prop: 'name', label: '模板名称', minWidth: 220 },
      { prop: 'scene', label: '适用场景' },
      { prop: 'updatedBy', label: '更新人' },
      { prop: 'updatedAt', label: '更新时间', minWidth: 160 },
    ]
  }
  return [
    { prop: 'title', label: '考核名称', minWidth: 220 },
    { prop: 'ownerName', label: '负责人' },
    { prop: 'cycleName', 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 === 'mine') res = await effectMineList(params)
    else if (active.value === 'board') res = await effectBoardList(params)
    else if (active.value === 'backlog') res = await effectBacklogList(params)
    else if (active.value === 'template') res = await effectTemplateList(params)
    else res = await effectManageList(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> = {
    manage: '/otr/effect/manage',
    mine: '/otr/effect/mine',
    board: '/otr/effect/board',
    backlog: '/otr/effect/backlog',
    template: '/otr/effect/template',
  }
  router.push(map[tab])
}

function goDetail(row: any) {
  router.push({ path: '/otr/effect/detail', query: { id: String(row.id || '') } })
}

function goTemplateForm() {
  router.push('/otr/effect/template-form')
}

function goContentForm() {
  router.push('/otr/effect/content-form')
}

onMounted(() => {
  if (route.path.includes('/otr/effect/mine')) active.value = 'mine'
  if (route.path.includes('/otr/effect/board')) active.value = 'board'
  if (route.path.includes('/otr/effect/backlog')) active.value = 'backlog'
  if (route.path.includes('/otr/effect/template')) active.value = 'template'
  load()
})
</script>

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