<template>
  <div class="app-container">
    <el-card shadow="always">
      <template #header>
        <div class="card-header">
          <span class="title">BOM 配方管理</span>
          <div class="header-right">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索 编号/名称/规格/子件..."
                style="width: 300px; margin-right: 15px;"
                clearable
                @clear="fetchBomList"
                @keyup.enter="fetchBomList"
            >
              <template #append>
                <el-button :icon="Search" @click="fetchBomList" />
              </template>
            </el-input>
            <el-button v-if="userStore.hasPermission('bom_manage:operation')" type="primary" :icon="Plus" @click="handleCreate">新建 BOM</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="bomList" border style="width: 100%">
        <el-table-column v-if="hasColumnPermission('bom_no')" prop="bom_no" label="BOM编号" min-width="180" sortable />
        <el-table-column v-if="hasColumnPermission('parent_name')" prop="parent_name" label="父件名称" min-width="150" />
        <el-table-column v-if="hasColumnPermission('parent_spec')" prop="parent_spec" label="父件规格" min-width="150" />
        <el-table-column v-if="hasColumnPermission('version')" prop="version" label="版本" width="100" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="hasColumnPermission('status')" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_enabled ? 'success' : 'danger'">
              {{ row.is_enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="hasColumnPermission('child_count')" prop="child_count" label="子件数" width="80" align="center" />
        <el-table-column v-if="userStore.hasPermission('bom_manage:operation')" label="操作" width="250" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleSaveAs(row)">另存为</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="850px" destroy-on-close :close-on-click-modal="false">
      <el-form :model="form" label-width="120px" ref="formRef" :rules="rules">

        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="父件 (成品)" prop="parent_id" v-if="hasFormFieldPermission('parent_id')">
              <el-select
                  v-model="form.parent_id"
                  placeholder="请搜索并选择父件"
                  filterable
                  style="width: 100%"
                  :disabled="isEditMode"
                  class="beautified-select"
                  :filter-method="filterMaterial"
                  @change="onParentChange"
              >
                <el-option
                    v-for="item in materialOptions"
                    :key="item.id"
                    :label="`${item.name} (${item.spec})`"
                    :value="item.id"
                >
                  <div class="option-row">
                    <span class="option-name">{{ item.name }}</span>
                    <span class="option-spec">{{ item.spec }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用" prop="is_enabled" v-if="hasFormFieldPermission('is_enabled')">
              <el-switch v-model="form.is_enabled" active-text="启用" inactive-text="禁用" :disabled="!userStore.hasPermission('bom_manage:operation')" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="BOM 编号" required v-if="hasFormFieldPermission('bom_no')">
              <el-input v-model="form.bom_no" placeholder="选择父件后自动生成" disabled />
              <div style="font-size: 12px; color: #909399; line-height: 1.2; margin-top: 4px;">
                编号预览: <span style="font-weight: bold">{{ form.bom_no || '请选择父件' }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" v-if="hasFormFieldPermission('remark')">
              <el-input v-model="form.remark" placeholder="备注信息（可选）" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 任务1：另存为模式显示版本选项，新建/编辑模式显示输入框 -->
            <el-form-item label="版本号" prop="version" v-if="hasFormFieldPermission('version')">
              <template v-if="isSaveAsMode">
                <el-radio-group v-model="form.versionUpgradeType" @change="onVersionUpgradeTypeChange">
                  <el-radio-button label="minor">升级次版本 ({{ versionOptions.minor }})</el-radio-button>
                  <el-radio-button label="major">升级主版本 ({{ versionOptions.major }})</el-radio-button>
                </el-radio-group>
              </template>
              <template v-else>
                <el-input v-model="form.version" placeholder="如: V1.0" />
              </template>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="font-weight: bold; margin: 15px 0 10px 0; border-left: 4px solid #409EFF; padding-left: 10px;">
          子件列表
          <span style="font-weight: normal; font-size: 12px; color: #909399; margin-left: 10px;">(已选 {{ filteredChildren.length }} 条)</span>
        </div>

        <!-- 任务2：子件列表本地模糊搜索 -->
        <el-input
            v-model="childSearchKeyword"
            placeholder="请输入子件名称或规格型号搜索"
            clearable
            style="width: 300px; margin-bottom: 10px;"
            :prefix-icon="Search"
        />

        <el-table :data="filteredChildren" border style="width: 100%; margin-bottom: 15px" max-height="300">
          <el-table-column label="子件物料" min-width="280" v-if="hasFormFieldPermission('child_id')">
            <template #default="{ row, $index }">
              <el-select
                  v-model="row.child_id"
                  placeholder="请搜索原料"
                  filterable
                  style="width: 100%"
                  :filter-method="filterMaterial"
                  @change="(val) => onChildChange(val, $index)"
              >
                <el-option
                    v-for="item in materialOptions"
                    :key="item.id"
                    :label="`${item.name} (${item.spec})`"
                    :value="item.id"
                >
                  <div class="option-row">
                    <span class="option-name">{{ item.name }}</span>
                    <span class="option-spec">{{ item.spec }}</span>
                  </div>
                </el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="用量" width="140" v-if="hasFormFieldPermission('dosage')">
            <template #default="{ row }">
              <!-- 任务2：整数精度，去掉调节按钮 -->
              <el-input-number v-model="row.dosage" :min="0" :precision="0" style="width: 100%" :controls="false" />
            </template>
          </el-table-column>

          <el-table-column label="备注" width="150" v-if="hasFormFieldPermission('remark')">
            <template #default="{ row }">
              <el-input v-model="row.remark" placeholder="备注" />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="60" align="center" v-if="userStore.hasPermission('bom_manage:operation')">
            <template #default="{ $index }">
              <el-button type="danger" link @click="removeChild($index)">删</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 10px; text-align: center;" v-if="hasFormFieldPermission('child_id')">
          <el-button type="primary" plain :icon="Plus" @click="addChild" style="width: 100%">添加一行子件</el-button>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getBomList, getBomDetail, saveBom, deleteBom } from '@/api/bom'
import { getMaterialBaseList } from '@/api/inbound/stock'
import { useUserStore } from '@/stores/user'

// 类型定义
interface BomItem {
  bom_no: string
  parent_id: number
  parent_name: string
  version: string
  is_enabled: boolean
  child_count: number
}
interface MaterialBase {
  id: number
  name: string
  spec: string
}
interface ChildRow {
  child_id: number | null
  dosage: number
  remark: string
}

const userStore = useUserStore()
const loading = ref(false)
const dialogVisible = ref(false)
const saving = ref(false)
const isEditMode = ref(false)
const isSaveAsMode = ref(false)  // 任务1：标记是否为另存为模式
let originalVersion = ''  // 保存原始版本号用于计算升级选项
let currentBomNo = ''  // 保存当前操作的 BOM 编号用于计算版本避让
let originalChildren: ChildRow[] = []  // 保存原始子件数据用于本地查重

const bomList = ref<BomItem[]>([])
const materialOptions = ref<MaterialBase[]>([])
const searchKeyword = ref('')
const childSearchKeyword = ref('')  // 任务2：子件列表搜索关键字

// 任务2：子件列表本地模糊搜索 - 计算属性
const filteredChildren = computed(() => {
  if (!childSearchKeyword.value) {
    return form.children
  }
  const kw = childSearchKeyword.value.toLowerCase()
  return form.children.filter(child => {
    // 获取子件物料的名称和规格
    const material = materialOptions.value.find(m => m.id === child.child_id)
    if (!material) return false
    const name = (material.name || '').toLowerCase()
    const spec = (material.spec || '').toLowerCase()
    return name.includes(kw) || spec.includes(kw)
  })
})

// 任务3：自定义过滤方法 - 同时匹配名称和规格
const filterMaterial = (val: string) => {
  if (!val) return true
  const kw = val.toLowerCase()
  return (item: MaterialBase) => {
    const name = (item.name || '').toLowerCase()
    const spec = (item.spec || '').toLowerCase()
    return name.includes(kw) || spec.includes(kw)
  }
}

// 列与权限Code的映射关系（数据库中的code）
const permissionMap: Record<string, string> = {
  bom_no: 'bom_manage:bom_no',
  parent_name: 'bom_manage:parent_name',
  parent_spec: 'bom_manage:parent_spec',
  version: 'bom_manage:version',
  status: 'bom_manage:status',
  child_count: 'bom_manage:child_count',
  // 表单字段
  parent_id: 'bom_manage:parent_id',
  is_enabled: 'bom_manage:status',
  bom_no: 'bom_manage:bom_no',
  child_id: 'bom_manage:child_id',
  dosage: 'bom_manage:dosage',
  remark: 'bom_manage:remark',
}

// 检查列权限
const hasColumnPermission = (prop: string) => {
  if (userStore.role === 'SUPER_ADMIN' || userStore.username === 'IRIS') {
    return true
  }
  const code = permissionMap[prop]
  return code ? userStore.hasPermission(code) : false
}

// 检查表单字段权限
const hasFormFieldPermission = (fieldName: string) => {
  if (userStore.role === 'SUPER_ADMIN' || userStore.username === 'IRIS') {
    return true
  }
  const code = permissionMap[fieldName]
  return code ? userStore.hasPermission(code) : false
}

const formRef = ref<FormInstance>()
const form = reactive({
  bom_no: '',      // 纯净的 BOM 编号（从父件规格提取）
  remark: '',      // BOM 备注信息
  parent_id: null as number | null,
  version: 'V1.0',
  versionUpgradeType: 'minor' as 'minor' | 'major',  // 任务1：另存为时的版本升级类型
  is_enabled: true,
  children: [] as ChildRow[]
})

// 纯净 BOM 编号（直接从表单获取，无拼接逻辑）
const pureBomNo = computed(() => form.bom_no)

// 任务1：根据原版本号计算升级选项（智能避让已占用版本）
const versionOptions = computed(() => {
  const ver = originalVersion || 'V1.0'
  
  // 获取当前 BOM 编号下所有已占用的版本号集合
  const occupiedVersions = new Set(
    bomList.value
      .filter(item => item.bom_no === currentBomNo)
      .map(item => item.version)
  )
  
  // 智能递增避让函数
  const getNextMinor = (baseMajor: number, baseMinor: number): string => {
    let minor = baseMinor + 1
    let candidate = `V${baseMajor}.${minor}`
    while (occupiedVersions.has(candidate)) {
      minor++
      candidate = `V${baseMajor}.${minor}`
    }
    return candidate
  }
  
  const getNextMajor = (baseMajor: number): string => {
    let major = baseMajor + 1
    let candidate = `V${major}.0`
    while (occupiedVersions.has(candidate)) {
      major++
      candidate = `V${major}.0`
    }
    return candidate
  }
  
  // 解析版本号格式 Vx.y
  const match = ver.match(/^V(\d+)\.(\d+)$/)
  if (match) {
    const major = parseInt(match[1])
    const minor = parseInt(match[2])
    return {
      minor: getNextMinor(major, minor),
      major: getNextMajor(major)
    }
  }
  // 无法解析时返回默认选项（带避让）
  return { minor: getNextMinor(1, 0), major: getNextMajor(1) }
})

// 任务1：版本升级类型变更时更新版本号
const onVersionUpgradeTypeChange = (type: 'minor' | 'major') => {
  form.version = versionOptions.value[type]
}

const rules = reactive<FormRules>({
  parent_id: [{ required: true, message: '请选择父件', trigger: 'change' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
})

const dialogTitle = ref('新建 BOM')

const fetchBomList = async () => {
  loading.value = true
  try {
    const res = await getBomList({ keyword: searchKeyword.value })
    if (res.code === 200) bomList.value = res.data
  } catch (error) {
    // 错误已由全局拦截器统一处理
  }
  finally { loading.value = false }
}

const fetchMaterialOptions = async () => {
  try {
    const res = await getMaterialBaseList()
    if (res.code === 200) materialOptions.value = res.data
  } catch (error) {
    // 错误已由全局拦截器统一处理
  }
}

// 监听父件变化，自动设置纯净的 BOM 编号
const onParentChange = (val: number) => {
  const selected = materialOptions.value.find(m => m.id === val)
  if (selected && selected.spec) {
    // 安全提取：取 / 前面的部分作为纯净 BOM 编号
    const rawSpec = selected.spec || ''
    form.bom_no = rawSpec.split('/')[0].trim()
  } else {
    form.bom_no = ''
  }
}

// 任务2：子件物料选中后自动设置用量为1，并检测重复
const onChildChange = (val: number | null, index: number) => {
  if (val !== null) {
    // 任务1：检测重复 - 检查该物料是否已在其他行存在
    const existingIndex = form.children.findIndex((child, idx) => idx !== index && child.child_id === val)
    if (existingIndex !== -1) {
      const material = materialOptions.value.find(m => m.id === val)
      ElMessage.warning(`该物料已在第 ${existingIndex + 1} 行存在，请合并用量或删除重复项`)
      // 清空当前选择
      form.children[index].child_id = null
      form.children[index].dosage = 0
      return
    }
    form.children[index].dosage = 1
  }
}

const handleCreate = () => {
  resetForm()
  dialogTitle.value = '新建 BOM'
  isEditMode.value = false
  isSaveAsMode.value = false  // 确保新建模式
  dialogVisible.value = true
}

const handleEdit = async (row: BomItem) => {
  await loadDetail(row.bom_no, row.version)
  dialogTitle.value = '编辑 BOM'
  isEditMode.value = true // 编辑时不允许修改编号前缀/后缀
  isSaveAsMode.value = false  // 确保编辑模式
  dialogVisible.value = true
}

const handleSaveAs = async (row: BomItem) => {
  await loadDetail(row.bom_no, row.version)
  dialogTitle.value = '另存为新版/变体'
  isEditMode.value = true
  isSaveAsMode.value = true  // 任务1：进入另存为模式，显示版本选项

  // 保存原始版本号和 BOM 编号用于计算升级选项
  originalVersion = form.version
  currentBomNo = row.bom_no  // 保存当前操作的 BOM 编号
  // 保存原始子件数据用于本地查重
  originalChildren = JSON.parse(JSON.stringify(form.children))
  // 默认选中次版本升级
  form.versionUpgradeType = 'minor'
  form.version = versionOptions.value.minor
  dialogVisible.value = true
}

const loadDetail = async (bomNo: string, version: string) => {
  try {
    const res = await getBomDetail(bomNo, version)
    if (res.code === 200) {
      const data = res.data
      form.parent_id = data.parent_id
      form.version = data.version
      form.is_enabled = data.is_enabled
      form.children = data.children.map((child: any) => ({
        child_id: child.child_id,
        dosage: child.dosage,
        remark: child.remark || ''
      }))

      // 解析编号：安全提取纯净 BOM 编号
      if (data.parent_spec) {
        form.bom_no = (data.parent_spec || '').split('/')[0].trim()
      } else {
        // 无父件规格时直接使用 bom_no
        form.bom_no = bomNo.split('/')[0].trim()
      }
      // 加载备注信息
      form.remark = data.remark || ''
    }
  } catch (e) {
    // 错误已由全局拦截器统一处理
  }
}

const handleDelete = (row: BomItem) => {
  ElMessageBox.confirm(`确定删除 ${row.bom_no} (${row.version}) 吗？`, '警告', { type: 'warning' })
      .then(async () => {
        try {
          const res = await deleteBom(row.bom_no, row.version)
          if (res.code === 200) {
            ElMessage.success('删除成功')
            fetchBomList()
          }
        } catch (e) {}
      })
      .catch(() => {})
}

const resetForm = () => {
  form.bom_no = ''
  form.remark = ''
  form.parent_id = null
  form.version = 'V1.0'
  form.versionUpgradeType = 'minor'
  form.is_enabled = true
  form.children = []
  isSaveAsMode.value = false  // 任务1：重置另存为模式
  originalVersion = ''
  currentBomNo = ''  // 重置当前 BOM 编号
  childSearchKeyword.value = ''  // 任务2：重置搜索关键字
  if (formRef.value) formRef.value.resetFields()
}

const addChild = () => form.children.push({ child_id: null, dosage: 0, remark: '' })
const removeChild = (idx: number) => form.children.splice(idx, 1)

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    if (!pureBomNo.value) return ElMessage.warning('BOM编号不能为空')
    if (form.children.length === 0) return ElMessage.warning('请至少添加一个子件')

    // 任务1：提交前校验重复子件
    const childIds = form.children.map(c => c.child_id).filter(id => id !== null)
    const uniqueIds = new Set(childIds)
    if (childIds.length !== uniqueIds.size) {
      return ElMessage.warning('子件列表中存在重复物料，请合并用量或删除重复项')
    }

    // ===== 另存为本地查重：检查是否修改过 =====
    if (isSaveAsMode.value && originalChildren.length > 0) {
      // 将当前 children 和原始 children 转换为 set 进行比较
      const currentSet = new Set(form.children.map(c => `${c.child_id}-${c.dosage}`))
      const originalSet = new Set(originalChildren.map(c => `${c.child_id}-${c.dosage}`))
      
      // 比较两个集合是否完全相同
      const isIdentical = currentSet.size === originalSet.size && 
        [...currentSet].every(item => originalSet.has(item))
      
      if (isIdentical) {
        return ElMessage.warning('您未修改任何子件，与原版本内容一致，请修改后再保存')
      }
    }

    const payload = {
      bom_no: pureBomNo.value,
      remark: form.remark,
      version: form.version,
      parent_id: form.parent_id,
      is_enabled: form.is_enabled,
      children: form.children
    }

    saving.value = true
    try {
      const res = await saveBom(payload)
      if (res.code === 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        fetchBomList()
      } else { ElMessage.error(res.msg || '保存失败') }
    } catch (e: any) {
      // 全局拦截器已处理错误提示，此处不再重复弹窗
      // 如需特殊处理，可在此处添加，但不要调用 ElMessage
    }
    finally { saving.value = false }
  })
}

onMounted(() => {
  fetchBomList()
  fetchMaterialOptions()
})
</script>

<style scoped>
.card-header { display: flex; justify-content: space-between; align-items: center; }
.header-right { display: flex; align-items: center; }
.title { font-size: 18px; font-weight: bold; }
.option-row { display: flex; justify-content: space-between; width: 100%; }
.option-name { font-weight: bold; color: #303133; }
.option-spec { font-size: 12px; color: #909399; margin-left: 15px; }
</style>
