<template>
  <div class="inventory-summary">
    <!-- 筛选条件 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="110px">
      <!-- 仓库选择 -->
      <el-form-item label="仓库">
        <el-select
          v-model="queryParams.warehouseId"
          placeholder="请选择仓库"
          clearable
          @change="handleWarehouseChange"
          style="width: 180px;"
        >
          <el-option
            v-for="warehouse in warehouseList"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
      </el-form-item>
      
      <!-- 库区选择 -->
      <el-form-item label="库区">
        <el-select
          v-model="queryParams.areaId"
          placeholder="请选择库区"
          clearable
          :disabled="!queryParams.warehouseId"
          style="width: 180px;"
        >
          <el-option
            v-for="area in areaList"
            :key="area.areaId"
            :label="area.areaName"
            :value="area.areaId"
          />
        </el-select>
      </el-form-item>

      <!-- 物资分类选择 -->
      <el-form-item label="物资分类">
        <el-cascader v-model="queryParams.categoryId" :options="categoryOptions"
          :props="{ value: 'categoryId', label: 'categoryName', checkStrictly: true, emitPath: false }"
          placeholder="请选择物资分类" clearable style="width: 200px;" />
      </el-form-item>

      <!-- 物资编码 -->
      <el-form-item label="物资编码">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物资编码" clearable @keyup.enter="handleQuery"
          style="width: 180px;" />
      </el-form-item>

      <!-- 物资名称 -->
      <el-form-item label="物资名称">
        <el-input v-model="queryParams.materialName" placeholder="请输入物资名称" clearable @keyup.enter="handleQuery"
          style="width: 180px;" />
      </el-form-item>

      <!-- 库存数量范围 -->
      <el-form-item label="库存数量范围">
        <el-input-number v-model="queryParams.minQuantity" :min="0" placeholder="最小" style="width: 140px;" clearable />
        <span style="margin: 0 10px;">-</span>
        <el-input-number v-model="queryParams.maxQuantity" :min="0" placeholder="最大" style="width: 140px;" clearable />
      </el-form-item>

      <!-- 是否显示0库存 -->
      <el-form-item label="是否显示0库存">
        <el-select v-model="queryParams.showzerostock" placeholder="请选择" clearable >
          <el-option label="显示" value="true" />
          <el-option label="不显示" value="false" />
        </el-select>
      </el-form-item>

      <!-- 排序方式 -->
      <el-form-item label="排序方式">
        <el-select v-model="queryParams.orderBy" placeholder="请选择" clearable >
          <el-option label="总库存降序" value="totalquantity DESC" />
          <el-option label="总库存升序" value="totalquantity ASC" />
          <el-option label="总金额降序" value="totalAmount DESC" />
          <el-option label="总金额升序" value="totalAmount ASC" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 库存列表 -->
    <el-table ref="inventoryTableRef" :data="inventoryList" row-key="materialId" border style="width: 100%"
      @expand-change="handleExpandChange">
      <!-- 二级展开列 -->
      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.inventoryList" border style="width: 100%" size="small">
            <el-table-column prop="batchNo" label="批次号" width="150" />
            <el-table-column prop="warehouse.warehouseName" label="仓库"  />
            <el-table-column prop="area.areaName" label="库区" />
            <el-table-column prop="location.locationName" label="货架"/>
            <el-table-column label="批次号" align="center" prop="batchNo" width="180" />
            <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="有效日期" align="center" prop="expirationDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库存数量" align="center" prop="quantity" />
            <el-table-column label="可用数量" align="center" prop="availableQuantity" />
            <el-table-column label="锁定数量" align="center" prop="lockedQuantity" />
            <el-table-column label="入库单价" align="center" prop="unitCost" />
            <el-table-column label="总成本" align="center" prop="totalCost" />
            <el-table-column label="库存状态" align="center" prop="inventoryStatus">
              <template #default="scope">
                <dict-tag :options="inventory_status" :value="scope.row.inventoryStatus" />
              </template>
            </el-table-column>
            <el-table-column label="最后入库时间" align="center" prop="lastInboundTime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.lastInboundTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最后出库时间" align="center" prop="lastOutboundTime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.lastOutboundTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="RFID标签" align="center" prop="rfidTagCodes">
              <template #default="scope">
                <span>{{ scope.row.rfidTag || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="RFID绑定数量" align="center" prop="rfidBindingCount" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
              <template #default="scope">
                <el-button link type="primary" icon="Document" @click="handleFlowQuery(scope.row)" v-hasPermi="['ware:wmsInventory:flow']">库存履历</el-button>
                <el-button link type="primary" icon="View" @click="handleLocationVisualization(scope.row)" v-hasPermi="['ware:wmsInventory:visualization']">货架可视化</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <!-- 物资信息列 -->
      <el-table-column prop="materialCode" label="物资编码" width="150" />
      <el-table-column prop="materialName" label="物资名称" width="200" />
      <el-table-column prop="categoryName" label="物资分类" width="200" />
      <el-table-column prop="specification" label="规格型号" width="150" />
      <el-table-column prop="unit" label="计量单位" width="100" />
      <el-table-column prop="totalQuantity" label="总库存" />
      <!-- <el-table-column prop="totalAmount" label="总金额"  /> -->
      <el-table-column prop="locationCount" label="存储货架数"  />
      <el-table-column prop="batchCount" label="批次数量"/>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getInventoryList" />

    <!-- 货架可视化对话框 -->
    <LocationVisualDialog 
      v-model:visible="locationVisualVisible" 
      :inventory-info="currentInventoryInfo" 
      :selected-location="currentLocation" 
      :locations="locations"
    />

    <!-- 库存履历对话框 -->
    <InventoryFlowDialog 
      v-model:visible="inventoryFlowVisible" 
      v-model:inventory-id="selectedInventoryId" 
      title="库存履历"
    />
  </div>
</template>

<script setup name="InventorySummary">
import { ref, reactive, onMounted, watch } from 'vue'
import { listMaterialInventory, getMaterialInventoryDetail } from '@/api/ware/wmsInventory'
import { listWmsMaterialCategory } from '@/api/ware/wmsMaterialCategory'
import { listWmsWarehouse } from '@/api/ware/wmsWarehouse'
import { listWmsArea } from '@/api/ware/wmsArea'
import { ElMessage } from 'element-plus'
import LocationVisualDialog from './components/LocationVisualDialog.vue'
import InventoryFlowDialog from '@/components/InventoryFlowDialog.vue'

const { proxy } = getCurrentInstance()
const { sys_yes_no, inventory_status } = proxy.useDict('sys_yes_no', 'inventory_status')
// 表格引用
const inventoryTableRef = ref(null)
// 查询表单引用
const queryRef = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  warehouseId: null,
  areaId: null,
  categoryId: null,
  materialCode: null,
  materialName: null,
  minQuantity: null,
  maxQuantity: null,
  showzerostock: null,
  orderBy: 'totalquantity DESC'
})

// 物资分类选项
const categoryOptions = ref([])

// 仓库列表
const warehouseList = ref([])
// 库区列表
const areaList = ref([])

// 库存列表数据
const inventoryList = ref([])
// 总条数
const total = ref(0)

// 货架可视化对话框
const locationVisualVisible = ref(false)
const currentInventoryInfo = ref({})
const currentLocation = ref({})
const locations = ref([])

// 库存履历对话框
const inventoryFlowVisible = ref(false)
const selectedInventoryId = ref(null)

// 获取库存列表
const getInventoryList = () => {
  listMaterialInventory(queryParams).then(response => {
    inventoryList.value = response.rows
    total.value = response.total
  }).catch(error => {
    ElMessage.error('获取库存列表失败：' + error.message)
    console.error('获取库存列表失败:', error)
  })
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getInventoryList()
}

// 重置
const resetQuery = () => {
  queryRef.value.resetFields()
  
  // 手动重置其他字段
  queryParams.warehouseId = null
  queryParams.areaId = null
  queryParams.categoryId = null
  queryParams.materialCode = null
  queryParams.materialName = null
  queryParams.minQuantity = null
  queryParams.maxQuantity = null
  queryParams.showzerostock = null
  queryParams.orderBy = 'totalquantity DESC'
  queryParams.pageNum = 1
  
  // 重置库区列表
  areaList.value = []
  
  getInventoryList()
}

// 分页大小变化
const handleSizeChange = (pageSize) => {
  queryParams.pageSize = pageSize
  queryParams.pageNum = 1
  getInventoryList()
}

// 分页当前页变化
const handleCurrentChange = (pageNum) => {
  queryParams.pageNum = pageNum
  getInventoryList()
}

// 展开行变化
const handleExpandChange = (row, expandedRows) => {
  // 找到当前展开的行
  const expandedRow = expandedRows.find(item => item.materialId === row.materialId)
  if (expandedRow) {
    // 准备请求参数
    const params = {
      materialId: expandedRow.materialId,
      warehouseId: queryParams.warehouseId,
      areaId: queryParams.areaId,
      showzerostock: queryParams.showzerostock
    }

    // 调用接口获取详细库存数据
    getMaterialInventoryDetail(params).then(response => {
      // 将获取到的数据赋值给行的inventoryList属性
      expandedRow.inventoryList = response.data;
    }).catch(error => {
      console.error('获取库存详情失败:', error)
      ElMessage.error('获取库存详情失败')
      // 确保有默认的空数组，避免表格报错
      expandedRow.inventoryList = []
    })
  }
}

// 获取物资分类树形结构
const initCategoryTree = () => {
  listWmsMaterialCategory({ pageNum: 1, pageSize: 1000 }).then(response => {
    // 转换为级联选择器需要的格式
    categoryOptions.value = proxy.handleTree(response.data, 'categoryId', 'parentId')
  }).catch(error => {
    console.error('获取物资分类失败:', error)
    ElMessage.error('获取物资分类失败')
  })
}

// 初始化仓库列表
const initWarehouseList = () => {
  listWmsWarehouse({ pageNum: 1, pageSize: 100 }).then(response => {
    warehouseList.value = response.rows
  }).catch(error => {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  })
}

// 获取库区列表
const getAreaList = (warehouseId) => {
  if (!warehouseId) {
    areaList.value = []
    queryParams.areaId = null
    return
  }
  
  listWmsArea({ pageNum: 1, pageSize: 100, warehouseId: warehouseId }).then(response => {
    areaList.value = response.rows
  }).catch(error => {
    console.error('获取库区列表失败:', error)
    ElMessage.error('获取库区列表失败')
  })
}

// 仓库选择变化
const handleWarehouseChange = () => {
  getAreaList(queryParams.warehouseId)
}

// 货架可视化
const handleLocationVisualization = (row) => {
  // 设置当前库存信息
  currentInventoryInfo.value = {
    materialName: row.material.materialName,
    materialCode: row.material.materialCode,
    specification: row.material.specification,
    unit: row.material.unit,
    batchNo: row.batchNo,
    productionDate: row.productionDate,
    expirationDate: row.expirationDate,
    quantity: row.quantity,
    availableQuantity: row.availableQuantity,
    lockedQuantity: row.lockedQuantity,
    unitCost: row.unitCost,
    totalCost: row.totalCost
  }
  
  // 设置当前位置信息
  currentLocation.value = {
    locationId: row.location.locationId,
    locationName: row.location.locationName,
    locationCode: row.location.locationCode
  }
  
  // 获取所有相关位置信息（这里需要根据实际情况调整，可能需要调用API）
  // 暂时使用模拟数据
  locations.value = [
    {
      locationId: row.location.locationId,
      locationName: row.location.locationName,
      locationCode: row.location.locationCode
    }
  ]
  
  // 显示对话框
  locationVisualVisible.value = true
}

// 库存履历
const handleFlowQuery = (row) => {
  // 设置选中的库存ID
  selectedInventoryId.value = row.inventoryId
  
  // 显示对话框
  inventoryFlowVisible.value = true
}

// 初始化
onMounted(() => {
  initWarehouseList()
  initCategoryTree()
  getInventoryList()
})
</script>

<style scoped>
.inventory-summary {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>