<template>
  <Dialog
    title="库存盘点报告"
    v-model="dialogVisible"
    width="1400px"
    :close-on-click-modal="false"
  >
    <div v-loading="loading" class="report-container">
      <!-- 筛选条件 -->
      <el-card shadow="never" class="filter-card">
        <el-form :model="queryParams" :inline="true" label-width="80px">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select
              v-model="queryParams.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              class="!w-200px"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="queryParams.productId"
              clearable
              filterable
              placeholder="请选择产品"
              class="!w-200px"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="盘点时间" prop="checkTime">
            <el-date-picker
              v-model="queryParams.checkTime"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-280px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-150px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_AUDIT_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" /> 查询
            </el-button>
            <el-button @click="handleReset">
              <Icon icon="ep:refresh" class="mr-5px" /> 重置
            </el-button>
            <el-button type="success" @click="handleExport" :loading="exportLoading">
              <Icon icon="ep:download" class="mr-5px" /> 导出报告
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 统计卡片 -->
      <ReportSummaryCard :summary="summaryData" />

      <!-- 图表展示 -->
      <ReportCharts
        ref="chartsRef"
        :trend-data="trendData"
        :warehouse-data="warehouseData"
        :product-data="productData"
      />

      <!-- 明细表格 -->
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="card-header">
            <span class="title">仓库库存明细</span>
          </div>
        </template>
        <el-table :data="warehouseData" stripe border>
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="warehouseName" label="仓库名称" min-width="150" />
          <el-table-column
            prop="checkCount"
            label="盘点次数"
            width="100"
            align="center"
          />
          <el-table-column
            prop="productCount"
            label="产品数量"
            width="100"
            align="center"
          />
          <el-table-column
            prop="totalAmount"
            label="库存金额"
            width="120"
            align="right"
            :formatter="erpPriceTableColumnFormatter"
          />
          <el-table-column
            prop="profitAmount"
            label="盘盈金额"
            width="120"
            align="right"
            :formatter="erpPriceTableColumnFormatter"
          >
            <template #default="scope">
              <span style="color: #67c23a">
                {{ erpPriceTableColumnFormatter(scope.row, scope.column, scope.row.profitAmount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="lossAmount"
            label="盘亏金额"
            width="120"
            align="right"
            :formatter="erpPriceTableColumnFormatter"
          >
            <template #default="scope">
              <span style="color: #f56c6c">
                {{ erpPriceTableColumnFormatter(scope.row, scope.column, scope.row.lossAmount) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="card-header">
            <span class="title">产品库存明细</span>
          </div>
        </template>
        <el-table :data="productData" stripe border max-height="400">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="productName" label="产品名称" min-width="200" />
          <el-table-column
            prop="checkCount"
            label="盘点次数"
            width="100"
            align="center"
          />
          <el-table-column
            prop="totalCount"
            label="库存数量"
            width="100"
            align="center"
            :formatter="erpCountTableColumnFormatter"
          />
          <el-table-column
            prop="totalAmount"
            label="库存金额"
            width="120"
            align="right"
            :formatter="erpPriceTableColumnFormatter"
          />
          <el-table-column
            prop="profitCount"
            label="盘盈数量"
            width="100"
            align="center"
            :formatter="erpCountTableColumnFormatter"
          >
            <template #default="scope">
              <span style="color: #67c23a">
                {{ erpCountTableColumnFormatter(scope.row, scope.column, scope.row.profitCount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="lossCount"
            label="盘亏数量"
            width="100"
            align="center"
            :formatter="erpCountTableColumnFormatter"
          >
            <template #default="scope">
              <span style="color: #f56c6c">
                {{ erpCountTableColumnFormatter(scope.row, scope.column, scope.row.lossCount) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import {
  StockCheckApi,
  StockReportQueryVO,
  StockReportSummaryVO,
  WarehouseStockVO,
  ProductStockVO,
  StockTrendVO
} from '@/api/erp/stock/check'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { erpPriceTableColumnFormatter, erpCountTableColumnFormatter } from '@/utils'
import ReportSummaryCard from './components/ReportSummaryCard.vue'
import ReportCharts from './components/ReportCharts.vue'

/** 库存报告对话框 */
defineOptions({ name: 'StockReportDialog' })

const message = useMessage()
const dialogVisible = ref(false)
const loading = ref(false)
const exportLoading = ref(false)
const chartsRef = ref()

// 查询参数
const queryParams = reactive<StockReportQueryVO>({
  warehouseId: undefined,
  productId: undefined,
  checkTime: [],
  status: undefined
})

// 下拉列表数据
const warehouseList = ref<WarehouseVO[]>([])
const productList = ref<ProductVO[]>([])

// 报告数据
const summaryData = ref<StockReportSummaryVO>({
  totalCheckCount: 0,
  totalCheckAmount: 0,
  totalProfitAmount: 0,
  totalLossAmount: 0,
  warehouseCount: 0,
  productCount: 0,
  avgCheckAmount: 0,
  checkAccuracyRate: 0
})
const warehouseData = ref<WarehouseStockVO[]>([])
const productData = ref<ProductStockVO[]>([])
const trendData = ref<StockTrendVO[]>([])

/** 打开对话框 */
const open = async () => {
  dialogVisible.value = true
  // 设置默认时间为最近30天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  queryParams.checkTime = [
    startDate.toISOString().split('T')[0] + ' 00:00:00',
    endDate.toISOString().split('T')[0] + ' 23:59:59'
  ]
  await loadData()
  await getReportData()
}

/** 加载下拉列表数据 */
const loadData = async () => {
  try {
    warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
    productList.value = await ProductApi.getProductSimpleList()
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

/** 获取报告数据 */
const getReportData = async () => {
  loading.value = true
  try {
    // 并行请求所有数据
    const [summary, warehouse, product, trend] = await Promise.all([
      StockCheckApi.getStockReportSummary(queryParams),
      StockCheckApi.getWarehouseStockList(queryParams),
      StockCheckApi.getProductStockList(queryParams),
      StockCheckApi.getStockTrend(queryParams)
    ])

    summaryData.value = summary
    warehouseData.value = warehouse
    productData.value = product
    trendData.value = trend

    // 刷新图表
    nextTick(() => {
      chartsRef.value?.initCharts()
    })
  } catch (error) {
    console.error('获取报告数据失败:', error)
    message.error('获取报告数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/** 查询按钮操作 */
const handleQuery = () => {
  getReportData()
}

/** 重置按钮操作 */
const handleReset = () => {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  queryParams.warehouseId = undefined
  queryParams.productId = undefined
  queryParams.status = undefined
  queryParams.checkTime = [
    startDate.toISOString().split('T')[0] + ' 00:00:00',
    endDate.toISOString().split('T')[0] + ' 23:59:59'
  ]
  getReportData()
}

/** 导出报告 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await StockCheckApi.exportStockReport(queryParams)
    download.excel(data, '库存盘点报告.xls')
  } catch (error) {
    console.error('导出失败:', error)
  } finally {
    exportLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.report-container {
  .filter-card {
    margin-bottom: 20px;
    background-color: #f5f7fa;
  }

  .table-card {
    margin-bottom: 20px;

    .card-header {
      .title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}
</style>
