<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:inventory:export']"
        >导出Excel</el-button>
      </template>
    </PageTitle>

    <!-- 页面容器 -->
    <div class="page-container">
      <!-- 查询表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="仓库" prop="warehousesCode">
        <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="''"
          :disabled="!queryParams.warehouseId"
        >
          <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="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入物料ID或编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货主" prop="ownerId">
        <el-input
          v-model="queryOwnerName"
          placeholder="请选择货主"
          readonly
          @focus="openOwnerSelector"
          :suffix-icon="''"
        >
          <template v-if="queryOwnerName" #suffix>
            <i
              class="el-icon-circle-close el-input__icon"
              style="cursor: pointer;"
              @click.stop="clearQueryOwner"
            ></i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="库存类别" prop="inventoryType">
        <el-select v-model="queryParams.inventoryType" placeholder="请选择库存类别" clearable>
          <el-option
            v-for="item in inventoryTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </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="alertType">
        <el-select v-model="queryParams.alertType" placeholder="请选择预警类型" clearable>
          <el-option
            v-for="item in alertTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库存状态" prop="inventoryStatus">
        <el-select v-model="queryParams.inventoryStatus" placeholder="请选择库存状态" clearable>
          <el-option
            v-for="item in inventoryStatusOptions"
            :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>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table v-loading="loading" :data="inventoryList" border height="100%">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="库存编号" align="center" prop="id" width="150" />
      <el-table-column label="库存类别" align="center" prop="inventoryType" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.inventoryType === 1 ? 'primary' : 'warning'" size="small">
            {{ getInventoryTypeName(scope.row.inventoryType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="入库单号" align="center" prop="orderId" width="150" />
      <el-table-column label="物料ID" align="center" prop="materialId" width="150" />
      <el-table-column label="批次ID" align="center" prop="batchId" width="120" />
      <el-table-column label="仓库编码" align="center" prop="warehousesCode" width="120" />
      <el-table-column label="库位ID" align="center" prop="locationId" width="120" />
      <el-table-column label="货主ID" align="center" prop="ownerId" width="120" />
      <el-table-column label="库存数量" align="center" prop="quantity" width="100" />
      <el-table-column label="锁定数量" align="center" prop="lockedQuantity" width="100" />
      <el-table-column label="可用数量" align="center" width="100">
        <template slot-scope="scope">
          {{ (scope.row.quantity || 0) - (scope.row.lockedQuantity || 0) }}
        </template>
      </el-table-column>
      <el-table-column label="单位重量" align="center" prop="unitWeight" width="100">
        <template slot-scope="scope">
          {{ formatWeight(scope.row.unitWeight) }}
        </template>
      </el-table-column>
      <el-table-column label="总重量" align="center" prop="totalWeight" width="100">
        <template slot-scope="scope">
          {{ formatWeight(scope.row.totalWeight) }}
        </template>
      </el-table-column>
      <el-table-column label="总体积" align="center" prop="totalVolume" width="100">
        <template slot-scope="scope">
          {{ formatVolume(scope.row.totalVolume) }}
        </template>
      </el-table-column>
      <el-table-column label="生产日期" align="center" prop="productionDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效日期" align="center" prop="expirationDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存状态" align="center" prop="inventoryStatus" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.inventoryStatus)"
            size="small"
          >
            {{ getStatusName(scope.row.inventoryStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后入库时间" align="center" prop="lastInboundTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastInboundTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后出库时间" align="center" prop="lastOutboundTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastOutboundTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
          >明细</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>

    <!-- 货主选择组件 -->
    <OwnerSelector
      v-model="ownerSelectorVisible"
      @selected="handleOwnerSelected"
    />
    <!-- 仓库选择组件 -->
    <WarehouseSelector
      v-model="warehouseSelectorVisible"
      @selected="handleWarehouseSelected"
    />
    <!-- 库位选择组件 -->
    <LocationSelector
      v-model="locationSelectorVisible"
      :warehousesId="queryParams.warehouseId"
      @selected="handleLocationSelected"
    />

    <!-- 物料明细弹窗 -->
    <el-dialog
      title="物料库存明细"
      :visible.sync="detailDialogVisible"
      width="1400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-table
        v-loading="detailLoading"
        :data="detailList"
        border
        style="width: 100%"
        max-height="600"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="库存编号" align="center" prop="id" width="150" />
        <el-table-column label="库存类别" align="center" prop="inventoryType" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.inventoryType === 1 ? 'primary' : 'warning'" size="small">
              {{ getInventoryTypeName(scope.row.inventoryType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入库单号" align="center" prop="orderId" width="150" />
        <el-table-column label="物料ID" align="center" prop="materialId" width="150" />
        <el-table-column label="批次ID" align="center" prop="batchId" width="120" />
        <el-table-column label="仓库编码" align="center" prop="warehousesCode" width="120" />
        <el-table-column label="库位ID" align="center" prop="locationId" width="120" />
        <el-table-column label="货主ID" align="center" prop="ownerId" width="120" />
        <el-table-column label="库存数量" align="center" prop="quantity" width="100" />
        <el-table-column label="锁定数量" align="center" prop="lockedQuantity" width="100" />
        <el-table-column label="可用数量" align="center" width="100">
          <template slot-scope="scope">
            {{ (scope.row.quantity || 0) - (scope.row.lockedQuantity || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="单位重量" align="center" prop="unitWeight" width="100">
          <template slot-scope="scope">
            {{ formatWeight(scope.row.unitWeight) }}
          </template>
        </el-table-column>
        <el-table-column label="总重量" align="center" prop="totalWeight" width="100">
          <template slot-scope="scope">
            {{ formatWeight(scope.row.totalWeight) }}
          </template>
        </el-table-column>
        <el-table-column label="总体积" align="center" prop="totalVolume" width="100">
          <template slot-scope="scope">
            {{ formatVolume(scope.row.totalVolume) }}
          </template>
        </el-table-column>
        <el-table-column label="生产日期" align="center" prop="productionDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="失效日期" align="center" prop="expirationDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存状态" align="center" prop="inventoryStatus" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.inventoryStatus)"
              size="small"
            >
              {{ getStatusName(scope.row.inventoryStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后入库时间" align="center" prop="lastInboundTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastInboundTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后出库时间" align="center" prop="lastOutboundTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastOutboundTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人代码" align="center" prop="createUserCode" width="120" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人代码" align="center" prop="updateUserCode" width="120" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventory, exportInventory } from "@/api/inventory/inventory"
import RightToolbar from "@/components/RightToolbar"
import PageTitle from "@/components/PageTitle"
import OwnerSelector from "@/views/compononents/OwnerSelector.vue"
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"

export default {
  name: "InventoryDetail",
  components: {
    RightToolbar,
    PageTitle,
    OwnerSelector,
    WarehouseSelector,
    LocationSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存明细表格数据
      inventoryList: [],
      // 库存类别选项（1普通2退库）
      inventoryTypeOptions: [
        { value: 1, label: '普通' },
        { value: 2, label: '退库' }
      ],
      // 预警类型选项
      alertTypeOptions: [
        { value: 'all', label: '全部预警' },
        { value: 'over', label: '超量预警' },
        { value: 'under', label: '不足预警' }
      ],
      // 库存状态选项（0-已出库 1-正常）
      inventoryStatusOptions: [
        { value: 0, label: '已出库' },
        { value: 1, label: '正常' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        warehousesCode: null,
        locationId: null,
        materialId: null,
        ownerId: null,
        inventoryType: null,
        batchId: null,
        alertType: null,
        inventoryStatus: null
      },
      // 货主选择相关
      ownerSelectorVisible: false,
      queryOwnerName: null,
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null,
      // 明细弹窗相关
      detailDialogVisible: false,
      detailLoading: false,
      detailList: [],
      currentDetailRow: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询库存明细列表 */
    getList() {
      this.loading = true
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryOwnerName = null
      this.queryWarehouseName = null
      this.queryLocationName = null
      this.queryParams.ownerId = null
      this.queryParams.warehouseId = null
      this.queryParams.warehousesCode = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 打开货主选择器 */
    openOwnerSelector() {
      this.ownerSelectorVisible = true
    },
    /** 货主选择回调 */
    handleOwnerSelected(owner) {
      if (!owner) return
      this.queryParams.ownerId = owner.ownerId || owner.ownerCode
      this.queryOwnerName = owner.ownerName || owner.ownerCode
      this.handleQuery()
    },
    /** 清空货主选择 */
    clearQueryOwner() {
      this.queryOwnerName = null
      this.queryParams.ownerId = null
      this.handleQuery()
    },
    /** 打开仓库选择器 */
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true
    },
    /** 仓库选择回调 */
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      this.queryParams.warehouseId = warehouse.warehouseId || warehouse.id
      this.queryParams.warehousesCode = warehouse.warehousesCode
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehousesCode
      // 仓库选择后，清空库位信息
      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()
    },
    /** 清空仓库选择 */
    clearQueryWarehouse() {
      this.queryWarehouseName = null
      this.queryParams.warehouseId = null
      this.queryParams.warehousesCode = null
      // 清空仓库时，同时清空库位
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 清空库位选择 */
    clearQueryLocation() {
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 获取库存类别名称 */
    getInventoryTypeName(type) {
      const item = this.inventoryTypeOptions.find(item => item.value === type)
      return item ? item.label : '未知'
    },
    /** 获取状态样式类型 */
    getStatusType(status) {
      const item = this.inventoryStatusOptions.find(item => item.value === status)
      return item ? (status === 1 ? 'success' : 'info') : 'info'
    },
    /** 获取状态名称 */
    getStatusName(status) {
      const item = this.inventoryStatusOptions.find(item => item.value === status)
      return item ? item.label : '未知'
    },
    /** 格式化重量 */
    formatWeight(weight) {
      if (weight === null || weight === undefined || isNaN(weight)) {
        return '-'
      }
      return parseFloat(weight).toFixed(2)
    },
    /** 格式化体积 */
    formatVolume(volume) {
      if (volume === null || volume === undefined || isNaN(volume)) {
        return '-'
      }
      return parseFloat(volume).toFixed(2)
    },
    /** 查看明细 */
    handleViewDetail(row) {
      this.currentDetailRow = row
      this.detailDialogVisible = true
      this.getDetailList(row)
    },
    /** 查询物料明细列表 */
    getDetailList(row) {
      this.detailLoading = true
      // 根据当前行的物料ID、仓库、库位、货主等信息查询明细
      const params = {
        materialId: row.materialId,
        warehousesCode: row.warehousesCode,
        locationId: row.locationId,
        ownerId: row.ownerId,
        batchId: row.batchId,
        inventoryType: row.inventoryType,
        inventoryStatus: row.inventoryStatus,
        pageNum: 1,
        pageSize: 10000 // 设置一个很大的值，不分页
      }
      
      listInventory(params).then(response => {
        this.detailList = response.rows || []
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    /** 导出库存明细数据 */
    handleExport() {
      const params = { ...this.queryParams }
      delete params.pageNum
      delete params.pageSize
      
      this.download('inventory/inventory/export', {
        ...params
      }, `库存明细数据_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 页面容器样式 */
.page-container {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 140px);
  min-height: 600px;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  min-height: 0;
  margin-top: 16px;
  display: flex;
  flex-direction: column;
}

.mb8 {
  margin-bottom: 8px;
}
</style>

