<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']"
        >导出</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="''"
        >
          <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>
        <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="物料名称" align="center" prop="materialName" min-width="150" show-overflow-tooltip />
      <el-table-column label="入库次数" align="center" prop="inboundCount" min-width="100" />
      <el-table-column label="出库次数" align="center" prop="outboundCount" min-width="100" />
      <el-table-column label="入库数量" align="center" prop="inboundQuantity" min-width="120">
        <template slot-scope="scope">
          <span
            v-if="Number(scope.row.inboundQuantity || 0) > 0"
            class="link-number"
            @click="openDetailDialog('inbound', scope.row)"
          >
            {{ formatNumber(scope.row.inboundQuantity) }}
          </span>
          <span v-else>
            {{ formatNumber(scope.row.inboundQuantity) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="出库数量" align="center" prop="outboundQuantity" min-width="120">
        <template slot-scope="scope">
          <span
            v-if="Number(scope.row.outboundQuantity || 0) > 0"
            class="link-number"
            @click="openDetailDialog('outbound', scope.row)"
          >
            {{ formatNumber(scope.row.outboundQuantity) }}
          </span>
          <span v-else>
            {{ formatNumber(scope.row.outboundQuantity) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="入库总额" align="center" prop="inboundAmount" min-width="120">
        <template slot-scope="scope">
          {{ formatAmount(scope.row.inboundAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="出库总额" align="center" prop="outboundAmount" min-width="120">
        <template slot-scope="scope">
          {{ formatAmount(scope.row.outboundAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="总额差" align="center" prop="amountDiff" min-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"
      :warehousesId="queryParams.warehouseId"
      @selected="handleLocationSelected"
    />

    <!-- 出入库明细弹窗 -->
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailDialogVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-table
        v-loading="detailLoading"
        :data="detailList"
        border
        style="width: 100%"
        max-height="500"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="物料名称" prop="materialName" align="center" min-width="180" />
        <el-table-column :label="detailType === 'inbound' ? '入库单号' : '出库单号'" prop="orderId" align="center" min-width="100" />
        <el-table-column label="批次号" prop="batchNo" align="center" min-width="100" />
        <el-table-column :label="detailType === 'inbound' ? '入库数量' : '出库数量'" prop="quantity" align="center" min-width="100" />
        <el-table-column label="当前库存数量" v-if="detailType === 'inbound'" prop="inventoryQuantity" align="center" min-width="120" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInboundOutboundStatistics,
  exportInboundOutboundStatistics,
  listInboundDetails,
  listOutboundDetails
} 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,
      // 明细弹窗相关
      detailDialogVisible: false,
      detailLoading: false,
      detailType: '',
      detailTitle: '',
      detailList: []
    }
  },
  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.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()
    },
    /** 打开明细弹窗 */
    openDetailDialog(type, row) {
      this.detailType = type
      this.detailTitle = type === 'inbound'
        ? `入库明细 - ${row.materialName || ''}`
        : `出库明细 - ${row.materialName || ''}`
      this.detailDialogVisible = true
      this.fetchDetailList(row)
    },
    /** 查询明细列表 */
    fetchDetailList(row) {
      this.detailLoading = 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

      // 当前行物料ID
      params.materialId = row.materialId

      const api = this.detailType === 'inbound' ? listInboundDetails : listOutboundDetails

      api(params)
        .then(res => {
          this.detailList = res.rows || []
          this.detailLoading = false
        })
        .catch(() => {
          this.detailLoading = false
        })
    },
    /** 格式化金额，保留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;
}

.link-number {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
}

.link-number:hover {
  color: #66b1ff;
}
</style>

