<template>
  <div class="app-container">
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:locations:add']"
        >新增</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:locations:edit']"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:locations:remove']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:locations:export']"
        >导出</el-button>
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="medium"
          @click="handleImport"
          v-hasPermi="['inventory:locations:add']"
        >导入</el-button>
      </template>
    </PageTitle>

    <div class="page-container">
      <page-wrapper-search 
        :model="queryParams" 
        ref="queryForm" 
        size="small" 
        @search="handleQuery"
        @reset="resetQuery"
      >
        <el-form-item label="库位编码" prop="locationCode">
          <el-input
            v-model="queryParams.locationCode"
            placeholder="请输入库位编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="库位名称" prop="locationName">
          <el-input
            v-model="queryParams.locationName"
            placeholder="请输入库位名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库编码" prop="warehousesCode">
          <el-select
            v-model="queryParams.warehousesCode"
            placeholder="请选择仓库编码"
            clearable
            filterable
            style="width: 100%;"
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.value"
              :label="warehouse.label"
              :value="warehouse.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="层" prop="layerCode">
          <el-input
            v-model="queryParams.layerCode"
            placeholder="请输入层"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="库位类型" prop="locationType">
          <el-select
            v-model="queryParams.locationType"
            placeholder="请选择库位类型"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="item in dict.type.location_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </page-wrapper-search>
      
      <div class="table-container">
        <el-table 
          ref="locationsTable" 
          v-loading="loading" 
          :data="locationsList" 
          height="100%"
          @selection-change="handleSelectionChange" 
          @row-click="handleRowClick" 
          row-key="id"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :gutter="20" style="margin: 10px 0;">
                <el-col :span="6">
                  <div><strong>区域代码：</strong>{{ scope.row.zoneCode || '-' }}</div>
                </el-col>
                <el-col :span="6">
                  <div><strong>排：</strong>{{ scope.row.rowCode || '-' }}</div>
                </el-col>
                <el-col :span="6">
                  <div><strong>列：</strong>{{ scope.row.columnCode || '-' }}</div>
                </el-col>
                <el-col :span="6">
                  <div><strong>层：</strong>{{ scope.row.layerCode || '-' }}</div>
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin: 10px 0;">
                <el-col :span="24">
                  <div><strong>允许存放物料名称：</strong>{{ scope.row.materialNames || '-' }}</div>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="55" align="center" fixed />
          <el-table-column label="库位编码" align="center" prop="locationCode" width="120" fixed />
          <el-table-column label="库位名称" align="center" prop="locationName" width="150" />
          <el-table-column label="仓库编码" align="center" prop="warehousesCode" width="180">
            <template slot-scope="scope">
              {{ getWarehouseName(scope.row.warehousesCode) }}
            </template>
          </el-table-column>
          <el-table-column label="库位类型" align="center" prop="locationType" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.location_type" :value="scope.row.locationType"/>
            </template>
          </el-table-column>
          <el-table-column label="库位容量(千克)" align="center" prop="capacity" width="120" />
          <el-table-column label="体积容量(立方米)" align="center" prop="volumeCapacity" width="120" />
          <el-table-column label="允许存放的危险等级" align="center" prop="allowedHazardLevels" width="140" />
          <el-table-column label="允许存放的分类名称" align="center" prop="allowedCategoryNames" width="200">
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row.allowedCategoryNames"
                placement="top"
                effect="light"
                :disabled="!(scope.row.allowedCategoryNames && scope.row.allowedCategoryNames.split(',').length > 3)"
              >
                <div class="category-tags">
                  <el-tag
                    v-for="(name, index) in (scope.row.allowedCategoryNames ? scope.row.allowedCategoryNames.split(',') : [])"
                    :key="name"
                    type="info"
                    size="small"
                    style="margin-right: 5px; margin-bottom: 5px;"
                    v-show="index < 3"
                  >
                    {{ name }}
                  </el-tag>
                  <el-tag
                    v-if="(scope.row.allowedCategoryNames ? scope.row.allowedCategoryNames.split(',').length : 0) > 3"
                    type="info"
                    size="small"
                    style="margin-right: 5px; margin-bottom: 5px; background: #f0f9eb; border-color: #c2e7b0;"
                  >
                    +{{ (scope.row.allowedCategoryNames ? scope.row.allowedCategoryNames.split(',').length : 0) - 3 }}
                  </el-tag>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="温区" align="center" prop="temperatureZone" width="100" />
          <el-table-column label="应用状态" align="center" prop="isEnabled" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isEnabled"/>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sortNo" width="80" />
          <el-table-column label="创建日期" align="center" prop="createTime" width="160" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['inventory:locations:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['inventory:locations:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改库位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位编码" prop="locationCode">
              <el-input 
                v-model="form.locationCode" 
                placeholder="请输入库位编码" 
                :readonly="!!form.id" 
                :disabled="!!form.id"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位名称" prop="locationName">
              <el-input 
                v-model="form.locationName" 
                placeholder="请输入库位名称" 
                :readonly="!!form.id" 
                :disabled="!!form.id"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehousesCode">
              <el-select
                v-model="form.warehousesCode"
                placeholder="请选择仓库编码"
                filterable
                :loading="loadingWarehouse"
                style="width: 100%;"
              >
                <el-option
                  v-for="warehouse in warehouseOptions"
                  :key="warehouse.value"
                  :label="warehouse.label"
                  :value="warehouse.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位类型" prop="locationType">
              <el-select v-model="form.locationType" placeholder="请选择库位类型" style="width: 100%;">
                <el-option
                  v-for="item in dict.type.location_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域代码" prop="zoneCode">
              <el-input v-model="form.zoneCode" placeholder="请输入区域代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排" prop="rowCode">
              <el-input v-model="form.rowCode" placeholder="请输入排" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="列" prop="columnCode">
              <el-input v-model="form.columnCode" placeholder="请输入列" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="层" prop="layerCode">
              <el-input v-model="form.layerCode" placeholder="请输入层" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位容量(千克)" prop="capacity">
              <el-input-number 
                v-model="form.capacity" 
                placeholder="请输入库位容量(千克)" 
                :min="0" 
                :step="0.01" 
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体积容量(立方米)" prop="volumeCapacity">
              <el-input-number 
                v-model="form.volumeCapacity" 
                placeholder="请输入体积容量(立方米)" 
                :min="0" 
                :step="0.01" 
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存放危险等级" prop="allowedHazardLevels">
              <el-input v-model="form.allowedHazardLevels" placeholder="请输入允许存放的危险等级" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="允许存放物料" prop="allowedCategoryIds">
              <div style="display: flex; align-items: center; flex-direction: column; gap: 8px;">
                <el-input 
                  v-model="form.materialNames" 
                  placeholder="请选择允许存放的物料" 
                  readonly 
                  style="width: 100%;" 
                />
                <el-button 
                  type="primary" 
                  size="small" 
                  @click.stop="openMaterialSelector" 
                  style="align-self: flex-end;"
                >选择物料</el-button>
              </div>
              <div style="margin-top: 8px; font-size: 12px; color: #666;">
                已选SAP号：{{ form.allowedCategoryIds || '无' }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应用状态" prop="isEnabled">
              <el-radio-group v-model="form.isEnabled" style="width: 100%;">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortNo">
              <el-input-number 
                v-model="form.sortNo" 
                placeholder="请输入排序" 
                :min="0" 
                :step="1" 
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="温区" prop="temperatureZone">
              <el-input v-model="form.temperatureZone" type="textarea" placeholder="请输入温区信息" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择允许存放的物料对话框 -->
    <el-dialog
      title="选择允许存放的物料"
      :visible.sync="showMaterialSelect"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"  
      :close-on-press-escape="false" 
      @open="initMaterialSelector"
    >
      <!-- 关键修复：v-if确保弹窗打开时才初始化组件 -->
      <materialsSeletor
        v-if="showMaterialSelect"
        ref="materialsSeletor"
        @selection-change="handleMaterialSelectionChange"
        :selected-material-codes="selectedSapCodes"
        :multiple="true"
        :default-category-codes="[]"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleMaterialSelectionCancel">取消</el-button>
        <el-button type="primary" @click="confirmMaterialSelection">确认选择</el-button>
      </div>
    </el-dialog>

    <!-- 导入组件 -->
    <import-excel
      ref="import"
      title="库位导入"
      import-url="/inventory/locations/import"
      template-url="inventory/locations/importTemplate"
      template-name="locations_importTemplate"
      @success="getList"
    />
  </div>
</template>

<script>
import { listLocations, getLocations, delLocations, addLocations, updateLocations } from "@/api/inventory/locations"
import { listWarehouses } from "@/api/inventory/warehouses"
import materialsSeletor from "@/components/materialsSeletor.vue"
import ImportExcel from "@/components/ImportExcel/index"
import { listMaterials } from "@/api/inventory/materials"

export default {
  name: "Locations",
  components: { materialsSeletor, ImportExcel },
  dicts: ['sys_normal_disable', 'location_type'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      locationsList: [],
      title: "",
      open: false,
      
      dict: {
        type: {
          location_type: [
            { label: "货架", value: "1" },
            { label: "地面", value: "2" },
            { label: "货位", value: "3" },
            { label: "专区", value: "4" }
          ],
          sys_normal_disable: [
            { label: "启用", value: "1" },
            { label: "禁用", value: "0" }
          ]
        }
      },
      
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locationCode: null,
        locationName: null,
        warehousesCode: null,
        locationType: null,
        layerCode: null
      },
      
      form: {
        id: null,
        locationCode: null,
        locationName: null,
        warehousesCode: null,
        locationType: null,
        zoneCode: null,
        rowCode: null,
        columnCode: null,
        layerCode: null,
        capacity: null,
        volumeCapacity: null,
        allowedHazardLevels: null,
        allowedCategoryIds: null, // 核心字段：存储逗号分隔的SAP号
        materialNames: null, // 存储物料名称（逗号分隔，用于显示）
        allowedCategoryNames: null, // 存储物料分类名称（逗号分隔）
        temperatureZone: null,
        isEnabled: 1,
        isUsed: 0,
        sortNo: 0
      },
      
      rules: {
        locationCode: [
          { required: true, message: '库位编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '库位编码长度不能超过50个字符', trigger: 'blur' }
        ],
        locationName: [
          { required: true, message: '库位名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '库位名称长度不能超过100个字符', trigger: 'blur' }
        ],
        warehousesCode: [
          { required: true, message: '仓库编码不能为空', trigger: 'change' }
        ],
        locationType: [
          { required: true, message: '库位类型不能为空', trigger: 'change' }
        ],
        isEnabled: [
          { required: true, message: '应用状态不能为空', trigger: 'change' }
        ],
        allowedCategoryIds: [
          { required: true, message: '请选择允许存放的物料', trigger: 'blur' }
        ]
      },
      
      warehouseOptions: [],
      loadingWarehouse: false,
      
      showMaterialSelect: false,
      tempSelectedMaterials: { // 临时存储选择的物料数据
        materialCodes: [], // SAP号数组
        names: [], // 物料名称数组
        categoryIds: [] // 分类ID数组
      },
      materialCodeToNameMap: {}, // SAP号→物料名称映射表
      materialMapLoaded: false // 映射表加载状态
    }
  },
  computed: {
    // 计算属性：统一处理SAP号大小写，确保反显参数正确
    selectedSapCodes() {
      if (!this.form.allowedCategoryIds) return []
      // 核心修复：转大写 + 去空 + 去重
      return this.form.allowedCategoryIds.split(',')
        .map(code => code.trim().toUpperCase())
        .filter(code => code)
        .filter((code, index, self) => self.indexOf(code) === index)
    }
  },
  created() {
    this.getList()
    this.getWarehouseOptions()
    this.initMaterialCodeToNameMap() // 初始化SAP号-名称映射
  },
  methods: {
    /** 初始化SAP号→物料名称映射表（用于反显） */
    async initMaterialCodeToNameMap() {
      try {
        this.materialMapLoaded = false
        let pageNum = 1
        const pageSize = 1000
        let hasMore = true
        this.materialCodeToNameMap = {}
        
        while (hasMore) {
          const response = await listMaterials({ 
            pageNum, 
            pageSize, 
            isUsed: 1 // 只查询启用的物料
          })
          
          if (response.rows && response.rows.length) {
            response.rows.forEach(item => {
              if (item.sapNo && item.materialName) {
                const sapCode = item.sapNo.trim().toUpperCase() // SAP号统一大写存储
                this.materialCodeToNameMap[sapCode] = item.materialName
              }
            })
            hasMore = pageNum * pageSize < response.total
            pageNum++
          } else {
            hasMore = false
          }
        }
        this.materialMapLoaded = true
        console.log('SAP号-物料名称映射表初始化完成:', this.materialCodeToNameMap)
      } catch (error) {
        console.error('初始化SAP号-物料名称映射表失败:', error)
        this.materialMapLoaded = false
        this.$modal.msgError('物料数据加载失败，请刷新页面重试！')
      }
    },

    /** 表格行点击展开详情 */
    handleRowClick(row, event, column) {
      if (column.type !== 'selection') {
        this.$refs.locationsTable.toggleRowExpansion(row)
      }
    },

    /** 获取库位列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        isUsed: 0 // 只查询未删除的库位
      }
      listLocations(params).then(response => {
        this.locationsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    
    /** 获取仓库下拉选项 */
    getWarehouseOptions() {
      this.loadingWarehouse = true
      listWarehouses({ pageNum: 1, pageSize: 100 }).then(response => {
        const rows = response.rows || []
        this.warehouseOptions = rows.map(item => ({
          label: `${item.warehousesName || item.name || '未命名仓库'} (${item.warehouseCode || item.code || item.warehousesCode || ''})`,
          value: item.warehouseCode || item.code || item.warehousesCode || ''
        })).filter(option => option.value)
        this.loadingWarehouse = false
      }).catch(error => {
        console.error('获取仓库列表失败:', error)
        this.warehouseOptions = []
        this.loadingWarehouse = false
      })
    },
    
    /** 根据仓库编码获取仓库名称 */
    getWarehouseName(warehouseCode) {
      if (!warehouseCode) return ''
      const warehouse = this.warehouseOptions.find(item => item.value === warehouseCode)
      return warehouse ? warehouse.label : warehouseCode
    },

    /** 取消操作，关闭弹窗并重置 */
    cancel() {
      this.open = false
      this.reset() // 重置表单状态，避免数据残留
    },

    /** 重置表单（关键：清空所有状态，避免数据残留） */
    reset() {
      this.form = {
        id: null,
        locationCode: null,
        locationName: null,
        warehousesCode: null,
        locationType: null,
        zoneCode: null,
        rowCode: null,
        columnCode: null,
        layerCode: null,
        capacity: null,
        volumeCapacity: null,
        allowedHazardLevels: null,
        allowedCategoryIds: null, // 清空SAP号
        materialNames: null, // 清空物料名称
        allowedCategoryNames: null, // 清空分类名称
        temperatureZone: null,
        isEnabled: 1,
        isUsed: 0,
        sortNo: 0
      }
      // 清空临时选择的物料数据
      this.tempSelectedMaterials = {
        materialCodes: [],
        names: [],
        categoryIds: []
      }
      // 重置物料选择器（关键：避免切换时残留选中状态）
      if (this.$refs.materialsSeletor) {
        // 调用选择器内部的清空方法（需组件支持）
        if (typeof this.$refs.materialsSeletor.clearSelection === 'function') {
          this.$refs.materialsSeletor.clearSelection()
        }
        if (typeof this.$refs.materialsSeletor.resetQuery === 'function') {
          this.$refs.materialsSeletor.resetQuery()
        }
      }
      // 重置表单校验
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.showMaterialSelect = false
    },

    /** 查询库位列表 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置查询条件 */
    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields()
      }
      this.handleQuery()
    },

    /** 表格选择事件 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增库位 */
    handleAdd() {
      this.reset() // 新增前先重置，避免残留修改的数据
      this.open = true
      this.title = "添加库位"
    },

    /** 修改库位（反显数据，基于allowedCategoryIds存储的SAP号） */
    async handleUpdate(row) {
      this.reset() // 修改前先重置，避免数据残留
      const id = row.id || this.ids
      
      try {
        const response = await getLocations(id)
        const data = response.data || {}
        this.form = { ...this.form, ...data } // 赋值基础字段
        
        // 等待映射表加载完成，再处理SAP号反显
        if (!this.materialMapLoaded) {
          await this.initMaterialCodeToNameMap()
        }
        
        // 核心修复：统一转大写，确保匹配映射表
        const sapCodes = this.form.allowedCategoryIds 
          ? this.form.allowedCategoryIds.split(',').map(code => code.trim().toUpperCase()).filter(code => code)
          : []
        
        console.log('反显的SAP号(转大写后):', sapCodes)
        console.log('映射表匹配结果:', sapCodes.map(code => ({
          code,
          name: this.materialCodeToNameMap[code]
        })))
        
        // 匹配物料名称
        this.form.materialNames = sapCodes.map(code => {
          return this.materialCodeToNameMap[code] || `【未匹配】${code}`
        }).join(',')
        
        // 临时存储选中的物料数据（用于物料选择器回显）
        this.tempSelectedMaterials = {
          materialCodes: sapCodes,
          names: this.form.materialNames.split(',').filter(name => name.trim()),
          categoryIds: [] // 分类ID按需从后端获取，此处暂空
        }
        
        this.open = true
        this.title = "修改库位"
      } catch (error) {
        console.error('获取库位详情失败:', error)
        this.$modal.msgError('获取数据失败，请重试！')
      }
    },

    /** 提交表单（新增/修改） */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理SAP号：去重、去空、统一大写，用逗号分隔
          const sapCodes = this.form.allowedCategoryIds 
            ? this.form.allowedCategoryIds.split(',')
                .map(code => code.trim().toUpperCase())
                .filter(code => code)
                .filter((code, index, self) => self.indexOf(code) === index) // 去重
            : []
          
          this.form.allowedCategoryIds = sapCodes.join(',') // 重新赋值SAP号
          
          // 物料名称与SAP号保持一致
          this.form.materialNames = sapCodes.map(code => {
            return this.materialCodeToNameMap[code] || `【未匹配】${code}`
          }).join(',')
          
          // 提交到后端
          if (this.form.id != null) {
            updateLocations(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLocations(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除库位 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm(row.id ? `是否确认删除库位编号为"${row.locationCode}"的数据项？` : `是否确认删除选中的${ids.length}条库位数据项？`).then(function() {
        return delLocations(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    /** 导出库位数据 */
    handleExport() {
      this.download('inventory/locations/export', {
        ...this.queryParams
      }, `locations_${new Date().getTime()}.xlsx`)
    },

    /** 打开物料选择器（封装逻辑，确保数据加载完成） */
    openMaterialSelector() {
      // 确保映射表加载完成
      if (!this.materialMapLoaded) {
        this.$modal.msgWarning('物料数据正在加载，请稍候！')
        this.initMaterialCodeToNameMap().then(() => {
          this.showMaterialSelect = true
        })
        return
      }
      this.showMaterialSelect = true
    },

    /** 初始化物料选择器（弹窗打开时触发） */
    initMaterialSelector() {
      // 主动触发选择器反显（需组件支持setSelectedCodes方法）
      if (this.$refs.materialsSeletor && typeof this.$refs.materialsSeletor.setSelectedCodes === 'function') {
        this.$refs.materialsSeletor.setSelectedCodes(this.selectedSapCodes)
      }
      console.log('物料选择器反显参数:', this.selectedSapCodes)
    },
    
    /** 物料选择器选择事件（接收选中的物料数据） */
    handleMaterialSelectionChange(selectedData) {
      this.tempSelectedMaterials = {
        materialCodes: selectedData.materialCodes || [], // SAP号数组
        names: selectedData.names || [], // 物料名称数组
        categoryIds: selectedData.categoryIds || [] // 分类ID数组
      }
    },
    
    /** 取消物料选择 */
    handleMaterialSelectionCancel() {
      this.showMaterialSelect = false
      // 恢复之前选择的物料数据（避免取消后丢失已选数据）
      this.tempSelectedMaterials = {
        materialCodes: this.form.allowedCategoryIds ? this.form.allowedCategoryIds.split(',').filter(code => code.trim()).map(code => code.toUpperCase()) : [],
        names: this.form.materialNames ? this.form.materialNames.split(',').filter(name => name.trim()) : [],
        categoryIds: []
      }
    },
    
    /** 确认选择物料（将选中的SAP号赋值给allowedCategoryIds） */
    confirmMaterialSelection() {
      const { materialCodes, names, categoryIds } = this.tempSelectedMaterials
      
      if (!materialCodes.length) {
        this.$modal.msgWarning('请至少选择一个物料！')
        return
      }
      
      // 核心：将选中的SAP号用逗号分隔存储到allowedCategoryIds
      this.form.allowedCategoryIds = materialCodes.join(',')
      // 存储物料名称（用于显示）
      this.form.materialNames = names.join(',')
      // 存储分类名称（按需处理）
      this.form.allowedCategoryNames = categoryIds.map(id => {
        return this.$refs.materialsSeletor?.categoryMap[id] || id
      }).join(',')
      
      this.showMaterialSelect = false
      this.$modal.msgSuccess(`成功选择 ${materialCodes.length} 个物料（SAP号：${this.form.allowedCategoryIds}）`)
    },
    
    /** 导入库位数据 */
    handleImport() {
      this.$refs.import.show()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  height: 100%;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 80px);
}

.table-container {
  flex: 1;
  margin-top: 16px;
  overflow: hidden;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.material-names {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dialog-footer {
  text-align: center;
}

/deep/ .el-table .el-table__expand-icon {
  color: #1989fa;
}

/deep/ .el-tooltip__popper {
  max-width: 300px;
  white-space: normal;
}

/* 优化SAP号显示样式 */
/deep/ .el-form-item__content .el-input {
  margin-bottom: 4px;
}

.el-form-item__content .el-button {
  margin-top: 4px;
}

.el-form-item__content div[style*="font-size: 12px"] {
  color: #888;
}
</style>