<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:statistics: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="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </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="''"
          :disabled="!queryParams.warehousesCode"
        >
          <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>
        <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="statisticsList" border height="100%">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="物料ID" align="center" prop="materialId" width="150" />
      <el-table-column label="物料名称" align="center" prop="materialName" min-width="150" show-overflow-tooltip />
      <el-table-column label="入库次数" align="center" prop="inboundCount" width="100" />
      <el-table-column label="出库次数" align="center" prop="outboundCount" width="100" />
      <el-table-column label="入库数量" align="center" prop="inboundQuantity" width="120">
        <template slot-scope="scope">
          {{ formatNumber(scope.row.inboundQuantity) }}
        </template>
      </el-table-column>
      <el-table-column label="出库数量" align="center" prop="outboundQuantity" width="120">
        <template slot-scope="scope">
          {{ formatNumber(scope.row.outboundQuantity) }}
        </template>
      </el-table-column>
      <el-table-column label="入库总额" align="center" prop="inboundAmount" width="120">
        <template slot-scope="scope">
          {{ formatAmount(scope.row.inboundAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="出库总额" align="center" prop="outboundAmount" width="120">
        <template slot-scope="scope">
          {{ formatAmount(scope.row.outboundAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="总额差" align="center" prop="amountDiff" width="120">
        <template slot-scope="scope">
          <span :style="{ color: (scope.row.amountDiff || 0) >= 0 ? '#67C23A' : '#F56C6C' }">
            {{ formatAmount(scope.row.amountDiff || ((scope.row.inboundAmount || 0) - (scope.row.outboundAmount || 0))) }}
          </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"
      />
    </div>

    <!-- 仓库选择组件 -->
    <WarehouseSelector
      v-model="warehouseSelectorVisible"
      @selected="handleWarehouseSelected"
    />
    <!-- 库位选择组件 -->
    <LocationSelector
      v-model="locationSelectorVisible"
      :warehouses-code="queryParams.warehousesCode"
      @selected="handleLocationSelected"
    />
  </div>
</template>

<script>
import { listInboundOutboundStatistics, exportInboundOutboundStatistics } from "@/api/inventory/inventory_statistics"
import RightToolbar from "@/components/RightToolbar"
import PageTitle from "@/components/PageTitle"
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"

export default {
  name: "InboundOutboundStatistics",
  components: {
    RightToolbar,
    PageTitle,
    WarehouseSelector,
    LocationSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计数据列表
      statisticsList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startDate: null,
        endDate: null,
        warehouseId: null,
        warehousesCode: null,
        locationId: null,
        materialId: null,
        dateRange: null
      },
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询出入库统计列表 */
    getList() {
      this.loading = true
      // 处理日期范围
      const params = { ...this.queryParams }
      if (params.dateRange && params.dateRange.length === 2) {
        params.startDate = params.dateRange[0]
        params.endDate = params.dateRange[1]
      }
      delete params.dateRange
      
      listInboundOutboundStatistics(params).then(response => {
        this.statisticsList = 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.queryWarehouseName = null
      this.queryLocationName = null
      this.queryParams.dateRange = null
      this.queryParams.warehouseId = null
      this.queryParams.warehousesCode = null
      this.queryParams.locationId = 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()
    },
    /** 清空仓库选择 */
    clearQueryWarehouse() {
      this.queryWarehouseName = null
      this.queryParams.warehouseId = null
      this.queryParams.warehousesCode = null
      // 清空仓库时，同时清空库位
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 打开库位选择器 */
    openLocationSelector() {
      if (!this.queryParams.warehousesCode) {
        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()
    },
    /** 格式化金额，保留2位小数 */
    formatAmount(amount) {
      if (amount === null || amount === undefined || isNaN(amount)) {
        return '0.00'
      }
      return parseFloat(amount).toFixed(2)
    },
    /** 格式化数量 */
    formatNumber(num) {
      if (num === null || num === undefined || isNaN(num)) {
        return '0'
      }
      return parseFloat(num).toString()
    },
    /** 导出统计数据 */
    handleExport() {
      const params = { ...this.queryParams }
      if (params.dateRange && params.dateRange.length === 2) {
        params.startDate = params.dateRange[0]
        params.endDate = params.dateRange[1]
      }
      delete params.dateRange
      delete params.pageNum
      delete params.pageSize
      
      this.download('inventory/statistics/inboundOutbound/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>

