<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:inbound:export']"
        >导出</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="物料SAPNO" prop="sapNo">
          <el-input
            v-model="queryParams.sapNo"
            placeholder="请输入物料SAPNO"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="关联入库单单号" prop="orderId">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入入库单单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="批次" prop="batchId">
          <el-input
            v-model="queryParams.batchId"
            placeholder="请输入批次"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="仓库" prop="warehouseId">
          <el-input
            v-model="queryWarehouseName"
            placeholder="请选择仓库"
            readonly
            @focus="openWarehouseSelector"
            :suffix-icon="''"
          >
            <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="locationId">
          <el-input
            v-model="queryLocationName"
            placeholder="请选择库位"
            readonly
            @focus="openLocationSelector"
            :suffix-icon="''"

          >
            <template v-if="queryLocationName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearQueryLocation"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="标签颜色" prop="labelColor">
          <el-select v-model="queryParams.labelColor" placeholder="请选择标签颜色" clearable>
            <el-option
              v-for="dict in dict.type.label_color"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </page-wrapper-search>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          height="100%"
          :data="inboundList"
          @selection-change="handleSelectionChange"
          :row-key="(row) => row.materialId + '_' + row.orderId + '_' + row.warehousesName + '_' + row.locationName"
        >
          <el-table-column label="物料SAPNO" align="center" prop="sapNo" width="200"/>
          <el-table-column label="物料名称" align="center" prop="materialName" width="200"/>
          <el-table-column label="关联入库单" align="center" prop="orderId" :show-overflow-tooltip="true" width="200"/>
          <el-table-column label="批次号" align="center" prop="batchId" :show-overflow-tooltip="true" width="200"/>
          <el-table-column label="源仓库" align="center" prop="warehousesName" width="200"/>
          <el-table-column label="库位" align="center" prop="locationName" width="200"/>
          <el-table-column label="入库数量" align="center" prop="actualQuantity" width="200"/>
          <el-table-column label="件数" align="center" prop="actualPackages" width="200"/>
          <el-table-column label="单价" align="center" prop="unitPrice" width="200"/>
          <el-table-column label="入库批次物料总价" align="center" prop="totalPrice" width="200"/>
          <el-table-column label="标签颜色" align="center" prop="labelColor" width="200">
            <template slot-scope="scope">
              <el-tag
                :type="getDictListClass('label_color', scope.row.labelColor)"
                size="small"
              >
                {{ getDictLabel('label_color', scope.row.labelColor) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" width="200"/>
          <el-table-column label="入库时间" align="center" prop="inboundDate" width="200">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.inboundDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 仓库选择组件 -->
      <WarehouseSelector
        v-model="warehouseSelectorVisible"
        @selected="handleWarehouseSelected"
      />

      <!-- 库位选择组件 -->
      <LocationSelector
        v-model="locationSelectorVisible"

        @selected="handleLocationSelected"
      />
    </div>
  </div>
</template>

<script>
import { inbound_details } from "@/api/inventory/inbound_items"
import PageTitle from "@/components/PageTitle"
import PageWrapperSearch from "@/components/Search/PageWrapperSearch"
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"

export default {
  name: "InboundDetails",
  dicts: ['label_color'],
  components: {
    PageTitle,
    PageWrapperSearch,
    WarehouseSelector,
    LocationSelector
  },
  data() {
    return {
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 入库表格数据
      inboundList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sapNo: null,
        materialName: null,
        orderId: null,
        batchId: null,
        warehouseId: null,
        locationId: null,
        labelColor: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 封装字典取值方法
    getDictLabel(dictType, value) {
      if (!value || !this.dict?.type?.[dictType]) return '-';
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.label || '-';
    },
    getDictListClass(dictType, value) {
      if (!value || !this.dict?.type?.[dictType]) return '-';
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.raw?.listClass || '';
    },

    /** 查询入库列表 */
    getList() {
      this.loading = true
      inbound_details(this.queryParams).then(response => {
        this.inboundList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sapNo: null,
        materialName: null,
        orderId: null,
        batchId: null,
        warehouseId: null,
        locationId: null,
        labelColor: null
      }
      this.queryWarehouseName = null
      this.queryLocationName = null
      this.handleQuery()
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 打开仓库选择器 */
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true
    },

    /** 仓库选择回调 */
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      this.queryParams.warehouseId = warehouse.warehouseId
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehousesCode
      // 仓库选择后，清空库位信息
      // this.queryLocationName = null
      // this.queryParams.locationId = null
      this.handleQuery()
    },

    /** 清空仓库选择 */
    clearQueryWarehouse() {
      this.queryWarehouseName = null
      this.queryParams.warehouseId = null
      // 清空仓库时，同时清空库位
      // this.queryLocationName = null
      // this.queryParams.locationId = null
      this.handleQuery()
    },

    /** 打开库位选择器 */
    openLocationSelector() {
      // if (!this.queryParams.warehouseId) {
      //   this.$message.warning("请先选择仓库")
      //   return
      // }
      this.locationSelectorVisible = true
    },

    /** 库位选择回调 */
    handleLocationSelected(location) {
      if (!location) return
      this.queryParams.locationId = location.locationId || location.id
      this.queryLocationName = location.locationName || location.locationCode
      this.handleQuery()
    },

    /** 清空库位选择 */
    clearQueryLocation() {
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/inbound/export', {
        ...this.queryParams
      }, `inbound_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 核心样式保留，冗余样式删除 */
.page-container {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-container {
  margin-top: 16px;
}
</style>
