<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="warehouseId">
          <el-input
            v-model="queryWarehouseName"
            placeholder="请选择仓库"
            readonly
            @focus="openWarehouseSelector('query')"
            @click="openWarehouseSelector('query')"
            :suffix-icon="''"
            clearable
          >
            <template v-if="queryWarehouseName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearQueryWarehouse"
              ></i>
            </template>
          </el-input>
        </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="warehousesName" width="180">
            <template slot-scope="scope">
              {{ scope.row.warehousesName }}
            </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="materialCodes" width="200">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.materialCodes" placement="top">
                <div class="material-names">
                  {{ scope.row.materialCodes ? (scope.row.materialCodes.length > 20 ? scope.row.materialCodes.substring(0, 20) + '...' : scope.row.materialCodes) : '-' }}
                </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-form-item label="仓库" prop="warehouseId">
          <el-input
            v-model="form.warehouseName"
            placeholder="请选择仓库"
            readonly
            @focus="openWarehouseSelector('form')"
            @click="openWarehouseSelector('form')"
            :suffix-icon="''"
            clearable
          >
            <template v-if="form.warehouseName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearFormWarehouse"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        <el-row :gutter="20">
          <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="materialCodes">
              <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="showMaterialSelect = true" 
                  style="align-self: flex-end;"
                >选择物料</el-button>
              </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" 
    >
      <materialsSeletor
        ref="materialsSeletor"
        @selection-change="handleMaterialSelectionChange"
        :selected-material-codes="form.materialCodes ? form.materialCodes.split(',').filter(u => u.trim()) : []"
        :multiple="true"
        :default-category-codes="form.allowedCategoryIds ? form.allowedCategoryIds.split(',').filter(c => c.trim()) : []"
      />

      <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"
    />
    <WarehouseSelector
      v-model="warehouseSelectorVisible"
      @selected="handleWarehouseSelected"
    />
  </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 WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import ImportExcel from "@/components/ImportExcel/index"
import { listMaterials } from "@/api/inventory/materials"

export default {
  name: "Locations",
  components: { materialsSeletor, WarehouseSelector, 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,
        warehouseId: null, // 前端保持warehouseId，内部映射后端的warehousesId
        locationType: null,
        layerCode: null
      },
      
      form: {
        id: null,
        locationCode: null,
        locationName: null,
        warehouseId: null, // 前端保持warehouseId，内部映射后端的warehousesId
        warehouseName: null, // 新增仓库名称字段
        locationType: null,
        zoneCode: null,
        rowCode: null,
        columnCode: null,
        layerCode: null,
        capacity: null,
        volumeCapacity: null,
        allowedHazardLevels: null,
        materialCodes: null,
        materialNames: null,
        allowedCategoryIds: null,
        allowedCategoryNames: null,
        temperatureZone: null,
        isEnabled: 1,
        isUsed: 1,
        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' }
        ],
        warehouseId: [ // 验证规则保持warehouseId
          { required: true, message: '仓库不能为空', trigger: 'change' }
        ],
        locationType: [
          { required: true, message: '库位类型不能为空', trigger: 'change' }
        ],
        isEnabled: [
          { required: true, message: '应用状态不能为空', trigger: 'change' }
        ]
      },
      
      warehouseList: [], // 仓库列表（包含id和名称）
      loadingWarehouse: false,
      queryWarehouseName: '', // 查询用仓库名称
      
      showMaterialSelect: false,
      tempSelectedMaterials: {
        materialCodes: [],
        names: [],
        categoryIds: []
      },
      materialCodeToNameMap: {},
      materialMapLoaded: false,
      warehouseSelectorVisible: false,
      warehouseSelectTarget: '', // 仓库选择目标（query/form）
      currentDetailItem: null // 当前编辑的明细项
    }
  },
  created() {
    this.getList()
    this.getWarehouseList()
    this.initMaterialCodeToNameMap()
  },
  methods: {
    // 清空查询仓库
    clearQueryWarehouse() {
      this.queryWarehouseName = ''
      this.queryParams.warehouseId = null
      this.handleQuery()
    },
    
    // 清空表单仓库
    clearFormWarehouse() {
      this.form.warehouseName = ''
      this.form.warehouseId = null
    },
    
    // 仓库选择回调 - 适配后端返回的warehousesId
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      // 统一处理：优先取warehousesId，兼容warehouseId/id
      const warehouseId = warehouse.warehousesId || warehouse.warehouseId || warehouse.id
      const warehouseName = warehouse.warehousesName || warehouse.name || warehouse.warehouseName
      
      if (this.warehouseSelectTarget === 'query') {
        this.queryParams.warehouseId = warehouseId
        this.queryWarehouseName = warehouseName
        this.handleQuery()
      } else {
        this.form.warehouseId = warehouseId
        this.form.warehouseName = warehouseName
        
        // 更新明细中的默认仓库
        if (this.currentDetailItem) {
          this.currentDetailItem.warehouseId = warehouseId
          this.currentDetailItem.warehouseName = warehouseName
        }
      }
      this.warehouseSelectorVisible = false
    },
    
    // 打开仓库选择器
    openWarehouseSelector(target = 'form') {
      this.warehouseSelectTarget = target
      this.warehouseSelectorVisible = true
    },
    
    // 获取仓库列表（包含id）
    getWarehouseList() {
      this.loadingWarehouse = true
      listWarehouses({ pageNum: 1, pageSize: 1000, isUsed: 1 }).then(response => {
        this.warehouseList = response.rows || []
        this.loadingWarehouse = false
      }).catch(error => {
        console.error('获取仓库列表失败:', error)
        this.warehouseList = []
        this.loadingWarehouse = false
      })
    },
    
    // 根据仓库ID获取仓库名称 - 适配后端的warehousesId
    getWarehouseNameById(warehouseId) {
      if (!warehouseId) return '-'
      // 兼容匹配：同时匹配warehousesId/warehouseId/id
      const warehouse = this.warehouseList.find(item => 
        item.warehousesId === warehouseId || item.warehouseId === warehouseId || item.id === warehouseId
      )
      return warehouse ? (warehouse.warehousesName || warehouse.name || warehouse.warehouseName || '-') : '-'
    },
    
    // 初始化物料编码-名称映射表
    async initMaterialCodeToNameMap() {
      try {
        this.materialMapLoaded = true
        let pageNum = 1
        const pageSize = 1000
        let hasMore = true
        this.materialCodeToNameMap = {}
        
        while (hasMore) {
          const response = await listMaterials({ 
            pageNum, 
            pageSize, 
            isUsed: 1,
            materialCode: null,
            materialName: null
          })
          
          if (response.rows && response.rows.length) {
            response.rows.forEach(item => {
              if (item.materialCode && item.materialName) {
                const code = item.materialCode.trim().toUpperCase()
                this.materialCodeToNameMap[code] = item.materialName
              }
            })
            hasMore = pageNum * pageSize < response.total
            pageNum++
          } else {
            hasMore = false
          }
        }
        console.log('物料映射表初始化完成:', this.materialCodeToNameMap)
      } catch (error) {
        console.error('初始化物料编码-名称映射表失败:', error)
        this.materialMapLoaded = false
        this.$modal.msgError('物料数据加载失败，请刷新页面重试！')
      }
    },

    // 行点击事件（展开/收起）
    handleRowClick(row, event, column) {
      if (column.type !== 'selection') {
        this.$refs.locationsTable?.toggleRowExpansion(row)
      }
    },

    // 获取库位列表 - 适配后端的warehousesId参数
    getList() {
      this.loading = true
      // 转换参数：将前端的warehouseId映射为后端需要的warehousesId
      const params = {
        ...this.queryParams,
        isUsed: 1,
        warehousesId: this.queryParams.warehouseId, // 新增：传递warehousesId给后端
        warehouseId: undefined // 移除：避免重复传参
      }
      listLocations(params).then(response => {
        this.locationsList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取库位列表失败:', error)
        this.locationsList = []
        this.total = 0
        this.loading = false
      })
    },
    
    // 查询事件
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        locationCode: null,
        locationName: null,
        warehouseId: null,
        locationType: null,
        layerCode: null
      }
      this.queryWarehouseName = ''
      this.getList()
    },

    // 表格选择事件
    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 = "添加库位"
    },

    // 修改库位 - 适配后端返回的warehousesId字段
    async handleUpdate(row) {
      this.reset()
      const id = row?.id || this.ids?.[0]
      if (!id) {
        this.$modal.msgWarning('请选择要修改的库位！')
        return
      }
      
      try {
        const response = await getLocations(id)
        console.log('后端返回库位详情:', response.data)
        const rowData = response.data
        // 映射后端的warehousesId到前端的warehouseId
        const formData = {
          ...rowData,
          warehouseId: rowData.warehousesId || rowData.warehouseId || rowData.id, // 优先级：warehousesId > warehouseId > id
          warehousesId: undefined // 移除：前端只维护warehouseId
        }
        this.form = JSON.parse(JSON.stringify(formData))
        
        // 设置仓库名称
        if (this.form.warehouseId) {
          this.form.warehouseName = this.getWarehouseNameById(this.form.warehouseId)
        }

        await this.initMaterialCodeToNameMap()

        // 从allowedCategoryIds读取物料编码（替代缺失的materialCodes）
        const rawMaterialCodes = this.form.allowedCategoryIds || row.allowedCategoryIds || ''
        console.log('原始物料编码(从allowedCategoryIds读取):', rawMaterialCodes)
        
        if (rawMaterialCodes) {
          const materialCodes = rawMaterialCodes.split(',')
            .map(code => code.trim().toUpperCase())
            .filter(code => code)
          
          console.log('处理后物料编码:', materialCodes)
          console.log('映射表匹配:', materialCodes.map(code => ({
            code,
            name: this.materialCodeToNameMap[code]
          })))

          this.form.materialNames = materialCodes.map(code => {
            return this.materialCodeToNameMap[code] || `【未匹配】${code}`
          }).join(',')
          
          // 同步赋值materialCodes（确保选择器能接收到）
          this.form.materialCodes = rawMaterialCodes

          this.tempSelectedMaterials = {
            materialCodes: materialCodes,
            names: this.form.materialNames.split(',').filter(name => name.trim()),
            categoryIds: this.form.allowedCategoryIds ? this.form.allowedCategoryIds.split(',').filter(c => c.trim()) : []
          }
        }
        
        this.open = true
        this.title = "修改库位"
      } catch (error) {
        console.error('获取库位详情失败:', error)
        this.$modal.msgError('获取数据失败，请重试！')
      }
    },

    // 提交表单 - 适配后端的warehousesId参数
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理物料编码和名称
          if (this.form.materialCodes) {
            this.form.materialCodes = this.form.materialCodes.split(',').filter(code => code.trim()).join(',')
          }
          if (this.form.materialNames) {
            this.form.materialNames = this.form.materialNames.split(',').filter(name => name.trim()).join(',')
          }
          
          // 转换表单数据：将前端的warehouseId映射为后端需要的warehousesId
          const submitData = {
            ...this.form,
            warehousesId: this.form.warehouseId, // 新增：传递warehousesId给后端
            warehouseId: undefined, // 移除：避免重复传参
            warehouseName: undefined // 移除：只传ID给后端
          }
          
          const request = this.form.id != null ? updateLocations(submitData) : addLocations(submitData)
          request.then(response => {
            this.$modal.msgSuccess(this.form.id != null ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          }).catch(error => {
            console.error('提交库位数据失败:', error)
            this.$modal.msgError(this.form.id != null ? "修改失败" : "新增失败")
          })
        }
      })
    },

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

    // 导出库位 - 适配后端的warehousesId参数
    handleExport() {
      // 转换导出参数：将前端的warehouseId映射为后端需要的warehousesId
      const exportParams = {
        ...this.queryParams,
        warehousesId: this.queryParams.warehouseId,
        warehouseId: undefined
      }
      this.download('inventory/locations/export', exportParams, `locations_${new Date().getTime()}.xlsx`)
    },
    
    // 物料选择变化
    handleMaterialSelectionChange(selectedData) {
      this.tempSelectedMaterials = {
        materialCodes: selectedData.materialCodes || [],
        names: selectedData.names || [],
        categoryIds: selectedData.formattedCategoryIds || []
      }
    },
    
    // 取消物料选择
    handleMaterialSelectionCancel() {
      this.showMaterialSelect = false
      this.tempSelectedMaterials = {
        materialCodes: this.form.materialCodes ? this.form.materialCodes.split(',').filter(u => u.trim()) : [],
        names: this.form.materialNames ? this.form.materialNames.split(',').filter(n => n.trim()) : [],
        categoryIds: this.form.allowedCategoryIds ? this.form.allowedCategoryIds.split(',').filter(c => c.trim()) : []
      }
    },
    
    // 确认物料选择
    confirmMaterialSelection() {
      if (!this.tempSelectedMaterials.materialCodes.length) {
        this.$modal.msgWarning('请至少选择一个物料！')
        return
      }

      this.form.materialCodes = this.tempSelectedMaterials.materialCodes.join(',')
      this.form.materialNames = this.tempSelectedMaterials.names.join(',')
      this.form.allowedCategoryIds = this.tempSelectedMaterials.categoryIds.join(',')
      
      if (this.$refs.materialsSeletor) {
        const categoryNames = this.tempSelectedMaterials.categoryIds.map(code => {
          const rawCode = code.replace(/-/g, '')
          return this.$refs.materialsSeletor.categoryMap[rawCode] || code
        })
        this.form.allowedCategoryNames = categoryNames.join(',')
      }
      
      this.showMaterialSelect = false
      this.$modal.msgSuccess(`成功选择 ${this.tempSelectedMaterials.names.length} 个物料`)
    },
    
    // 导入库位
    handleImport() {
      this.$refs.import.show()
    },
    
    // 重置表单
    reset() {
      this.form = {
        id: null,
        locationCode: null,
        locationName: null,
        warehouseId: null,
        warehouseName: null,
        locationType: null,
        zoneCode: null,
        rowCode: null,
        columnCode: null,
        layerCode: null,
        capacity: null,
        volumeCapacity: null,
        allowedHazardLevels: null,
        materialCodes: null,
        materialNames: null,
        allowedCategoryIds: null,
        allowedCategoryNames: null,
        temperatureZone: null,
        isEnabled: 1,
        isUsed: 1,
        sortNo: 0
      }
      this.tempSelectedMaterials = {
        materialCodes: [],
        names: [],
        categoryIds: []
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    
    // 取消操作
    cancel() {
      this.open = false
      this.reset()
    }
  }
}
</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;
}
</style>