<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: 'ESG关联' })

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

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: 'ESG',
  initForm: { code: '', name: '', level: '', number: '', remark: '' },
  doCreate: api.createESG,
  doUpdate: api.updateESG,
  doDelete: api.deleteESG,
  refresh: () => $table.value?.handleSearch(),
})

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

const columns = [
  {
    title: 'ESG代码',
    key: 'code',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: 'ESG名称',
    key: 'name',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: 'ESG级别',
    key: 'level',
    width: 120,
    align: 'center',
    render(row) {
      const levelMap = {
        'E': { type: 'success', text: '环境(E)' },
        'S': { type: 'info', text: '社会(S)' },
        'G': { type: 'warning', text: '治理(G)' },
        'ESG': { type: 'error', text: '综合ESG' }
      }
      const level = levelMap[row.level] || { type: 'default', text: row.level }
      return h(
        NTag,
        { type: level.type },
        { default: () => level.text }
      )
    },
  },
  {
    title: 'ESG编号',
    key: 'number',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '备注',
    key: 'remark',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    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/esg/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/esg/delete']]
        ),
      ]
    },
  },
]

const modalRules = {
  code: [
    {
      required: true,
      message: '请输入ESG代码',
      trigger: ['input', 'blur'],
    },
  ],
  name: [
    {
      required: true,
      message: '请输入ESG名称',
      trigger: ['input', 'blur'],
    },
  ],
  level: [
    {
      required: true,
      message: '请输入ESG级别',
      trigger: ['input', 'blur'],
    },
  ],
  number: [
    {
      required: true,
      message: '请输入ESG编号',
      trigger: ['input', 'blur'],
    },
  ],
}
</script>

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

    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="{ ordering: 'id' }"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.getESGList"
    >
      <template #queryBar>
        <QueryBarItem label="ESG代码" :label-width="80">
          <NInput
            v-model:value="queryItems.code"
            type="text"
            placeholder="请输入ESG代码"
            @keydown.enter="$table?.handleSearch"
          />
        </QueryBarItem>
        <QueryBarItem label="ESG名称" :label-width="80">
          <NInput
            v-model:value="queryItems.name"
            type="text"
            placeholder="请输入ESG名称"
            @keydown.enter="$table?.handleSearch"
          />
        </QueryBarItem>
        <QueryBarItem label="ESG级别" :label-width="80">
          <NInput
            v-model:value="queryItems.level"
            type="text"
            placeholder="请输入ESG级别"
            @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="ESG代码" path="code">
          <NInput v-model:value="modalForm.code" placeholder="请输入ESG代码" />
        </NFormItem>
        <NFormItem label="ESG名称" path="name">
          <NInput v-model:value="modalForm.name" placeholder="请输入ESG名称" />
        </NFormItem>
        <NFormItem label="ESG级别" path="level">
          <NInput v-model:value="modalForm.level" placeholder="请输入ESG级别（如：E, S, G, ESG）" />
        </NFormItem>
        <NFormItem label="ESG编号" path="number">
          <NInput v-model:value="modalForm.number" placeholder="请输入ESG编号" />
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput v-model:value="modalForm.remark" type="textarea" placeholder="请输入备注" />
        </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>