<script setup>
import { h, ref, watch, onMounted } from 'vue'
import { NButton, NInput, NTabs, NTabPane, NPopconfirm, NForm, NFormItem, NGrid, NGridItem, NCard, NStatistic } from 'naive-ui'
import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { renderIcon, formatDate } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api/keyword'
import TheIcon from '@/components/icon/TheIcon.vue'

defineOptions({ name: '关键词管理' })

const activeTab = ref('boss')
const $table = ref(null)
const queryItems = ref({})
const overviewStats = ref({
  boss: { total: 0, used: 0, unused: 0 },
  qcwy: { total: 0, used: 0, unused: 0 },
  zhilian: { total: 0, used: 0, unused: 0 },
})

const fetchStats = async () => {
  try {
    const res = await api.getOverview()
    if (res.code === 200) {
      overviewStats.value = res.data
    }
  } catch (error) {
    console.error('Failed to fetch stats:', error)
  }
}

onMounted(() => {
  fetchStats()
})

// Wrapper for API calls to include source
const getList = (params) => {
  return api.getList({ ...params, source: activeTab.value })
}

const doCreate = (data) => {
  return api.create(data, { source: activeTab.value }).then(res => {
      fetchStats()
      return res
  })
}

const doUpdate = (data) => {
    const { id, ...rest } = data
    return api.update({ id, source: activeTab.value }, rest)
}

const doDelete = (data) => {
    return api.delete({ id: data.id, source: activeTab.value }).then(res => {
        fetchStats()
        return res
    })
}

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '关键词',
  initForm: { city: '', job: '' },
  doCreate: doCreate,
  doUpdate: doUpdate,
  doDelete: doDelete,
  refresh: () => $table.value?.handleSearch(),
})

watch(activeTab, () => {
  $table.value?.handleSearch()
})

const columns = [
  { title: 'ID', key: 'id', width: 60, align: 'center' },
  { title: '城市', key: 'city', width: 100, align: 'center' },
  { title: '职位关键词', key: 'job', width: 150, align: 'center' },
  { 
      title: '最后请求日期', 
      key: 'last_requested_date', 
      width: 120, 
      align: 'center',
      render(row) {
          return row.last_requested_date || '-'
      }
  },
  { 
      title: '最后请求时间', 
      key: 'last_requested_at', 
      width: 150, 
      align: 'center',
      render(row) {
          return row.last_requested_at ? formatDate(row.last_requested_at) : '-'
      }
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-right: 8px;',
            onClick: () => handleEdit(row),
          },
          { default: () => '编辑', icon: renderIcon('material-symbols:edit', { size: 16 }) }
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete(row, false),
          },
          {
            trigger: () =>
              h(
                NButton,
                { size: 'small', type: 'error' },
                { default: () => '删除', icon: renderIcon('material-symbols:delete-outline', { size: 16 }) }
              ),
            default: () => '确定删除该关键词吗?',
          }
        ),
      ]
    },
  },
]
</script>

<template>
  <CommonPage show-footer title="关键词管理">
    <div class="flex flex-col gap-4">
      <n-grid :x-gap="12" :y-gap="12" :cols="3">
        <n-grid-item>
          <n-card>
            <n-statistic label="Boss直聘">
              <template #prefix>
                <div class="text-sm font-semibold text-gray-700">已用 / 总数</div>
              </template>
              {{ overviewStats.boss.used }} / {{ overviewStats.boss.total }}
              <template #suffix>
                <span class="text-xs text-green-600" v-if="overviewStats.boss.total > 0">
                  {{ ((overviewStats.boss.used / overviewStats.boss.total) * 100).toFixed(1) }}%
                </span>
              </template>
            </n-statistic>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card>
            <n-statistic label="前程无忧">
              <template #prefix>
                <div class="text-sm font-semibold text-gray-700">已用 / 总数</div>
              </template>
              {{ overviewStats.qcwy.used }} / {{ overviewStats.qcwy.total }}
              <template #suffix>
                <span class="text-xs text-green-600" v-if="overviewStats.qcwy.total > 0">
                  {{ ((overviewStats.qcwy.used / overviewStats.qcwy.total) * 100).toFixed(1) }}%
                </span>
              </template>
            </n-statistic>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card>
            <n-statistic label="智联招聘">
              <template #prefix>
                <div class="text-sm font-semibold text-gray-700">已用 / 总数</div>
              </template>
              {{ overviewStats.zhilian.used }} / {{ overviewStats.zhilian.total }}
              <template #suffix>
                <span class="text-xs text-green-600" v-if="overviewStats.zhilian.total > 0">
                  {{ ((overviewStats.zhilian.used / overviewStats.zhilian.total) * 100).toFixed(1) }}%
                </span>
              </template>
            </n-statistic>
          </n-card>
        </n-grid-item>
      </n-grid>

      <div class="bg-white p-4 rounded-lg shadow-sm">
        <div class="flex justify-between items-center mb-4">
          <NTabs v-model:value="activeTab" type="line" animated>
            <NTabPane name="boss" tab="Boss直聘" />
            <NTabPane name="qcwy" tab="前程无忧" />
            <NTabPane name="zhilian" tab="智联招聘" />
          </NTabs>
          <NButton type="primary" @click="handleAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-2" />新建关键词
          </NButton>
        </div>

        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="getList"
        >
          <template #queryBar>
            <QueryBarItem label="城市" :label-width="50">
              <NInput
                v-model:value="queryItems.city"
                clearable
                type="text"
                placeholder="请输入城市"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="职位" :label-width="50">
              <NInput
                v-model:value="queryItems.job"
                clearable
                type="text"
                placeholder="请输入职位"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
          </template>
        </CrudTable>
      </div>
    </div>

    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      @save="handleSave"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
      >
        <NFormItem label="城市" path="city" :rule="{ required: true, message: '请输入城市', trigger: ['input', 'blur'] }">
          <NInput v-model:value="modalForm.city" clearable placeholder="请输入城市" />
        </NFormItem>
        <NFormItem label="职位" path="job" :rule="{ required: true, message: '请输入职位', trigger: ['input', 'blur'] }">
          <NInput v-model:value="modalForm.job" clearable placeholder="请输入职位" />
        </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>
