<template>
  <div class="report-charts">
    <el-row :gutter="20">
      <!-- 库存趋势图 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">库存盘点趋势</span>
              <el-tag type="info" size="small">近30天</el-tag>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 仓库分布饼图 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">仓库库存分布</span>
              <el-tag type="success" size="small">金额占比</el-tag>
            </div>
          </template>
          <div ref="warehousePieRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 盘盈盘亏对比图 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">盘盈盘亏对比</span>
              <el-tag type="warning" size="small">金额统计</el-tag>
            </div>
          </template>
          <div ref="profitLossChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 产品TOP10 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">产品库存TOP10</span>
              <el-tag type="danger" size="small">金额排名</el-tag>
            </div>
          </template>
          <div ref="productTopChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 库存数量统计 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">产品库存数量TOP10</span>
              <el-tag type="primary" size="small">数量排名</el-tag>
            </div>
          </template>
          <div ref="productCountChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 盘点频次分析 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">仓库盘点频次</span>
              <el-tag type="warning" size="small">次数统计</el-tag>
            </div>
          </template>
          <div ref="checkFrequencyChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { StockTrendVO, WarehouseStockVO, ProductStockVO } from '@/api/erp/stock/check'
import { erpPriceInputFormatter } from '@/utils'

interface Props {
  trendData: StockTrendVO[]
  warehouseData: WarehouseStockVO[]
  productData: ProductStockVO[]
}

const props = defineProps<Props>()

const trendChartRef = ref<HTMLDivElement>()
const warehousePieRef = ref<HTMLDivElement>()
const profitLossChartRef = ref<HTMLDivElement>()
const productTopChartRef = ref<HTMLDivElement>()
const productCountChartRef = ref<HTMLDivElement>()
const checkFrequencyChartRef = ref<HTMLDivElement>()

let trendChart: echarts.ECharts | null = null
let warehousePieChart: echarts.ECharts | null = null
let profitLossChart: echarts.ECharts | null = null
let productTopChart: echarts.ECharts | null = null
let productCountChart: echarts.ECharts | null = null
let checkFrequencyChart: echarts.ECharts | null = null

// 初始化趋势图
const initTrendChart = () => {
  if (!trendChartRef.value) return

  trendChart = echarts.init(trendChartRef.value)
  
  const dates = props.trendData.map(item => item.date)
  const checkAmounts = props.trendData.map(item => item.totalAmount)
  const profitAmounts = props.trendData.map(item => item.profitAmount)
  const lossAmounts = props.trendData.map(item => item.lossAmount)

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['盘点金额', '盘盈金额', '盘亏金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => erpPriceInputFormatter(value)
      }
    },
    series: [
      {
        name: '盘点金额',
        type: 'line',
        data: checkAmounts,
        smooth: true,
        itemStyle: { color: '#409eff' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
          ])
        }
      },
      {
        name: '盘盈金额',
        type: 'line',
        data: profitAmounts,
        smooth: true,
        itemStyle: { color: '#67c23a' }
      },
      {
        name: '盘亏金额',
        type: 'line',
        data: lossAmounts,
        smooth: true,
        itemStyle: { color: '#f56c6c' }
      }
    ]
  }

  trendChart.setOption(option)
}

// 初始化仓库分布饼图
const initWarehousePieChart = () => {
  if (!warehousePieRef.value) return

  warehousePieChart = echarts.init(warehousePieRef.value)

  const data = props.warehouseData.map(item => ({
    name: item.warehouseName,
    value: item.totalAmount
  }))

  const option: EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '库存金额',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }

  warehousePieChart.setOption(option)
}

// 初始化盘盈盘亏对比图
const initProfitLossChart = () => {
  if (!profitLossChartRef.value) return

  profitLossChart = echarts.init(profitLossChartRef.value)

  const warehouses = props.warehouseData.map(item => item.warehouseName)
  const profitData = props.warehouseData.map(item => item.profitAmount)
  const lossData = props.warehouseData.map(item => -item.lossAmount) // 负数显示

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['盘盈', '盘亏']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => erpPriceInputFormatter(Math.abs(value))
      }
    },
    yAxis: {
      type: 'category',
      data: warehouses
    },
    series: [
      {
        name: '盘盈',
        type: 'bar',
        stack: 'total',
        itemStyle: { color: '#67c23a' },
        data: profitData
      },
      {
        name: '盘亏',
        type: 'bar',
        stack: 'total',
        itemStyle: { color: '#f56c6c' },
        data: lossData
      }
    ]
  }

  profitLossChart.setOption(option)
}

// 初始化产品TOP10图
const initProductTopChart = () => {
  if (!productTopChartRef.value) return

  productTopChart = echarts.init(productTopChartRef.value)

  // 取前10名
  const topProducts = [...props.productData]
    .sort((a, b) => b.totalAmount - a.totalAmount)
    .slice(0, 10)

  const products = topProducts.map(item => item.productName)
  const amounts = topProducts.map(item => item.totalAmount)

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: products,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => erpPriceInputFormatter(value)
      }
    },
    series: [
      {
        name: '库存金额',
        type: 'bar',
        data: amounts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409eff' },
            { offset: 1, color: '#67c23a' }
          ])
        },
        barWidth: '60%'
      }
    ]
  }

  productTopChart.setOption(option)
}

// 初始化产品库存数量图
const initProductCountChart = () => {
  if (!productCountChartRef.value) return

  productCountChart = echarts.init(productCountChartRef.value)

  // 取前10名
  const topProducts = [...props.productData]
    .sort((a, b) => b.totalCount - a.totalCount)
    .slice(0, 10)

  const products = topProducts.map(item => item.productName)
  const counts = topProducts.map(item => item.totalCount)
  const profitCounts = topProducts.map(item => item.profitCount)
  const lossCounts = topProducts.map(item => item.lossCount)

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['库存数量', '盘盈数量', '盘亏数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: products,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '库存数量',
        type: 'bar',
        data: counts,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '盘盈数量',
        type: 'bar',
        data: profitCounts,
        itemStyle: { color: '#67c23a' }
      },
      {
        name: '盘亏数量',
        type: 'bar',
        data: lossCounts,
        itemStyle: { color: '#f56c6c' }
      }
    ]
  }

  productCountChart.setOption(option)
}

// 初始化盘点频次图
const initCheckFrequencyChart = () => {
  if (!checkFrequencyChartRef.value) return

  checkFrequencyChart = echarts.init(checkFrequencyChartRef.value)

  const warehouses = props.warehouseData.map(item => item.warehouseName)
  const checkCounts = props.warehouseData.map(item => item.checkCount)
  const productCounts = props.warehouseData.map(item => item.productCount)

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['盘点次数', '产品数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: warehouses,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '盘点次数',
        position: 'left'
      },
      {
        type: 'value',
        name: '产品数量',
        position: 'right'
      }
    ],
    series: [
      {
        name: '盘点次数',
        type: 'bar',
        data: checkCounts,
        itemStyle: { color: '#e6a23c' },
        yAxisIndex: 0
      },
      {
        name: '产品数量',
        type: 'line',
        data: productCounts,
        itemStyle: { color: '#909399' },
        yAxisIndex: 1,
        smooth: true
      }
    ]
  }

  checkFrequencyChart.setOption(option)
}

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    initTrendChart()
    initWarehousePieChart()
    initProfitLossChart()
    initProductTopChart()
    initProductCountChart()
    initCheckFrequencyChart()
  })
}

// 响应式调整
const handleResize = () => {
  trendChart?.resize()
  warehousePieChart?.resize()
  profitLossChart?.resize()
  productTopChart?.resize()
  productCountChart?.resize()
  checkFrequencyChart?.resize()
}

// 监听数据变化
watch(
  () => [props.trendData, props.warehouseData, props.productData],
  () => {
    initCharts()
  },
  { deep: true }
)

onMounted(() => {
  initCharts()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  warehousePieChart?.dispose()
  profitLossChart?.dispose()
  productTopChart?.dispose()
  productCountChart?.dispose()
  checkFrequencyChart?.dispose()
})

defineExpose({
  initCharts
})
</script>

<style scoped lang="scss">
.report-charts {
  .chart-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }

    .chart-container {
      width: 100%;
      height: 350px;
    }
  }
}
</style>
