<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSpace,
  NTag,
  NPopconfirm,
} 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 { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'

defineOptions({ name: '政策匹配' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '政策',
  initForm: { code: '', name: '', level: '', score: 0 },
  doCreate: api.createPolicy,
  doUpdate: api.updatePolicy,
  doDelete: api.deletePolicy,
  refresh: () => $table.value?.handleSearch(),
})

onMounted(() => {
  $table.value?.handleSearch()
})

const columns = [
  {
    title: '政策代码',
    key: 'code',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '政策名称',
    key: 'name',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '政策级别',
    key: 'level',
    width: 120,
    align: 'center',
    render(row) {
      const levelMap = {
        'national': { type: 'error', text: '国家级' },
        'provincial': { type: 'warning', text: '省级' },
        'municipal': { type: 'info', text: '市级' },
        'county': { type: 'default', text: '县级' }
      }
      const level = levelMap[row.level] || { type: 'default', text: row.level }
      return h(
        NTag,
        { type: level.type },
        { default: () => level.text }
      )
    },
  },
  {
    title: '政策评分',
    key: 'score',
    width: 120,
    align: 'center',
    render(row) {
      const getScoreType = (score) => {
        if (score >= 80) return 'success'
        if (score >= 60) return 'warning'
        return 'error'
      }
      return h(
        NTag,
        { type: getScoreType(row.score) },
        { default: () => `${row.score}分` }
      )
    },
  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 180,
    render(row) {
      return h(
        NButton,
        { size: 'small', type: 'text', ghost: true },
        {
          default: () => formatDate(row.created_at),
          icon: renderIcon('mdi:update', { size: 16 }),
        }
      )
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 240,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              secondary: true,
              onClick: () => handleEdit(row),
            },
            { default: () => '编辑', icon: renderIcon('material-symbols:edit-outline', { size: 16 }) }
          ),
          [[vPermission, 'post/api/v1/policy/update']]
        ),

        withDirectives(
          h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete([row.id], false),
            },
            {
              default: () => '确认删除',
              trigger: () =>
                h(
                  NButton,
                  { size: 'small', type: 'error', style: 'margin-left: 12px;' },
                  { default: () => '删除', icon: renderIcon('material-symbols:delete-outline', { size: 16 }) }
                ),
            }
          ),
          [[vPermission, 'delete/api/v1/policy/delete']]
        ),
      ]
    },
  },
]

const modalRules = {
  code: [
    {
      required: true,
      message: '请输入政策代码',
      trigger: ['input', 'blur'],
    },
  ],
  name: [
    {
      required: true,
      message: '请输入政策名称',
      trigger: ['input', 'blur'],
    },
  ],
  level: [
    {
      required: true,
      message: '请输入政策级别',
      trigger: ['input', 'blur'],
    },
  ],
  score: [
    {
      required: true,
      type: 'number',
      message: '请输入政策评分',
      trigger: ['input', 'blur'],
    },
  ],
}
</script>

<template>
  <CommonPage show-footer title="政策匹配">
    <template #action>
      <div>
        <NButton
          v-permission="'post/api/v1/policy/create'"
          class="float-right mb-8"
          type="primary"
          @click="handleAdd"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建政策
        </NButton>
      </div>
    </template>

    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="{ ordering: 'id' }"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.getPolicyList"
    >
      <template #queryBar>
        <QueryBarItem label="政策代码" :label-width="80">
          <NInput
            v-model:value="queryItems.code"
            type="text"
            placeholder="请输入政策代码"
            @keydown.enter="$table?.handleSearch"
          />
        </QueryBarItem>
        <QueryBarItem label="政策名称" :label-width="80">
          <NInput
            v-model:value="queryItems.name"
            type="text"
            placeholder="请输入政策名称"
            @keydown.enter="$table?.handleSearch"
          />
        </QueryBarItem>
        <QueryBarItem label="政策级别" :label-width="80">
          <NInput
            v-model:value="queryItems.level"
            type="text"
            placeholder="请输入政策级别"
            @keydown.enter="$table?.handleSearch"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑弹窗 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      :show-footer="true"
      @save="handleSave"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :rules="modalRules"
      >
        <NFormItem label="政策代码" path="code">
          <NInput v-model:value="modalForm.code" placeholder="请输入政策代码" />
        </NFormItem>
        <NFormItem label="政策名称" path="name">
          <NInput v-model:value="modalForm.name" placeholder="请输入政策名称" />
        </NFormItem>
        <NFormItem label="政策级别" path="level">
          <NInput v-model:value="modalForm.level" placeholder="请输入政策级别（如：national, provincial, municipal, county）" />
        </NFormItem>
        <NFormItem label="政策评分" path="score">
          <NInputNumber v-model:value="modalForm.score" placeholder="请输入政策评分" :min="0" :max="100" :precision="0" />
        </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>