<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <!-- <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="medium"
          @click="handleImport"
          v-hasPermi="['inventory:inventory:import']"
        >导入</el-button> -->
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:inventory:export']"
        >导出</el-button>
        <!-- <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="medium"
          v-print="handlePrint"
        >打印</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="warehousesId">
        <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="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入物料名称"
          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" id="print" :data="inventoryList" border height="100%">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="物料名称" align="center" prop="materialName" min-width="150" />
      <el-table-column label="SAP物料号" align="center" prop="sapNo" min-width="120" />
      <el-table-column label="TS Code" align="center" prop="tsCode" min-width="120" />
      <el-table-column label="危险类别" align="center" prop="hazardId" min-width="120" >
         <template slot-scope="scope">
                  <el-tag
                    :type="getDictListClass('danger_type',scope.row.hazardId)"
                    size="small">
                    {{ getDictLabel('danger_type',scope.row.hazardId) }}
                  </el-tag>
                </template>
      </el-table-column>
      <el-table-column label="规格型号" align="center" prop="specification" min-width="120" />
      <el-table-column label="计量单位" align="center" prop="materialUnit" min-width="120" />
      <el-table-column label="单位重量" align="center" prop="unitWeight" min-width="120" >
        <template slot-scope="scope">
          {{ formatAmount(scope.row.unitWeight || 0) }}
        </template>
      </el-table-column>
      <el-table-column label="库存数量" align="center" prop="totalQuantity" min-width="100" />
      <el-table-column label="锁定数量" align="center" prop="totalLockedQuantity" min-width="100" />
      <el-table-column label="可用数量" align="center" min-width="100">
        <template slot-scope="scope">
          {{ (scope.row.totalQuantity || 0) - (scope.row.totalLockedQuantity || 0) }}
        </template>
      </el-table-column>
      <el-table-column label="最低库存" align="center" prop="minStockLevel" min-width="100" />
      <el-table-column label="最高库存" align="center" prop="maxStockLevel" min-width="100" />
      <el-table-column label="预警状态" align="center" prop="alterType" min-width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getWarnStatusType(scope.row.alterType)"
            size="small"
          >
            {{ getWarnStatusName(scope.row.alterType) }}
          </el-tag>
        </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"
    />
    <ImportExcel
      ref="import"
      title="库存导入"
      import-url="/inventory/inventory/import"
      template-url="inventory/inventory/export"
      template-name="inventory_importTemplate"
      @success="getList"
    />

    <!-- 物料明细弹窗 -->
    <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="materialName" min-width="150" />
        <el-table-column label="SAP物料号" align="center" prop="sapNo" min-width="120" />
        <el-table-column label="TS Code" align="center" prop="tsCode" min-width="120" />
        <el-table-column label="危险类别" align="center" prop="hazardId" min-width="120" >
           <template slot-scope="scope">
                  <el-tag
                    :type="getDictListClass('danger_type',scope.row.hazardId)"
                    size="small">
                    {{ getDictLabel('danger_type',scope.row.hazardId) }}
                  </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="规格型号" align="center" prop="specification" width="120" /> -->
        <!-- <el-table-column label="入库单号" align="center" prop="orderId" width="150" /> -->
        <el-table-column label="批次" align="center" prop="batchId" min-width="120" />
        <el-table-column label="仓库" align="center" prop="warehousesName" min-width="120" />
        <el-table-column label="库位" align="center" prop="locationName" min-width="120" />
        <el-table-column label="货主" align="center" prop="ownerName" min-width="120" />
        <el-table-column label="库存数量" align="center" prop="quantity" min-width="100" />
        <el-table-column label="锁定数量" align="center" prop="lockedQuantity" min-width="100" />
        <el-table-column label="可用数量" align="center" min-width="100">
          <template slot-scope="scope">
            {{ (scope.row.quantity || 0) - (scope.row.lockedQuantity || 0) }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventoryCount, listInventoryDetail, 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"
import ImportExcel from "@/components/ImportExcel"

export default {
  name: "InventoryDetail",
  dicts: ['danger_type'],
  components: {
    RightToolbar,
    PageTitle,
    OwnerSelector,
    WarehouseSelector,
    LocationSelector,
    ImportExcel
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存明细表格数据
      inventoryList: [],
      // 库存类别选项（1普通2退库）
      inventoryTypeOptions: [
        { value: 1, label: '普通' },
        { value: 2, label: '退库' }
      ],
      // 预警类型选项
      alertTypeOptions: [
        { value: '0', label: '全部预警' },
        { value: '1', label: '超量预警' },
        { value: '2', 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,
      handlePrint: {
          id: 'print',
          // extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>,打印表格数据<style>#print {width: 100%;}<style>',
          popTitle: "页眉部分",
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    //从表格中的值当作键获取字典lebel
    getDictLabel(dictType, value){
      if(!value || !this.dict?.type?.[dictType]) return '-'
      const dictItem = this.dict.type[dictType].find(item => item.value === value)
      return dictItem?.label || '-'
    },
    //从表格中的值当作键获取字典listClass
    getDictListClass(dictType, value){
      if(!value || !this.dict?.type?.[dictType]) return '-'
      const dictItem = this.dict.type[dictType].find(item => item.value === value)
      return dictItem?.label || '-'
    },

    /** 查询库存明细列表 */
    getList() {
      this.loading = true
      listInventoryCount(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 : '未知'
    },
    /** 获取预警样式类型 */
    getWarnStatusType(status) {
      const item = this.alertTypeOptions.find(item => item.value === status)
      return item ? (status === 3 ? 'info' : 'warning') : 'info'
    },
    /** 获取预警状态名称 */
    getWarnStatusName(status) {
      const item = this.alertTypeOptions.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)
    },
    /** 格式化金额，保留2位小数 */
    formatAmount(amount) {
      if (amount === null || amount === undefined || isNaN(amount)) {
        return '0'
      }
      return parseFloat(amount).toFixed(2)
    },
    /** 查看明细 */
    handleViewDetail(row) {
      this.currentDetailRow = row
      this.detailDialogVisible = true
      this.getDetailList(row)
    },
    /** 查询物料明细列表 */
    getDetailList(row) {
      this.detailLoading = true
      // 根据当前行的物料ID、仓库、库位、货主等信息查询明细
      const params = {
        materialId: row.materialId,
        warehousesId: this.queryParams.warehousesId,
        locationId: this.queryParams.locationId,
        ownerId: this.queryParams.ownerId,
        batchId: this.queryParams.batchId,
        inventoryType: this.queryParams.inventoryType,
        inventoryStatus: this.queryParams.inventoryStatus,
        pageNum: 1,
        pageSize: 10000 // 设置一个很大的值，不分页
      }

      listInventoryDetail(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/exportExcel', {
        ...params
      }, `库存明细数据_${new Date().getTime()}.xlsx`)
    },
    /** 导入库存数据 */
    handleImport() {
      this.$refs.import && this.$refs.import.show()
    },

  }
}
</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;
}

/* 打印样式 */
@media print {
  @page{
    size:  auto;
    margin: 8mm 6mm;
  }
  html {
    /*打印缩放，防止显示不全*/
    zoom: 90%;
  }
  #print table {
    table-layout: auto !important;
  }
  #print .el-table__header-wrapper .el-table__header {
    width: 100% !important;
  }
  #print .el-table__body-wrapper .el-table__body {
    width: 100% !important;
  }
  .el-table--border .el-table__cell, .el-table__body-wrapper td {
    border: solid 1px #f2f2f2;
  }
  td.el-table__cell{
    border: solid 1px #f2f2f2;
  }
}

</style>

