<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>
        <el-form-item label="库位使用" prop="locationUsage">
          <el-select
            v-model="queryParams.locationUsage"
            placeholder="请选择库位使用"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="item in dict.type.location_usage"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="允许混放产品" prop="allowMixedProducts">
          <el-select
            v-model="queryParams.allowMixedProducts"
            placeholder="请选择是否允许混放产品"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="item in dict.type.yorn"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上架区" prop="zoneCode">
          <el-input
            v-model="queryParams.zoneCode"
            placeholder="请输入上架区"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="拣货区" prop="pickingArea">
          <el-input
            v-model="queryParams.pickingArea"
            placeholder="请输入拣货区"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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="6">
                  <div><strong>上架顺序：</strong>{{ scope.row.putawayOrder || '-' }}</div>
                </el-col>
                <el-col :span="6">
                  <div><strong>拣货顺序：</strong>{{ scope.row.pickingOrder || '-' }}</div>
                </el-col>
                <el-col :span="6">
                  <div><strong>库位处理：</strong>{{ scope.row.locationHandling || '-' }}</div>
                </el-col>
                <el-col :span="6">
                  <div><strong>周转需求：</strong>{{ scope.row.turnoverDemand || '-' }}</div>
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin: 10px 0;">
                <el-col :span="6">
                  <div><strong>库位使用：</strong>
                    <dict-tag :options="dict.type.location_usage" :value="scope.row.locationUsage"/>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div><strong>允许混放产品：</strong>
                    <dict-tag :options="dict.type.yorn" :value="scope.row.allowMixedProducts"/>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div><strong>允许混放批次：</strong>
                    <dict-tag :options="dict.type.yorn" :value="scope.row.allowMixedBatches"/></div>
                </el-col>
                <el-col :span="6">
                  <div><strong>拣货区：</strong>{{ scope.row.pickingArea || '-' }}</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="locationUsage" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.location_usage" :value="scope.row.locationUsage"/>
            </template>
          </el-table-column>
          <el-table-column label="上架区" align="center" prop="zoneCode" width="100" />
          <el-table-column label="拣货区" align="center" prop="pickingArea" width="100" />
          <el-table-column label="允许混放产品" align="center" prop="allowMixedProducts" width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yorn" :value="scope.row.allowMixedProducts"/>
            </template>
          </el-table-column>
          <el-table-column label="允许混放批次" align="center" prop="allowMixedBatches" width="120" >
             <template slot-scope="scope">
              <dict-tag :options="dict.type.yorn" :value="scope.row.allowMixedBatches"/>
            </template>
          </el-table-column>
          <el-table-column label="上架顺序" align="center" prop="putawayOrder" width="100" />
          <el-table-column label="拣货顺序" align="center" prop="pickingOrder" width="100" />
          
          <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(',').filter(n => n.trim()) : [])"
                    :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(',').filter(n => n.trim()).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(',').filter(n => n.trim()).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.is_enabled" :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="1000px" 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-col :span="12">
            <el-form-item label="库位使用" prop="locationUsage">
              <el-select v-model="form.locationUsage" placeholder="请选择库位使用" style="width: 100%;">
                <el-option
                  v-for="item in dict.type.location_usage"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(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="pickingArea">
              <el-input v-model="form.pickingArea" placeholder="请输入拣货区" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上架顺序" prop="putawayOrder">
              <el-input v-model="form.putawayOrder" placeholder="请输入上架顺序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拣货顺序" prop="pickingOrder">
              <el-input v-model="form.pickingOrder" placeholder="请输入拣货顺序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="允许混放产品" prop="allowMixedProducts">
              <el-radio-group v-model="form.allowMixedProducts" 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="allowMixedBatches">
              <el-radio-group v-model="form.allowMixedBatches" style="width: 100%;">
                <el-radio :label="'1'">允许</el-radio>
                <el-radio :label="'0'">不允许</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位处理" prop="locationHandling">
              <el-input v-model="form.locationHandling" placeholder="请输入库位处理" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周转需求" prop="turnoverDemand">
              <el-input v-model="form.turnoverDemand" placeholder="请输入周转需求" />
            </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="initMaterialSelector" 
                  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', 'location_usage', 'yorn','is_enabled'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      locationsList: [],
      title: "",
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locationCode: null,
        locationName: null,
        warehouseId: null,
        locationType: null,
        layerCode: null,
        locationUsage: null,
        allowMixedProducts: null,
        zoneCode: null,
        pickingArea: null
      },

      // 表单数据
      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,
        putawayOrder: null,
        pickingOrder: null,
        locationUsage: null,
        locationHandling: null,
        turnoverDemand: null,
        pickingArea: null,
        allowMixedProducts: null,
        allowMixedBatches: null
      },

      // 表单验证规则
      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: [
          { required: true, message: '仓库不能为空', trigger: 'change' }
        ],
        locationType: [
          { required: true, message: '库位类型不能为空', trigger: 'change' }
        ],
        locationUsage: [
          { required: true, message: '库位使用不能为空', trigger: 'change' }
        ],
        allowMixedProducts: [
          { required: true, message: '允许混放产品不能为空', trigger: 'change' }
        ],
        allowMixedBatches: [
          { required: true, message: '允许混放批次不能为空', trigger: 'change' }
        ],
        isEnabled: [
          { required: true, message: '应用状态不能为空', trigger: 'change' }
        ]
      },

      // 仓库相关
      warehouseList: [],
      loadingWarehouse: false,
      queryWarehouseName: '',

      // 物料选择相关
      showMaterialSelect: false,
      tempSelectedMaterials: {
        materialCodes: [],
        names: [],
        categoryIds: []
      },
      materialCodeToNameMap: {},
      materialMapLoaded: false,

      // 仓库选择器相关
      warehouseSelectorVisible: false,
      warehouseSelectTarget: '',
      currentDetailItem: null
    }
  },
  created() {
    console.log('【Locations组件】开始初始化')
    this.getList()
    this.getWarehouseList()
    this.initMaterialCodeToNameMap()
  },
  methods: {
    // ========== 新增：初始化物料选择器（核心修复数据残留） ==========
    initMaterialSelector() {
      console.log('【初始化物料选择器】清空残留数据')
      // 1. 清空临时选择数据（区分新增/修改）
      this.tempSelectedMaterials = {
        materialCodes: this.form.id ? (this.form.materialCodes ? this.form.materialCodes.split(',').filter(u => u.trim()) : []) : [],
        names: this.form.id ? (this.form.materialNames ? this.form.materialNames.split(',').filter(n => n.trim()) : []) : [],
        categoryIds: this.form.id ? (this.form.allowedCategoryIds ? this.form.allowedCategoryIds.split(',').filter(c => c.trim()) : []) : []
      }
      // 2. 延迟打开弹窗，确保数据先清空
      this.$nextTick(() => {
        this.showMaterialSelect = true
        // 3. 兼容子组件清空选中状态（如果有该方法）
        if (this.$refs.materialsSeletor && this.$refs.materialsSeletor.clearSelection) {
          this.$refs.materialsSeletor.clearSelection()
          // 修改模式下重新设置选中值
          if (this.form.id) {
            this.$refs.materialsSeletor.setSelection(this.tempSelectedMaterials.materialCodes)
          }
        }
      })
    },

    // 清空查询仓库
    clearQueryWarehouse() {
      console.log('【清空查询仓库】执行清空操作')
      this.queryWarehouseName = ''
      this.queryParams.warehouseId = null
      this.handleQuery()
    },
    
    // 清空表单仓库
    clearFormWarehouse() {
      console.log('【清空表单仓库】执行清空操作')
      this.form.warehouseName = ''
      this.form.warehouseId = null
    },
    
    // 仓库选择回调
    handleWarehouseSelected(warehouse) {
      console.log('【仓库选择回调】选中的仓库数据:', warehouse)
      if (!warehouse) return
      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') {
      console.log('【打开仓库选择器】目标:', target)
      this.warehouseSelectTarget = target
      this.warehouseSelectorVisible = true
    },
    
    // 获取仓库列表
    getWarehouseList() {
      console.log('【获取仓库列表】开始请求仓库数据')
      this.loadingWarehouse = true
      listWarehouses({ pageNum: 1, pageSize: 1000, isUsed: 1 }).then(response => {
        console.log('【获取仓库列表】请求成功，返回数据:', response)
        this.warehouseList = response.rows || []
        this.loadingWarehouse = false
      }).catch(error => {
        console.error('【获取仓库列表】请求失败:', error)
        this.warehouseList = []
        this.loadingWarehouse = false
      })
    },
    
    // 根据仓库ID获取仓库名称
    getWarehouseNameById(warehouseId) {
      console.log('【根据仓库ID获取名称】仓库ID:', warehouseId)
      if (!warehouseId) return '-'
      const warehouse = this.warehouseList.find(item => 
        item.warehousesId === warehouseId || item.warehouseId === warehouseId || item.id === warehouseId
      )
      const warehouseName = warehouse ? (warehouse.warehousesName || warehouse.name || warehouse.warehouseName || '-') : '-'
      console.log('【根据仓库ID获取名称】匹配到的仓库名称:', warehouseName)
      return warehouseName
    },
    
    // 初始化物料编码-名称映射表
    async initMaterialCodeToNameMap() {
      console.log('【初始化物料映射表】开始加载物料数据')
      try {
        this.materialMapLoaded = true
        let pageNum = 1
        const pageSize = 1000
        let hasMore = true
        this.materialCodeToNameMap = {}
        
        while (hasMore) {
          console.log(`【初始化物料映射表】请求第${pageNum}页物料数据，每页${pageSize}条`)
          const response = await listMaterials({ 
            pageNum, 
            pageSize, 
            isUsed: 1,
            materialCode: null,
            materialName: null
          })
          
          if (response.rows && response.rows.length) {
            console.log(`【初始化物料映射表】第${pageNum}页返回${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('【初始化物料映射表】完成，映射表长度:', Object.keys(this.materialCodeToNameMap).length)
      } catch (error) {
        console.error('【初始化物料映射表】失败:', error)
        this.materialMapLoaded = false
        this.$modal.msgError('物料数据加载失败，请刷新页面重试！')
      }
    },

    // 行点击事件
    handleRowClick(row, event, column) {
      console.log('【行点击事件】点击的行数据:', row, '列类型:', column.type)
      if (column.type !== 'selection') {
        this.$refs.locationsTable?.toggleRowExpansion(row)
      }
    },

    // 获取库位列表
    getList() {
      console.log('【获取库位列表】查询参数:', this.queryParams)
      this.loading = true
      const params = {
        ...this.queryParams,
        isUsed: 1,
        warehousesId: this.queryParams.warehouseId,
        warehouseId: undefined
      }
      console.log('【获取库位列表】最终请求参数:', params)
      listLocations(params).then(response => {
        console.log('【获取库位列表】请求成功，返回数据:', 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() {
      console.log('【查询事件】执行查询操作')
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置查询条件
    resetQuery() {
      console.log('【重置查询条件】执行重置操作')
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        locationCode: null,
        locationName: null,
        warehouseId: null,
        locationType: null,
        layerCode: null,
        locationUsage: null,
        allowMixedProducts: null,
        zoneCode: null,
        pickingArea: null
      }
      this.queryWarehouseName = ''
      this.getList()
    },

    // 表格选择事件
    handleSelectionChange(selection) {
      console.log('【表格选择事件】选中的行:', selection)
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      console.log('【表格选择事件】处理后 - ids:', this.ids, 'single:', this.single, 'multiple:', this.multiple)
    },

    // 新增库位
    handleAdd() {
      console.log('【新增库位】执行新增操作')
      this.reset()
      this.open = true
      this.title = "添加库位"
    },

    // 修改库位
    async handleUpdate(row) {
      console.log('【修改库位】触发修改操作，传入的行数据:', row)
      this.reset()
      const id = row?.id || this.ids?.[0]
      if (!id) {
        this.$modal.msgWarning('请选择要修改的库位！')
        return
      }
      
      try {
        console.log('【修改库位】请求库位详情，ID:', id)
        const response = await getLocations(id)
        console.log('【修改库位】后端返回库位详情:', response)
        const rowData = response.data
        
        // 映射后端字段到前端
        const formData = {
          ...rowData,
          warehouseId: rowData.warehousesId || rowData.warehouseId || rowData.id,
          warehousesId: undefined
        }
        this.form = JSON.parse(JSON.stringify(formData))
        
        // 设置仓库名称
        if (this.form.warehouseId) {
          this.form.warehouseName = this.getWarehouseNameById(this.form.warehouseId)
        }

        await this.initMaterialCodeToNameMap()

        // 处理物料编码和名称（支持数组或字符串格式）
        let materialCodes = []
        let materialNames = []
        
        // 优先从materialIds数组读取
        if (Array.isArray(rowData.materialIds) && rowData.materialIds.length) {
          materialCodes = rowData.materialIds
            .filter(code => code && code.trim()) 
            .map(code => code.trim().toUpperCase())
            .filter((code, index, self) => self.indexOf(code) === index) 
        } 
        // 兼容字符串格式
        else if (rowData.materialCodes) {
          materialCodes = rowData.materialCodes.split(',')
            .filter(code => code && code.trim())
            .map(code => code.trim().toUpperCase())
            .filter((code, index, self) => self.indexOf(code) === index)
        }

        // 处理物料名称
        if (Array.isArray(rowData.names) && rowData.names.length) {
          materialNames = rowData.names
            .filter(name => name && name.trim())
            .filter((name, index, self) => self.indexOf(name) === index)
        } 
        else if (rowData.materialNames) {
          materialNames = rowData.materialNames.split(',')
            .filter(name => name && name.trim())
            .filter((name, index, self) => self.indexOf(name) === index)
        }
        // 兜底：通过物料编码映射名称
        else if (materialCodes.length) {
          materialNames = materialCodes.map(code => {
            return this.materialCodeToNameMap[code] || `【未匹配】${code}`
          })
        }

        // 处理分类ID
        let categoryIds = []
        if (Array.isArray(rowData.categoryIds) && rowData.categoryIds.length) {
          categoryIds = rowData.categoryIds
            .filter(id => id && id.trim())
            .filter((id, index, self) => self.indexOf(id) === index)
        } 
        else if (rowData.allowedCategoryIds) {
          categoryIds = rowData.allowedCategoryIds.split(',')
            .filter(id => id && id.trim())
            .filter((id, index, self) => self.indexOf(id) === index)
        }

        // 更新表单数据
        this.form.materialCodes = materialCodes.join(',')
        this.form.materialNames = materialNames.join(',')
        this.form.allowedCategoryIds = categoryIds.join(',')

        // 处理分类名称
        if (categoryIds.length && this.$refs.materialsSeletor) {
          const categoryNames = categoryIds.map(code => {
            const rawCode = code.replace(/-/g, '')
            return this.$refs.materialsSeletor.categoryMap?.[rawCode] || code
          })
          this.form.allowedCategoryNames = categoryNames.join(',')
          console.log('【修改库位】处理后的分类名称:', categoryNames)
        } else if (rowData.allowedCategoryNames) {
          this.form.allowedCategoryNames = rowData.allowedCategoryNames
          console.log('【修改库位】使用原始分类名称:', rowData.allowedCategoryNames)
        }

        // 更新临时选择数据
        this.tempSelectedMaterials = {
          materialCodes: materialCodes,
          names: materialNames,
          categoryIds: categoryIds
        }

        console.log('【修改库位】处理后的物料数据:', {
          materialCodes: this.form.materialCodes,
          materialNames: this.form.materialNames,
          categoryIds: this.form.allowedCategoryIds
        })
        
        this.open = true
        this.title = "修改库位"
      } catch (error) {
        console.error('【修改库位】获取库位详情失败:', error)
        this.$modal.msgError('获取数据失败，请重试！')
      }
    },

    // 提交表单
    submitForm() {
      console.log('【提交表单】开始验证表单，当前表单数据:', this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('【提交表单】表单验证通过，开始格式化数据')
          // 格式化物料相关字段（去重、过滤空值）
          const formatField = (value) => {
            if (!value) return ''
            const result = value.split(',')
              .filter(item => item && item.trim())
              .filter((item, index, self) => self.indexOf(item) === index)
              .join(',')
            console.log(`【提交表单】格式化字段值 "${value}" 结果: "${result}"`)
            return result
          }

          this.form.materialCodes = formatField(this.form.materialCodes)
          this.form.materialNames = formatField(this.form.materialNames)
          this.form.allowedCategoryIds = formatField(this.form.allowedCategoryIds)
          this.form.allowedCategoryNames = formatField(this.form.allowedCategoryNames)
          
          // 转换表单数据
          const submitData = {
            ...this.form,
            warehousesId: this.form.warehouseId,
            warehouseId: undefined,
            warehouseName: undefined
          }
          
          console.log('【提交表单】最终提交数据:', submitData)
          const request = this.form.id != null ? updateLocations(submitData) : addLocations(submitData)
          request.then(response => {
            console.log('【提交表单】请求成功:', 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 ? "修改失败" : "新增失败")
          })
        } else {
          console.log('【提交表单】表单验证失败')
        }
      })
    },

    // 删除库位
    handleDelete(row) {
      console.log('【删除库位】触发删除操作，行数据:', row)
      const ids = row?.id ? [row.id] : this.ids
      if (!ids || ids.length === 0) {
        this.$modal.msgWarning('请选择要删除的库位！')
        return
      }
      
      console.log('【删除库位】待删除ID:', ids)
      this.$modal.confirm(
        row?.id ? `是否确认删除库位编号为"${row.locationCode}"的数据项？` : `是否确认删除选中的${ids.length}条库位数据项？`
      ).then(() => {
        console.log('【删除库位】用户确认删除，执行删除请求')
        return delLocations(ids)
      }).then(() => {
        console.log('【删除库位】删除成功')
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
        console.log('【删除库位】用户取消删除或请求失败')
      })
    },

    // 导出库位
    handleExport() {
      console.log('【导出库位】执行导出操作，查询参数:', this.queryParams)
      const exportParams = {
        ...this.queryParams,
        warehousesId: this.queryParams.warehouseId,
        warehouseId: undefined
      }
      console.log('【导出库位】最终导出参数:', exportParams)
      this.download('inventory/locations/export', exportParams, `locations_${new Date().getTime()}.xlsx`)
    },
    
    // 物料选择变化
    handleMaterialSelectionChange(selectedData) {
      console.log('【物料选择变化】接收到的选择数据:', selectedData)
      
      // 修复：从selectedData中取materialIds（而非materialCodes）
      const materialCodes = (selectedData.materialIds || [])
        .filter(code => code && code.trim())
        .map(code => code.trim().toUpperCase())
        .filter((code, index, self) => self.indexOf(code) === index)
      
      // 物料名称取selectedData.names
      const names = (selectedData.names || [])
        .filter(name => name && name.trim())
        .filter((name, index, self) => self.indexOf(name) === index)
      
      // 分类ID取selectedData.categoryIds
      const categoryIds = (selectedData.categoryIds || [])
        .filter(id => id && id.trim())
        .filter((id, index, self) => self.indexOf(id) === index)
      
      this.tempSelectedMaterials = {
        materialCodes,
        names,
        categoryIds
      }
      
      console.log('【物料选择变化】处理后的临时选择数据:', this.tempSelectedMaterials)
    },
    
    // 取消物料选择
    handleMaterialSelectionCancel() {
      console.log('【取消物料选择】执行取消操作，恢复原有选择状态')
      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()) : []
      }
      console.log('【取消物料选择】恢复后的临时选择数据:', this.tempSelectedMaterials)
    },
    
    // 确认物料选择
    confirmMaterialSelection() {
      console.log('【确认物料选择】当前临时选择数据:', this.tempSelectedMaterials)
      
      // 修复：判断tempSelectedMaterials.materialCodes是否有值
      if (!this.tempSelectedMaterials.materialCodes.length) {
        console.warn('【确认物料选择】未选择任何物料，提示用户')
        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 && this.tempSelectedMaterials.categoryIds.length) {
        const categoryNames = this.tempSelectedMaterials.categoryIds.map(code => {
          const rawCode = code.replace(/-/g, '')
          return this.$refs.materialsSeletor.categoryMap?.[rawCode] || code
        }).filter(name => name && name.trim())
        
        this.form.allowedCategoryNames = categoryNames.join(',')
        console.log('【确认物料选择】生成的分类名称:', categoryNames)
      }
      
      console.log('【确认物料选择】更新后的表单物料数据:', {
        materialCodes: this.form.materialCodes,
        materialNames: this.form.materialNames,
        allowedCategoryIds: this.form.allowedCategoryIds,
        allowedCategoryNames: this.form.allowedCategoryNames
      })
      
      this.showMaterialSelect = false
      this.$modal.msgSuccess(`成功选择 ${this.tempSelectedMaterials.names.length} 个物料`)
    },
    
    // 导入库位
    handleImport() {
      console.log('【导入库位】打开导入组件')
      this.$refs.import.show()
    },
    
    // 重置表单
    reset() {
      console.log('【重置表单】执行表单重置')
      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,
        putawayOrder: null,
        pickingOrder: null,
        locationUsage: null,
        locationHandling: null,
        turnoverDemand: null,
        pickingArea: null,
        allowMixedProducts: null,
        allowMixedBatches: null
      }
      this.tempSelectedMaterials = {
        materialCodes: [],
        names: [],
        categoryIds: []
      }
      // 修复：清空物料选择器残留
      if (this.$refs.materialsSeletor && this.$refs.materialsSeletor.clearSelection) {
        this.$refs.materialsSeletor.clearSelection()
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      console.log('【重置表单】重置完成，表单数据:', this.form)
    },
    
    // 取消操作
    cancel() {
      console.log('【取消操作】关闭弹窗并重置表单')
      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>