<template>
  <ContentWrap>
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="queryParams" class="-mb-15px" label-width="84px">
      <el-form-item label="BOM编号">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入BOM编号"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item label="BOM名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入BOM名称"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item label="产品条码">
        <el-input
          v-model="queryParams.productBarCode"
          placeholder="请输入产品条码"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="全部" class="!w-240px" clearable>
          <el-option :value="1" label="启用" />
          <el-option :value="0" label="禁用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="openForm('create')"
          ><Icon icon="ep:plus" class="mr-5px" /> 新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="selectionList.length === 0"
          @click="handleBatchDelete"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table :data="list" v-loading="loading" :stripe="true" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="code" label="BOM编号" min-width="140" />
      <el-table-column prop="name" label="BOM名称" min-width="180" />
      <el-table-column label="产品信息" min-width="200">
        <template #default="{ row }">
          <div>{{ row.productName }}</div>
          <div class="text-gray-400 text-sm">{{ row.productBarCode }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="version" label="版本" width="90" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">{{
            row.status === 1 ? '启用' : '禁用'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="itemCount" label="组件数" width="90" align="center" />
      <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
      <el-table-column label="操作" fixed="right" width="220" align="center">
        <template #default="{ row }">
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" @click="openForm('update', row.id)"
              ><Icon icon="ep:edit"
            /></el-button>
          </el-tooltip>
          <el-tooltip content="明细" placement="top">
            <el-button link type="info" @click="openDetail(row)"><Icon icon="ep:list" /></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" @click="handleDelete(row.id)"
              ><Icon icon="ep:delete"
            /></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="formDialogVisible" :title="formDialogTitle" width="700px" append-to-body>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="BOM编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入BOM编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本" prop="version">
            <el-input v-model="formData.version" placeholder="例如：V1.0" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="BOM名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入BOM名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="产品条码" prop="productBarCode">
            <el-input v-model="formData.productBarCode" placeholder="请输入成品条码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="formData.productName" placeholder="请输入成品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="formDialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="formSubmitting" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>

  <!-- 明细弹窗（只读，演示用） -->
  <el-dialog v-model="detailDialogVisible" title="BOM 明细" width="800px" append-to-body>
    <div class="mb-2 text-gray-500">
      <span>成品：</span>
      <span class="mr-2">{{ currentDetail?.productName }}</span>
      <span class="text-gray-400">({{ currentDetail?.productBarCode }})</span>
    </div>
    <el-table :data="detailItems" border stripe>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="materialCode" label="物料编码" min-width="140" />
      <el-table-column prop="materialName" label="物料名称" min-width="160" />
      <el-table-column prop="unit" label="单位" width="90" align="center" />
      <el-table-column prop="quantity" label="用量" width="100" align="center" />
      <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
    </el-table>
    <template #footer>
      <el-button type="primary" @click="detailDialogVisible = false">知道了</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@/components/Icon'

// 可替换的 Service 层：未来直接改为真实接口调用即可
// 约定：列表分页、增删改查、明细查询
interface BomItemVO {
  id: number
  materialCode: string
  materialName: string
  unit: string
  quantity: number
  remark?: string
}

interface BomVO {
  id: number
  code: string
  name: string
  productBarCode: string
  productName: string
  version: string
  status: 0 | 1
  itemCount: number
  remark?: string
  updateTime: string
}

interface BomQuery {
  pageNo: number
  pageSize: number
  code?: string
  name?: string
  productBarCode?: string
  status?: number | undefined
}

interface BomPageResult {
  list: BomVO[]
  total: number
}

interface BomService {
  getPage(params: BomQuery): Promise<BomPageResult>
  get(id: number): Promise<BomVO | null>
  getItems(id: number): Promise<BomItemVO[]>
  create(data: Partial<BomVO>): Promise<void>
  update(data: Partial<BomVO>): Promise<void>
  delete(id: number): Promise<void>
  deleteBatch(ids: number[]): Promise<void>
}

// Mock 数据源（可无缝替换为真实接口）
const mockDb = reactive({
  boms: [
    {
      id: 1,
      code: 'BOM-202501-001',
      name: 'A产品标准BOM',
      productBarCode: 'P-100001',
      productName: 'A产品',
      version: 'V1.0',
      status: 1,
      itemCount: 3,
      remark: '首版',
      updateTime: '2025-01-01 10:00:00'
    },
    {
      id: 2,
      code: 'BOM-202501-002',
      name: 'B产品试制BOM',
      productBarCode: 'P-100002',
      productName: 'B产品',
      version: 'V0.9',
      status: 0,
      itemCount: 2,
      remark: '试制用',
      updateTime: '2025-01-03 15:20:00'
    }
  ] as BomVO[],
  items: new Map<number, BomItemVO[]>([
    [
      1,
      [
        { id: 11, materialCode: 'M-200001', materialName: '外壳', unit: '个', quantity: 1 },
        { id: 12, materialCode: 'M-200002', materialName: '主板', unit: '块', quantity: 1 },
        { id: 13, materialCode: 'M-200003', materialName: '螺丝', unit: '颗', quantity: 6 }
      ]
    ],
    [
      2,
      [
        { id: 21, materialCode: 'M-300001', materialName: '外壳(B)', unit: '个', quantity: 1 },
        { id: 22, materialCode: 'M-300002', materialName: '主板(B)', unit: '块', quantity: 1 }
      ]
    ]
  ])
})

const mockService: BomService = {
  async getPage(params: BomQuery): Promise<BomPageResult> {
    const { pageNo, pageSize, code, name, productBarCode, status } = params
    let data = [...mockDb.boms]
    if (code) data = data.filter((b) => b.code.includes(code))
    if (name) data = data.filter((b) => b.name.includes(name))
    if (productBarCode) data = data.filter((b) => b.productBarCode.includes(productBarCode))
    if (status !== undefined && status !== null && status !== ('' as any)) {
      data = data.filter((b) => b.status === (status as 0 | 1))
    }
    const total = data.length
    const start = (pageNo - 1) * pageSize
    const end = start + pageSize
    const pageList = data.slice(start, end)
    await sleep(200)
    return { list: pageList, total }
  },
  async get(id: number): Promise<BomVO | null> {
    await sleep(120)
    return mockDb.boms.find((b) => b.id === id) || null
  },
  async getItems(id: number): Promise<BomItemVO[]> {
    await sleep(180)
    return mockDb.items.get(id) || []
  },
  async create(data: Partial<BomVO>): Promise<void> {
    await sleep(150)
    const id = Math.max(0, ...mockDb.boms.map((b) => b.id)) + 1
    const now = new Date().toISOString().replace('T', ' ').slice(0, 19)
    mockDb.boms.unshift({
      id,
      code: data.code || `BOM-${id}`,
      name: data.name || `未命名BOM-${id}`,
      productBarCode: data.productBarCode || '',
      productName: data.productName || '',
      version: data.version || 'V1.0',
      status: (data.status as 0 | 1) ?? 1,
      itemCount: 0,
      remark: data.remark || '',
      updateTime: now
    })
    mockDb.items.set(id, [])
  },
  async update(data: Partial<BomVO>): Promise<void> {
    await sleep(150)
    if (!data.id) return
    const idx = mockDb.boms.findIndex((b) => b.id === data.id)
    if (idx >= 0) {
      const now = new Date().toISOString().replace('T', ' ').slice(0, 19)
      mockDb.boms[idx] = { ...mockDb.boms[idx], ...data, updateTime: now } as BomVO
    }
  },
  async delete(id: number): Promise<void> {
    await sleep(120)
    const idx = mockDb.boms.findIndex((b) => b.id === id)
    if (idx >= 0) mockDb.boms.splice(idx, 1)
    mockDb.items.delete(id)
  },
  async deleteBatch(ids: number[]): Promise<void> {
    await sleep(180)
    for (const id of ids) {
      const i = mockDb.boms.findIndex((b) => b.id === id)
      if (i >= 0) mockDb.boms.splice(i, 1)
      mockDb.items.delete(id)
    }
  }
}

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

// 如果要替换真实接口，仅需在此处将 service 指向真实实现
const service: BomService = mockService

// 页面状态
const loading = ref(false)
const list = ref<BomVO[]>([])
const total = ref(0)
const selectionList = ref<BomVO[]>([])

const queryParams = reactive<BomQuery>({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  productBarCode: undefined,
  status: undefined
})

const formDialogVisible = ref(false)
const formDialogTitle = ref('')
const formSubmitting = ref(false)
const formRef = ref()
const formData = reactive<Partial<BomVO>>({
  id: undefined,
  code: '',
  name: '',
  productBarCode: '',
  productName: '',
  version: 'V1.0',
  status: 1,
  remark: ''
})
const formRules = reactive({
  code: [{ required: true, message: '请输入BOM编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入BOM名称', trigger: 'blur' }],
  productBarCode: [{ required: true, message: '请输入产品条码', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }]
})

const detailDialogVisible = ref(false)
const currentDetail = ref<BomVO | null>(null)
const detailItems = ref<BomItemVO[]>([])

async function getList() {
  loading.value = true
  try {
    const res = await service.getPage({ ...queryParams })
    list.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function handleQuery() {
  queryParams.pageNo = 1
  getList()
}

function resetQuery() {
  queryParams.pageNo = 1
  queryParams.code = undefined
  queryParams.name = undefined
  queryParams.productBarCode = undefined
  queryParams.status = undefined
  getList()
}

function onSelectionChange(rows: BomVO[]) {
  selectionList.value = rows
}

function openForm(type: 'create' | 'update', id?: number) {
  formDialogVisible.value = true
  formDialogTitle.value = type === 'create' ? '新增BOM' : '编辑BOM'
  if (type === 'create') {
    Object.assign(formData, {
      id: undefined,
      code: '',
      name: '',
      productBarCode: '',
      productName: '',
      version: 'V1.0',
      status: 1,
      remark: ''
    })
  } else if (id) {
    service.get(id).then((data) => {
      if (data) Object.assign(formData, data)
    })
  }
}

function submitForm() {
  ;(formRef.value as any)?.validate(async (valid: boolean) => {
    if (!valid) return
    formSubmitting.value = true
    try {
      if (formData.id) {
        await service.update(formData)
        ElMessage.success('修改成功')
      } else {
        await service.create(formData)
        ElMessage.success('新增成功')
      }
      formDialogVisible.value = false
      getList()
    } finally {
      formSubmitting.value = false
    }
  })
}

async function handleDelete(id: number) {
  try {
    await ElMessageBox.confirm('确认删除该BOM吗？', '提示', { type: 'warning' })
    await service.delete(id)
    ElMessage.success('删除成功')
    getList()
  } catch {}
}

async function handleBatchDelete() {
  if (!selectionList.value.length) return
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectionList.value.length} 条记录吗？`, '提示', {
      type: 'warning'
    })
    await service.deleteBatch(selectionList.value.map((i) => i.id))
    ElMessage.success('删除成功')
    getList()
  } catch {}
}

async function openDetail(row: BomVO) {
  currentDetail.value = row
  detailDialogVisible.value = true
  detailItems.value = []
  const items = await service.getItems(row.id)
  detailItems.value = items
}

getList()
</script>

<style scoped></style>
