<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <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
          @change="handleQuery"
          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
          @change="handleQuery"
          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>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inventory:locations:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:locations:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:locations:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inventory:locations:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="locationsTable" v-loading="loading" :data="locationsList" @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>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库位编码" align="center" prop="locationCode" width="120" />
      <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">
          {{ selectDictLabel(dict.type.location_type, scope.row.locationType) }}
        </template>
      </el-table-column>
      <el-table-column label="库位容量(千克)" align="center" prop="capacity" />
      <el-table-column label="体积容量(立方米)" align="center" prop="volumeCapacity" />
      <el-table-column label="允许存放的危险等级" align="center" prop="allowedHazardLevels"  />
      <el-table-column label="允许存放的分类名称" align="center" prop="allowedCategoryNames" width="300">
        <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="120" />
      <el-table-column label="应用状态" align="center" prop="isEnabled" width="100" fixed="right">
        <template slot-scope="scope">
          {{ selectDictLabel(dict.type.sys_normal_disable, 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="180" fixed="right" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" 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>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" 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 v-model="form.capacity" placeholder="请输入库位容量(千克)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体积容量(立方米)" prop="volumeCapacity">
              <el-input v-model="form.volumeCapacity" placeholder="请输入体积容量(立方米)" />
            </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="materialUuids">
              <div style="display: flex; align-items: center;">
                <el-input v-model="form.materialNames" placeholder="" readonly style="flex: 1;" />
                <el-button type="primary" size="small" @click="showMaterialSelect = true" style="margin-left: 10px">选择物料</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 v-model.number="form.sortNo" type="number" placeholder="请输入排序" min="0" step="1" />
            </el-form-item>
          </el-col>
          <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>

    <!-- 物料选择组件 -->
    <MaterialSelectComponent
      :visible.sync="showMaterialSelect"
      @selection-confirm="handleMaterialSelectionConfirm"
      @selection-cancel="handleMaterialSelectionCancel"
    />
  </div>
</template>

<script>
import { listLocations, getLocations, delLocations, addLocations, updateLocations } from "@/api/inventory/locations"
import { listWarehouses } from "@/api/inventory/warehouses"
import MaterialSelectComponent from "./MaterialSelectComponent.vue"

export default {
  name: "Locations",
  components: { MaterialSelectComponent },
  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,
        zoneCode: null,
        rowCode: null,
        columnCode: null,
        layerCode: null,
        capacity: null,
        volumeCapacity: null,
        allowedHazardLevels: null,
        allowedCategoryIds: null,
        temperatureZone: null,
        isEnabled: null,
        isUsed: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      },
      // 表单参数
      form: {},
      // 表单校验
      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' }
        ]
      },
      // 仓库列表
      warehouseOptions: [],
      // 仓库加载状态
      loadingWarehouse: false,
      // 物料选择组件显示状态
      showMaterialSelect: false
    }
  },
  created() {
    this.getList()
    this.getWarehouseOptions()
  },
  methods: {
    /** 处理行点击事件 */
    handleRowClick(row, event, column) {
      // 排除点击选择列时触发展开/折叠
      if (column.type !== 'selection') {
        this.$refs.locationsTable.toggleRowExpansion(row)
      }
    },
    /** 查询库位列表 */
    getList() {
      this.loading = true
      // 添加is_used=0条件，只查询未被使用的库位
      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
      // 移除isUsed=0条件，查询所有仓库
      listWarehouses({ pageNum: 1, pageSize: 100 }).then(response => {
        // 调试：查看仓库数据结构
        console.log('仓库数据:', response)
        
        // 确保rows存在且为数组
        const rows = response.rows || []
        
        // 处理不同可能的数据结构
        this.warehouseOptions = rows.map(item => {
          // 根据实际数据结构调整字段名
          const warehouseName = item.warehousesName || item.name || '未命名仓库'
          const warehouseCode = item.warehouseCode || item.code || item.warehousesCode || ''
          
          return {
            label: `${warehouseName} (${warehouseCode})`,
            value: warehouseCode
          }
        }).filter(option => option.value) // 过滤掉无效的仓库选项
        
        console.log('处理后的仓库选项:', this.warehouseOptions)
        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,
        materialUuids: null,
        materialNames: null,
        temperatureZone: null,
        isEnabled: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      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 = "添加库位"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getLocations(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改库位"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 直接使用表单数据，不需要转换仓库编码字段名
          const submitData = {
            ...this.form
          }
          
          if (this.form.id != null) {
            updateLocations(submitData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLocations(submitData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除库位编号为"' + ids + '"的数据项？').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`)
    },
    
    /** 处理物料选择确认 */
    handleMaterialSelectionConfirm(uuids, names) {
      this.form.materialUuids = uuids
      this.form.materialNames = names
    },
    
    /** 处理物料选择取消 */
    handleMaterialSelectionCancel() {
      // 可以根据需要执行取消操作
    }
  }
}
</script>
