<template>
  <div class="gi_table_page">
    <GiTable
      title="物料管理管理"
      row-key="id"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      :disabled-tools="['size']"
      :disabled-column-keys="['name']"
      @refresh="search"
    >
      <template #toolbar-left>
        <a-input-search v-model="queryForm.materialName" placeholder="请输入物料名称" allow-clear @search="search" />
        <a-input-search v-model="queryForm.encoding" placeholder="请输入物料编码" allow-clear @search="search" />
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['admin:materialInfo:add']" type="primary" @click="onAdd">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
        <a-button v-permission="['admin:materialInfo:import']" @click="onImport">
          <template #icon><icon-upload /></template>
          <template #default>导入</template>
        </a-button>
        <a-button v-permission="['admin:materialInfo:export']" @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>
      <!-- 物料照片插槽：核心新增部分 -->
      <template #photoUrl="{ record }">
        <div class="photo-container">
          <img
            v-if="record.photoUrl"
            :src="record.photoUrl"
            alt="物料照片"
            class="material-photo"
            @error="handleImgError($event)"
          />
          <span v-else class="no-photo">暂无照片</span>
        </div>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['admin:materialInfo:update']" title="修改" @click="onUpdate(record)">修改</a-link>
          <a-link
            v-permission="['admin:materialInfo:delete']"
            status="danger"
            :disabled="record.disabled"
            :title="record.disabled ? '不可删除' : '删除'"
            @click="onDelete(record)"
          >
            删除
          </a-link>
        </a-space>
      </template>
    </GiTable>

    <MaterialInfoAddModal ref="MaterialInfoAddModalRef" @save-success="search" />
    <MaterialInfoImportDrawer ref="MaterialInfoImportDrawerRef" @save-success="search" />
  </div>
</template>

<script setup lang="ts">
import MaterialInfoAddModal from './MaterialInfoAddModal.vue'
import MaterialInfoImportDrawer from './MaterialInfoImportDrawer.vue'
import { type MaterialInfoQuery, type MaterialInfoResp, deleteMaterialInfo, exportMaterialInfo, listMaterialInfo } from '@/apis/material/materialInfo'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { useDownload, useTable } from '@/hooks'
import { isMobile } from '@/utils'
import has from '@/utils/has'

defineOptions({ name: 'MaterialInfo' })

const queryForm = reactive<MaterialInfoQuery>({
  materialName: undefined,
  encoding: undefined,
  sort: ['id,desc'],
})

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete,
} = useTable((page) => listMaterialInfo({ ...queryForm, ...page }), { immediate: true })
const columns = ref<TableInstanceColumns[]>([
  { title: '物料名称', dataIndex: 'materialName', slotName: 'materialName' },
  { title: '物料编码', dataIndex: 'encoding', slotName: 'encoding' },
  { title: '物料单位重量(g)', dataIndex: 'unitWeight', slotName: 'unitWeight' },
  { title: '物料规格', dataIndex: 'materialSpec', slotName: 'materialSpec' },
  { title: '物料照片', dataIndex: 'photoUrl', slotName: 'photoUrl', width: 120, align: 'center' },
  { title: '创建人', dataIndex: 'createUserString', slotName: 'createUser' },
  { title: '创建时间', dataIndex: 'createTime', slotName: 'createTime' },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 160,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr(['admin:materialInfo:detail', 'admin:materialInfo:update', 'admin:materialInfo:delete']),
  },
])

// 重置
const reset = () => {
  queryForm.materialName = undefined
  queryForm.encoding = undefined
  search()
}

// 删除
const onDelete = (record: MaterialInfoResp) => {
  return handleDelete(() => deleteMaterialInfo(record.id), {
    content: `是否确定删除该条数据？`,
    showModal: true,
  })
}

// 导出
const onExport = () => {
  useDownload(() => exportMaterialInfo(queryForm))
}

// 图片加载失败处理函数（新增）
const handleImgError = (e: Event) => {
  // 替换为你的默认图片地址（建议放在/static目录下）
  const target = e.target as HTMLImageElement
  target.src = '/static/images/default-material.png'
}

const MaterialInfoAddModalRef = ref<InstanceType<typeof MaterialInfoAddModal>>()
// 新增
const onAdd = () => {
  MaterialInfoAddModalRef.value?.onAdd()
}

// 修改
const onUpdate = (record: MaterialInfoResp) => {
  MaterialInfoAddModalRef.value?.onUpdate(record.id)
}

const MaterialInfoImportDrawerRef = ref<InstanceType<typeof MaterialInfoImportDrawer>>()
const onImport = () => {
  MaterialInfoImportDrawerRef.value?.onOpen()
}
</script>

<style scoped lang="scss">
// 物料照片样式（新增）
.photo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80px;
}

.material-photo {
  width: 80px;
  height: 80px;
  object-fit: cover; // 保持图片比例，避免拉伸
  border-radius: 4px;
}

.no-photo {
  color: #999;
  font-size: 12px;
}
</style>
