<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    width="620px"
    class="wms-entity-dialog"
    append-to-body
    @update:model-value="emit('update:visible', $event)"
  >
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="108px">
      <!-- 库区 / 容器 -->
      <template v-if="kind === 'area'">
        <el-form-item label="编码" prop="code"><el-input v-model="masterForm.code" :disabled="isEditing" /></el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="masterForm.name" /></el-form-item>
        <el-form-item label="类型"><el-select v-model="masterForm.type"><el-option v-for="o in AREA_TYPES" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="布局"><el-select v-model="areaLayoutMode"><el-option v-for="o in AREA_LAYOUT_MODES" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="masterForm.sortOrder" :min="0" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="masterForm.enabled" /></el-form-item>
      </template>

      <template v-else-if="kind === 'container'">
        <el-form-item label="编码" prop="code"><el-input v-model="masterForm.code" :disabled="isEditing" /></el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="masterForm.name" /></el-form-item>
        <el-form-item label="容器类型"><el-select v-model="masterForm.type"><el-option v-for="o in CONTAINER_TYPES" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="条码"><el-input v-model="containerBarcode" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="masterForm.enabled" /></el-form-item>
      </template>

      <template v-else-if="kind === 'storage'">
        <el-form-item label="库区"><el-select v-model="storageForm.areaId"><el-option v-for="a in areas" :key="a.id" :label="a.name" :value="a.id" /></el-select></el-form-item>
        <el-form-item label="编码" prop="code"><el-input v-model="storageForm.code" :disabled="isEditing" /></el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="storageForm.name" /></el-form-item>
        <el-form-item label="货位种类"><el-select v-model="storageForm.locationKind"><el-option v-for="o in LOCATION_KINDS" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="库位类型"><el-select v-model="storageForm.storageType"><el-option v-for="o in STORAGE_TYPES" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <template v-if="storageForm.locationKind === 'Grid'">
          <el-form-item label="列"><el-input-number v-model="storageForm.columnNo" :min="0" /></el-form-item>
          <el-form-item label="层"><el-input-number v-model="storageForm.levelNo" :min="1" /></el-form-item>
          <el-form-item label="进深"><el-input-number v-model="storageForm.depthNo" :min="1" /></el-form-item>
        </template>
        <el-form-item label="站点">
          <el-select
            v-model="storageForm.siteId"
            filterable
            clearable
            :loading="sitesLoading"
            placeholder="搜索站点 ID 或名称"
            :filter-method="onSiteFilter"
            class="wms-field-control"
            @change="onSiteChange"
          >
            <el-option v-for="s in displayedSites" :key="s.id" :label="s.label" :value="s.id" />
          </el-select>
          <span v-if="sitesLoadError" class="field-hint field-hint-warn">{{ sitesLoadError }}</span>
          <span v-else class="field-hint">主数据来自 SimpleLite，保存值为站点 id</span>
        </el-form-item>
        <el-form-item label="条码"><el-input v-model="storageForm.barcode" /></el-form-item>
        <el-form-item label="优先级"><el-input-number v-model="storageForm.priority" :min="0" /></el-form-item>
        <el-form-item label="区域"><el-input v-model="storageForm.zoneCode" /></el-form-item>
        <el-form-item label="允许入库"><el-switch v-model="storageForm.allowInbound" /></el-form-item>
        <el-form-item label="允许出库"><el-switch v-model="storageForm.allowOutbound" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="storageForm.enabled" /></el-form-item>
      </template>

      <template v-else-if="kind === 'materialType'">
        <el-form-item label="编码" prop="code"><el-input v-model="materialTypeForm.code" :disabled="isEditing" /></el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="materialTypeForm.name" /></el-form-item>
        <el-form-item label="规格"><el-input v-model="materialTypeForm.spec" /></el-form-item>
        <el-form-item label="单位"><el-select v-model="materialTypeForm.unit" filterable allow-create><el-option v-for="o in MATERIAL_UNITS" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="类别"><el-input v-model="materialTypeForm.category" /></el-form-item>
        <el-form-item label="条码前缀"><el-input v-model="materialTypeForm.barcodePrefix" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="materialTypeForm.enabled" /></el-form-item>
      </template>

      <template v-else-if="kind === 'material'">
        <el-form-item label="编码" prop="code"><el-input v-model="materialForm.code" :disabled="isEditing" /></el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="materialForm.name" /></el-form-item>
        <el-form-item label="物料类型">
          <el-select
            v-model="materialForm.typeCode"
            filterable
            clearable
            allow-create
            placeholder="选择或输入类型编码"
            class="wms-field-control"
            @change="onMaterialTypeChange"
          >
            <el-option v-for="t in materialTypes" :key="t.id" :label="`${t.code} ${t.name}`" :value="t.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="条码"><el-input v-model="materialForm.barcode" /></el-form-item>
        <el-form-item label="规格"><el-input v-model="materialForm.spec" /></el-form-item>
        <el-form-item label="单位"><el-select v-model="materialForm.unit" filterable allow-create><el-option v-for="o in MATERIAL_UNITS" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="类别"><el-input v-model="materialForm.category" /></el-form-item>
        <el-form-item label="生命周期"><el-select v-model="materialForm.lifecycleStatus"><el-option v-for="o in MATERIAL_LIFECYCLES" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="启用"><el-switch v-model="materialForm.enabled" /></el-form-item>
      </template>

      <template v-else-if="kind === 'location'">
        <el-form-item label="容器"><el-select v-model="locationForm.containerId" :disabled="isEditing"><el-option v-for="c in containers" :key="c.id" :label="c.code" :value="c.id" /></el-select></el-form-item>
        <el-form-item label="位置类型"><el-select v-model="locationForm.locationType" :disabled="isEditing"><el-option label="库位" value="Storage" /><el-option label="车辆" value="Car" /></el-select></el-form-item>
        <el-form-item v-if="locationForm.locationType === 'Storage'" label="库位">
          <el-select v-model="locationForm.locationId">
            <el-option v-for="s in availableStorages" :key="s.id" :label="`${s.code} ${s.name}`" :value="s.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="车辆 ID"><el-input v-model="locationForm.locationId" :disabled="isEditing" /></el-form-item>
        <el-form-item label="状态"><el-select v-model="locationForm.status"><el-option v-for="o in CONTAINER_LOCATION_STATUSES" :key="o.value" :label="o.label" :value="o.value" /></el-select></el-form-item>
        <el-form-item label="原因" prop="reason"><el-input v-model="locationForm.reason" placeholder="绑定/转移原因" /></el-form-item>
      </template>

      <template v-else-if="kind === 'containerMaterial'">
        <el-form-item label="容器"><el-select v-model="containerMaterialForm.containerId" :disabled="isEditing"><el-option v-for="c in containers" :key="c.id" :label="c.code" :value="c.id" /></el-select></el-form-item>
        <el-form-item label="物料"><el-select v-model="containerMaterialForm.materialId" filterable :disabled="isEditing"><el-option v-for="m in materials" :key="m.id" :label="`${m.code} ${m.name}`" :value="m.id" /></el-select></el-form-item>
        <el-form-item label="原因" prop="reason"><el-input v-model="containerMaterialForm.reason" placeholder="绑定原因" /></el-form-item>
        <p class="field-hint">按单个物料实体绑定，无数量。</p>
      </template>

      <template v-else-if="kind === 'rule'">
        <el-form-item label="编码" prop="code"><el-input v-model="ruleForm.code" :disabled="isEditing" /></el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="ruleForm.name" /></el-form-item>
        <el-form-item label="触发类型"><el-select v-model="ruleForm.triggerType" :disabled="isEditing"><el-option label="呼叫物料" value="MaterialCall" /><el-option label="成品下线" value="FinishedGoodsOffline" /><el-option label="自动转运" value="AutoTransfer" /></el-select></el-form-item>
        <el-form-item label="优先级"><el-input-number v-model="ruleForm.priority" :min="0" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="ruleForm.enabled" /></el-form-item>
        <el-form-item label="起点 Selector"><el-input v-model="ruleForm.sourceSelectorJson" type="textarea" :rows="4" /></el-form-item>
        <el-form-item label="终点 Selector"><el-input v-model="ruleForm.targetSelectorJson" type="textarea" :rows="4" /></el-form-item>
        <el-form-item label="任务选项"><el-input v-model="ruleForm.taskOptionsJson" type="textarea" :rows="3" /></el-form-item>
      </template>

      <el-form-item label="备注"><el-input v-model="remark" type="textarea" :rows="2" /></el-form-item>

      <el-collapse>
        <el-collapse-item title="高级配置" name="advanced">
          <el-form-item v-if="kind !== 'location' && kind !== 'containerMaterial'" label="锁定"><el-switch v-model="isLock" /></el-form-item>
          <el-form-item label="扩展 JSON"><el-input v-model="extend" type="textarea" :rows="3" /></el-form-item>
        </el-collapse-item>
      </el-collapse>
    </el-form>

    <template #footer>
      <el-button @click="emit('update:visible', false)">取消</el-button>
      <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type {
  WarehouseArea, Storage, Container, Material, MaterialType,
  MasterDataPayload, StoragePayload, MaterialPayload, MaterialTypePayload,
  ContainerLocationPayload, BindMaterialPayload, TransportRulePayload
} from '@/types/wms'
import {
  AREA_TYPES, AREA_LAYOUT_MODES, STORAGE_TYPES, LOCATION_KINDS, CONTAINER_TYPES,
  CONTAINER_LOCATION_STATUSES, MATERIAL_UNITS, MATERIAL_LIFECYCLES
} from './wmsOptions'
import { useSimpleLiteSites } from './useSimpleLiteSites'

export type DialogKind = 'area' | 'storage' | 'container' | 'materialType' | 'material' | 'location' | 'containerMaterial' | 'rule'

const props = defineProps<{
  visible: boolean
  kind: DialogKind
  saving?: boolean
  areas: WarehouseArea[]
  storages: Storage[]
  containers: Container[]
  materials: Material[]
  materialTypes: MaterialType[]
  occupiedStorageIds: Set<string>
  masterForm: MasterDataPayload
  storageForm: StoragePayload
  materialForm: MaterialPayload
  materialTypeForm: MaterialTypePayload
  locationForm: ContainerLocationPayload
  containerMaterialForm: BindMaterialPayload
  ruleForm: TransportRulePayload
}>()

const emit = defineEmits<{
  'update:visible': [boolean]
  save: []
}>()

const formRef = ref<FormInstance>()
const areaLayoutMode = defineModel<string>('areaLayoutMode', { default: 'Flat' })
const containerBarcode = defineModel<string>('containerBarcode', { default: '' })
const { sites: simpleLiteSites, loading: sitesLoading, loadError: sitesLoadError, load: loadSimpleLiteSites } = useSimpleLiteSites()
const siteSearch = ref('')

function onSiteChange(id: string) {
  props.storageForm.siteCode = id || ''
}

function onMaterialTypeChange(code: string) {
  const t = props.materialTypes.find((x) => x.code === code)
  if (!t) return
  if (!props.materialForm.name) props.materialForm.name = t.name
  if (!props.materialForm.spec) props.materialForm.spec = t.spec
  if (!props.materialForm.unit) props.materialForm.unit = t.unit || 'pcs'
  if (!props.materialForm.category) props.materialForm.category = t.category
}

const siteOptionsWithCurrent = computed(() => {
  const opts = [...simpleLiteSites.value]
  const current = props.storageForm.siteId?.trim()
  if (current && !opts.some((o) => o.id === current)) {
    opts.unshift({ id: current, name: '', label: `#${current}（未在 SimpleLite 列表中）` })
  }
  return opts
})

const displayedSites = computed(() => {
  const q = siteSearch.value.trim().toLowerCase()
  if (!q) return siteOptionsWithCurrent.value
  return siteOptionsWithCurrent.value.filter(
    (s) => s.id.includes(q) || s.name.toLowerCase().includes(q) || s.label.toLowerCase().includes(q)
  )
})

function onSiteFilter(query: string) {
  siteSearch.value = query
}

const isEditing = computed(() => {
  if (props.kind === 'storage') return !!props.storageForm.id
  if (props.kind === 'materialType') return !!props.materialTypeForm.id
  if (props.kind === 'material') return !!props.materialForm.id
  if (props.kind === 'location') return !!props.locationForm.id
  if (props.kind === 'containerMaterial') return !!props.containerMaterialForm.id
  if (props.kind === 'rule') return !!props.ruleForm.id
  return !!props.masterForm.id
})

const editCode = computed(() => {
  if (props.kind === 'storage') return props.storageForm.code
  if (props.kind === 'materialType') return props.materialTypeForm.code
  if (props.kind === 'material') return props.materialForm.code
  if (props.kind === 'rule') return props.ruleForm.code
  return props.masterForm.code
})

const title = computed(() => {
  const names: Record<DialogKind, string> = {
    area: '库区', storage: '库位', container: '容器', materialType: '物料类型', material: '物料',
    location: '容器位置', containerMaterial: '容器物料', rule: '搬运规则'
  }
  const code = editCode.value?.trim()
  return isEditing.value && code ? `编辑${names[props.kind]} · ${code}` : `新增${names[props.kind]}`
})

const availableStorages = computed(() =>
  props.storages.filter((s) => !props.occupiedStorageIds.has(s.id) || s.id === props.locationForm.locationId))

const formModel = computed(() => {
  switch (props.kind) {
    case 'storage': return props.storageForm
    case 'materialType': return props.materialTypeForm
    case 'material': return props.materialForm
    case 'location': return props.locationForm
    case 'containerMaterial': return props.containerMaterialForm
    case 'rule': return props.ruleForm
    default: return props.masterForm
  }
})

const remark = computed({
  get: () => formModel.value.remark,
  set: (v: string) => { formModel.value.remark = v }
})
const extend = computed({
  get: () => formModel.value.extend,
  set: (v: string) => { formModel.value.extend = v }
})
const isLock = computed({
  get: () => formModel.value.isLock,
  set: (v: boolean) => { formModel.value.isLock = v }
})

const rules: FormRules = {
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  reason: [{ required: true, message: '请填写原因', trigger: 'blur' }]
}

watch(() => props.visible, (v) => {
  if (v) {
    formRef.value?.clearValidate()
    if (props.kind === 'storage') {
      siteSearch.value = ''
      void loadSimpleLiteSites()
    }
  }
})

async function submit() {
  if (!formRef.value) return
  await formRef.value.validate()
  emit('save')
}
</script>

<style scoped>
.field-hint { display: block; margin-top: 4px; font-size: 12px; color: rgba(91, 33, 182, 0.65); }
.field-hint-warn { color: #c45656; }

/* el-dialog teleport 到 body，脱离 .mg-content 主题覆盖，需单独强化边框与背景对比 */
.wms-entity-dialog :deep(.el-form-item__label) {
  color: rgba(45, 27, 105, 0.88) !important;
}
.wms-entity-dialog :deep(.el-input__wrapper),
.wms-entity-dialog :deep(.el-select .el-input__wrapper),
.wms-entity-dialog :deep(.el-input-number .el-input__wrapper) {
  background: #faf8ff !important;
  box-shadow: 0 0 0 1px rgba(124, 58, 237, 0.34) inset !important;
}
.wms-entity-dialog :deep(.el-input__wrapper:hover),
.wms-entity-dialog :deep(.el-select .el-input__wrapper:hover),
.wms-entity-dialog :deep(.el-input-number .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(124, 58, 237, 0.52) inset !important;
}
.wms-entity-dialog :deep(.el-input__wrapper.is-focus),
.wms-entity-dialog :deep(.el-select .el-input__wrapper.is-focus),
.wms-entity-dialog :deep(.el-input-number .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #7c3aed inset, 0 0 0 3px rgba(124, 58, 237, 0.14) !important;
}
.wms-entity-dialog :deep(.el-input__inner),
.wms-entity-dialog :deep(.el-textarea__inner) {
  color: #2d1b69 !important;
}
.wms-entity-dialog :deep(.el-input__inner::placeholder),
.wms-entity-dialog :deep(.el-textarea__inner::placeholder) {
  color: rgba(91, 33, 182, 0.42) !important;
}
.wms-entity-dialog :deep(.el-textarea__inner) {
  background: #faf8ff !important;
  box-shadow: 0 0 0 1px rgba(124, 58, 237, 0.34) inset !important;
}
.wms-entity-dialog :deep(.el-input-number .el-input-number__decrease),
.wms-entity-dialog :deep(.el-input-number .el-input-number__increase) {
  background: rgba(124, 58, 237, 0.08) !important;
  color: #5b21b6 !important;
  border-color: rgba(124, 58, 237, 0.22) !important;
}
.wms-entity-dialog :deep(.el-collapse) {
  border-top: 1px solid rgba(124, 58, 237, 0.18);
  border-bottom: 1px solid rgba(124, 58, 237, 0.18);
}
.wms-entity-dialog :deep(.el-collapse-item__header) {
  color: #5b21b6 !important;
  background: transparent !important;
  border-bottom: 1px solid rgba(124, 58, 237, 0.12);
}
.wms-entity-dialog :deep(.el-collapse-item__wrap) {
  border-bottom: 1px solid rgba(124, 58, 237, 0.12);
}
</style>
