<template>
  <div class="page-container">
    <n-card>
      <div class="search-form">
        <n-form inline :model="searchForm" label-placement="left">
          <n-form-item label="刀具编码">
            <n-input v-model:value="searchForm.toolCode" placeholder="请输入刀具编码" clearable style="width: 140px" />
          </n-form-item>
          <n-form-item label="刀具名称">
            <n-input v-model:value="searchForm.toolName" placeholder="请输入刀具名称" clearable style="width: 140px" />
          </n-form-item>
          <n-form-item label="刀具类型">
            <n-select v-model:value="searchForm.toolType" placeholder="请选择刀具类型" :options="toolTypeOptions" clearable style="width: 140px" />
          </n-form-item>
          <n-form-item label="品牌">
            <n-input v-model:value="searchForm.brand" placeholder="请输入品牌" clearable style="width: 140px" />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSearch">
              <template #icon><n-icon><SearchOutline /></n-icon></template>
              搜索
            </n-button>
          </n-form-item>
          <n-form-item>
            <n-button @click="handleReset">
              <template #icon><n-icon><RefreshOutline /></n-icon></template>
              重置
            </n-button>
          </n-form-item>
        </n-form>
      </div>

      <div class="table-toolbar">
        <n-space>
          <n-button type="primary" @click="handleAdd">
            <template #icon><n-icon><AddOutline /></n-icon></template>
            新增
          </n-button>
          <n-button @click="importModalVisible = true">
            <template #icon><n-icon><CloudUploadOutline /></n-icon></template>
            导入
          </n-button>
          <n-button @click="handleExport">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            导出{{ selectedIds.length > 0 ? `(${selectedIds.length})` : '' }}
          </n-button>
          <n-button type="error" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <template #icon><n-icon><TrashOutline /></n-icon></template>
            删除
          </n-button>
        </n-space>
      </div>

      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :row-key="(row) => row.id"
        :scroll-x="1200"
        @update:checked-row-keys="handleCheck"
      />
    </n-card>

    <n-modal v-model:show="modalVisible" preset="card" :title="modalTitle" style="width: 600px">
      <n-form ref="formRef" :model="formData" label-placement="left" label-width="100px">
        <n-form-item label="刀具编码" path="toolCode">
          <n-input v-model:value="formData.toolCode" placeholder="请输入刀具编码" />
        </n-form-item>
        <n-form-item label="刀具名称" path="toolName">
          <n-input v-model:value="formData.toolName" placeholder="请输入刀具名称" />
        </n-form-item>
        <n-form-item label="刀具类型" path="toolType">
          <n-select v-model:value="formData.toolType" placeholder="请选择刀具类型" :options="toolTypeOptions" />
        </n-form-item>
        <n-form-item label="规格型号" path="spec">
          <n-input v-model:value="formData.spec" placeholder="请输入规格型号" />
        </n-form-item>
        <n-form-item label="品牌" path="brand">
          <n-input v-model:value="formData.brand" placeholder="请输入品牌" />
        </n-form-item>
        <n-form-item label="仓库编码" path="warehouseCode">
          <n-input v-model:value="formData.warehouseCode" placeholder="请输入仓库编码" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal v-model:show="importModalVisible" preset="card" title="导入刀具基础信息" style="width: 500px">
      <n-space vertical>
        <n-alert type="info">
          <template #header>导入说明</template>
          <ul style="margin: 0; padding-left: 16px; line-height: 1.8">
            <li>请先下载导入模板，按模板格式填写数据</li>
            <li>支持 .xlsx 或 .xls 格式</li>
          </ul>
        </n-alert>
        <n-space>
          <n-button type="primary" @click="handleDownloadTemplate">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            下载模板
          </n-button>
        </n-space>
        <n-upload :max="1" accept=".xlsx,.xls" :show-file-list="true" :custom-request="handleImportUpload">
          <n-upload-dragger>
            <div style="margin-bottom: 12px">
              <n-icon size="48" :depth="3"><CloudUploadOutline /></n-icon>
            </div>
            <n-text style="font-size: 16px">点击或拖拽文件到此处上传</n-text>
            <n-p depth="3" style="margin: 8px 0 0 0">支持 .xlsx 或 .xls 格式</n-p>
          </n-upload-dragger>
        </n-upload>
      </n-space>
      <template #footer>
        <n-button @click="importModalVisible = false">关闭</n-button>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted } from 'vue'
import { NButton, NSpace, NIcon, NInput, NSelect, NForm, NFormItem, NDataTable, NCard, NModal, NTag, NUpload, NUploadDragger, NAlert, useMessage, useDialog, type UploadCustomRequestOptions } from 'naive-ui'
import { SearchOutline, RefreshOutline, AddOutline, TrashOutline, CreateOutline, DownloadOutline, CloudUploadOutline } from '@vicons/ionicons5'
import { toolApi } from '@/api/tool'

const message = useMessage()
const dialog = useDialog()

const searchForm = reactive({
  toolCode: '',
  toolName: '',
  toolType: undefined as number | undefined,
  brand: ''
})

const tableData = ref<any[]>([])
const loading = ref(false)
const selectedIds = ref<number[]>([])

const modalVisible = ref(false)
const modalTitle = ref('')
const importModalVisible = ref(false)
const formRef = ref()

const defaultFormData = {
  id: undefined as number | undefined,
  toolCode: '',
  toolName: '',
  toolType: undefined as number | undefined,
  spec: '',
  brand: '',
  warehouseCode: ''
}

const formData = reactive({ ...defaultFormData })

const toolTypeMap: Record<number, string> = {
  1: '钻头',
  2: '铣刀',
  3: '砂轮/研磨',
  4: '丝锥',
  5: '车刀',
  6: '锯片',
  7: '滚齿刀'
}

const getToolTypeName = (type: number) => {
  return toolTypeMap[type] || type
}

const toolTypeOptions = [
  { label: '钻头', value: 1 },
  { label: '铣刀', value: 2 },
  { label: '砂轮/研磨', value: 3 },
  { label: '丝锥', value: 4 },
  { label: '车刀', value: 5 },
  { label: '锯片', value: 6 },
  { label: '滚齿刀', value: 7 }
]

const columns = [
  { type: 'selection' },
  { title: '序号', key: 'index', width: 60, render: (_row: any, index: number) => index + 1 },
  { title: '刀具编码', key: 'toolCode', width: 120 },
  { title: '刀具名称', key: 'toolName', width: 150 },
  {
    title: '刀具类型',
    key: 'toolType',
    width: 100,
    render(row: any) {
      return h(NTag, { type: 'info' }, () => getToolTypeName(row.toolType))
    }
  },
  { title: '规格型号', key: 'spec', width: 120 },
  { title: '品牌', key: 'brand', width: 120 },
  { title: '仓库编码', key: 'warehouseCode', width: 120 },
  { title: '总寿命(小时)', key: 'lifeHour', width: 120 },
  { title: '已使用(小时)', key: 'currentUseHour', width: 120 },
  {
    title: '操作',
    key: 'actions',
    width: 140,
    fixed: 'right',
    render(row: any) {
      return h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'nowrap' } }, [
        h(NButton, { size: 'small', quaternary: true, onClick: () => handleEdit(row) }, {
          default: () => [h(NIcon, null, { default: () => h(CreateOutline) }), ' 编辑']
        }),
        h(NButton, { size: 'small', quaternary: true, type: 'error', onClick: () => handleDelete(row) }, {
          default: () => [h(NIcon, null, { default: () => h(TrashOutline) }), ' 删除']
        })
      ])
    }
  }
]

async function loadData() {
  loading.value = true
  try {
    const res = await toolApi.page({
      page: 1,
      pageSize: 1000,
      toolCode: searchForm.toolCode || undefined,
      toolName: searchForm.toolName || undefined,
      toolType: searchForm.toolType,
      brand: searchForm.brand || undefined
    })
    tableData.value = res.list || []
  } catch (error: any) {
    console.error('加载数据失败:', error)
    tableData.value = []
    message.error(error?.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  loadData()
}

function handleReset() {
  searchForm.toolCode = ''
  searchForm.toolName = ''
  searchForm.toolType = undefined
  searchForm.brand = ''
  handleSearch()
}

function handleCheck(keys: Array<string | number>) {
  selectedIds.value = keys as number[]
}

function handleAdd() {
  modalTitle.value = '新增刀具'
  Object.assign(formData, defaultFormData)
  modalVisible.value = true
}

function handleEdit(row: any) {
  modalTitle.value = '编辑刀具'
  Object.assign(formData, row)
  modalVisible.value = true
}

async function handleSubmit() {
  await formRef.value?.validate()
  try {
    if (formData.id) {
      await toolApi.update(formData)
      message.success('修改成功')
    } else {
      await toolApi.create(formData)
      message.success('新增成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error) {
  }
}

function handleDelete(row: any) {
  dialog.warning({
    title: '提示',
    content: `确定要删除刀具「${row.toolName}」吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await toolApi.delete([row.id])
        message.success('删除成功')
        loadData()
      } catch (error) {
      }
    }
  })
}

function handleBatchDelete() {
  dialog.warning({
    title: '提示',
    content: `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await toolApi.delete(selectedIds.value)
        message.success('删除成功')
        selectedIds.value = []
        loadData()
      } catch (error) {
      }
    }
  })
}

async function handleExport() {
  try {
    const res = await toolApi.export({
      toolCode: searchForm.toolCode || undefined,
      toolName: searchForm.toolName || undefined
    })
    const url = window.URL.createObjectURL(res)
    const a = document.createElement('a')
    a.href = url
    a.download = '刀具基础信息数据.xlsx'
    a.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
  }
}

async function handleDownloadTemplate() {
  try {
    const blob = await toolApi.downloadTemplate()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '刀具基础信息导入模板.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
  }
}

async function handleImportUpload({ file }: UploadCustomRequestOptions) {
  if (!file.file) return
  try {
    const result = await toolApi.importData(file.file)
    if (result.fail > 0) {
      dialog.warning({
        title: '导入结果',
        content: `成功: ${result.success} 条，失败: ${result.fail} 条\n错误信息: ${(result.errors || []).join('\n') || '无'}`,
        positiveText: '确定'
      })
    } else {
      message.success(`导入成功，共 ${result.success} 条数据`)
      importModalVisible.value = false
    }
    loadData()
  } catch (error) {
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 12px;
}

.search-form :deep(.n-form-item) {
  margin-right: 8px;
  margin-bottom: 0;
}

.search-form :deep(.n-form-item-label) {
  padding-right: 6px;
}

.search-form :deep(.n-form-item-control) {
  flex: none;
}

.table-toolbar {
  margin-bottom: 12px;
}
</style>
