<template>
  <div class="app-container">
    <el-card shadow="always">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">出库拣货选单</span>
            <span class="subtitle">(打印目标: 192.168.9.205)</span>
          </div>
          <div>
            <el-button type="success" :icon="Printer" :disabled="selectedItems.length === 0" @click="handlePreview">
              生成并预览出库单
            </el-button>
          </div>
        </div>
      </template>

      <div class="filter-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input
                v-model="searchKeyword"
                placeholder="请输入物料名称 或 规格型号 进行搜索"
                class="search-input"
                clearable
                :prefix-icon="Search"
            />
          </el-col>

          <el-col :span="12" style="text-align: right;">
            <el-button type="primary" plain :icon="Upload" @click="handleImportBom">
              导入 BOM 表
            </el-button>
            <el-button type="primary" plain :icon="Plus" @click="handleCreateBom">
              创建 BOM 表
            </el-button>
          </el-col>
        </el-row>
      </div>

      <el-alert
          v-if="selectedItems.length > 0"
          :title="`当前已选中 ${selectedItems.length} 项物品`"
          type="success"
          show-icon
          style="margin-bottom: 15px"
          :closable="false"
      />

      <el-table
          v-loading="loading"
          :data="filteredTableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          row-key="uuid"
          border
          height="600"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">{{ row.typeLabel }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="名称" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-html="highlightKeyword(row.name)"></span>
          </template>
        </el-table-column>

        <el-table-column prop="standard" label="规格型号" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-html="highlightKeyword(row.standard)"></span>
          </template>
        </el-table-column>

        <el-table-column prop="batch_no" label="批号" width="120" />
        <el-table-column prop="uuid" label="条码UUID" width="280" show-overflow-tooltip />
        <el-table-column prop="create_time" label="入库时间" width="170" />
      </el-table>
    </el-card>

    <el-dialog
        v-model="previewVisible"
        title="出库单打印预览"
        width="800px"
        destroy-on-close
    >
      <div class="print-preview-content">
        <el-alert title="请核对以下清单，确认无误后点击下方【确认打印】按钮" type="warning" :closable="false" style="margin-bottom: 10px;" />

        <el-table :data="selectedItems" border size="small" style="width: 100%">
          <el-table-column prop="typeLabel" label="类型" width="80" />
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="standard" label="规格" />
          <el-table-column prop="batch_no" label="批号" width="100" />
          <el-table-column prop="uuid" label="条码UUID" show-overflow-tooltip />
        </el-table>

        <div class="summary-info" style="margin-top: 20px; text-align: right; font-weight: bold;">
          总计出库数量: <span style="color: red; font-size: 18px;">{{ selectedItems.length }}</span> 件
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewVisible = false">取消</el-button>
          <el-button type="primary" :loading="printLoading" @click="confirmPrint">
            确认打印
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Printer, Search, Upload, Plus } from '@element-plus/icons-vue'
import { getAllStock, printSelectionList } from '@/api/inbound/stock'
import { ElMessage, ElMessageBox } from 'element-plus'

// --- 类型定义 ---
interface BaseStockItem {
  id: number | string;
  standard: string;
  batch_no: string;
  uuid: string;
  create_time: string;
  // 原始数据中可能存在的字段
  material_name?: string;
  product_name?: string;
}

// 统一后的显示对象
interface DisplayItem extends BaseStockItem {
  name: string;      // 统一后的名称
  type: 'material' | 'semi' | 'product'; // 类型标识
  typeLabel: string; // 类型中文名
}

// --- 状态变量 ---
const loading = ref(false)
const printLoading = ref(false)
const searchKeyword = ref('') // 搜索关键词
const previewVisible = ref(false) // 预览弹窗控制

// 原始扁平化数据
const allStockData = ref<DisplayItem[]>([])

// 当前选中的行
const selectedItems = ref<DisplayItem[]>([])

// --- 计算属性：前端模糊搜索过滤 ---
const filteredTableData = computed(() => {
  const keyword = searchKeyword.value.trim().toLowerCase()
  if (!keyword) {
    return allStockData.value
  }
  return allStockData.value.filter(item => {
    const nameMatch = item.name && item.name.toLowerCase().includes(keyword)
    const stdMatch = item.standard && item.standard.toLowerCase().includes(keyword)
    // 也可以加上UUID搜索
    const uuidMatch = item.uuid && item.uuid.toLowerCase().includes(keyword)
    return nameMatch || stdMatch || uuidMatch
  })
})

// --- 方法 ---

// 1. 获取并处理数据
const fetchData = async () => {
  loading.value = true
  try {
    const res: any = await getAllStock()
    // 假设 res 结构为 { materials: [], semis: [], products: [] }
    const materials = (res.materials || []).map((item: any) => ({
      ...item,
      name: item.material_name,
      type: 'material',
      typeLabel: '采购件'
    }))
    const semis = (res.semis || []).map((item: any) => ({
      ...item,
      name: item.material_name || item.product_name, // 半成品字段名不确定，做个兼容
      type: 'semi',
      typeLabel: '半成品'
    }))
    const products = (res.products || []).map((item: any) => ({
      ...item,
      name: item.product_name,
      type: 'product',
      typeLabel: '成品'
    }))

    // 合并所有数据
    allStockData.value = [...materials, ...semis, ...products]
  } catch (error) {
    console.error(error)
    ElMessage.error('无法获取库存数据')
  } finally {
    loading.value = false
  }
}

// 2. 表格选择
const handleSelectionChange = (val: DisplayItem[]) => {
  selectedItems.value = val
}

// 3. 点击“生成并预览”
const handlePreview = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先勾选需要出库的物品')
    return
  }
  previewVisible.value = true
}

// 4. 确认打印 (在弹窗中触发)
const confirmPrint = async () => {
  printLoading.value = true
  try {
    // 这里调用真实的打印接口
    await printSelectionList(selectedItems.value)
    ElMessage.success('指令已发送，请前往打印机(192.168.9.205)取单')
    previewVisible.value = false // 关闭弹窗
    // 可选：打印后是否清空选中？
    // selectedItems.value = []
    // 注意：el-table 需要调用 clearSelection 方法来清空UI选中状态
  } catch (err) {
    ElMessage.error('打印请求失败')
  } finally {
    printLoading.value = false
  }
}

// 5. BOM 操作占位函数
const handleImportBom = () => {
  // TODO: 打开上传文件的 Dialog 或者跳转页面
  ElMessage.info('点击了导入BOM，请实现具体逻辑')
}

const handleCreateBom = () => {
  // TODO: 打开新建 BOM 的表单
  ElMessage.info('点击了创建BOM，请实现具体逻辑')
}

// 辅助函数：高亮关键词 (可选)
const highlightKeyword = (text: string) => {
  if (!searchKeyword.value || !text) return text
  const reg = new RegExp(searchKeyword.value, 'gi')
  return text.replace(reg, (match) => `<span style="color: red; font-weight: bold;">${match}</span>`)
}

// 辅助函数：标签颜色
const getTypeTag = (type: string) => {
  switch (type) {
    case 'material': return 'info'
    case 'semi': return 'warning'
    case 'product': return 'success'
    default: return ''
  }
}

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

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left .title {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}

.header-left .subtitle {
  font-size: 12px;
  color: #909399;
}

.filter-container {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.search-input {
  width: 100%;
  max-width: 400px;
}
</style>