<template>
  <div class="chart-analysis-wrapper">
    <!-- 第一行：统计标签 -->
    <div class="header-container">
      <div class="title-wrapper">
        <div class="title-bar"></div>
        <h3 class="title-text">数据概览</h3>
      </div>
    </div>
    <Row class="statistics-bar">
      <Col span="8">
        <div class="statistics-item leave-count">
          <div class="stat-icon">
            <Icon type="ios-calendar-outline" size="32" />
          </div>
          <div class="stat-content">
            <div class="stat-title">请假申请次数</div>
            <div class="stat-number">{{ summaryData.leaveCount }}</div>
            <div class="stat-unit">次</div>
          </div>
        </div>
      </Col>
      <Col span="8">
        <div class="statistics-item borrow-count">
          <div class="stat-icon">
            <Icon type="ios-paper-outline" size="32" />
          </div>
          <div class="stat-content">
            <div class="stat-title">办公用品申领次数</div>
            <div class="stat-number">{{ summaryData.borrowCount }}</div>
            <div class="stat-unit">次</div>
          </div>
        </div>
      </Col>
      <Col span="8">
        <div class="statistics-item inbound-count">
          <div class="stat-icon">
            <Icon type="ios-archive-outline" size="32" />
          </div>
          <div class="stat-content">
            <div class="stat-title">办公用品入库次数</div>
            <div class="stat-number">{{ summaryData.inboundCount }}</div>
            <div class="stat-unit">次</div>
          </div>
        </div>
      </Col>
    </Row>

    <!-- 第二行：请假相关图表 -->
    <div class="header-container">
      <div class="title-wrapper">
        <div class="title-bar"></div>
        <h3 class="title-text">请假数据分析</h3>
      </div>
    </div>
    <Row :gutter="16">
      <Col span="10">
        <Card>
          <div class="chart-title">请假类型占比</div>
          <div ref="leaveTypeChart" class="chart-container"></div>
        </Card>
      </Col>
      <Col span="14">
        <Card>
          <div class="chart-title">月度各人员请假次数</div>
          <div ref="leaveUserChart" class="chart-container"></div>
        </Card>
      </Col>
    </Row>

    <!-- 第三行：办公用品相关图表和表格 -->
    <div class="header-container">
      <div class="title-wrapper">
        <div class="title-bar"></div>
        <h3 class="title-text">办公用品数据分析</h3>
      </div>
    </div>
    <Row :gutter="16">
      <Col span="10">
        <Card>
          <div class="chart-title">月度各用品领用量</div>
          <div ref="materialUsageChart" class="chart-container"></div>
        </Card>
      </Col>
      <Col span="14">
        <Card class="stock-warning-card">
          <div class="chart-title">库存预警信息</div>
          <div class="table-container">
            <Table :data="stockWarningData" :columns="stockWarningColumns" size="small" border :height="chartHeight">
              <template slot="threshold" slot-scope="{ row }">
                <span>{{ row.min_stock }}-{{ row.max_stock }}</span>
              </template>
              <template slot="status" slot-scope="{ row }">
                <Tag :color="row.status === 'low' ? 'red' : 'orange'">
                  {{ row.status === 'low' ? '库存不足' : '库存过高' }}
                </Tag>
              </template>
            </Table>
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getSummaryStats,
  getLeaveTypeStats,
  getLeaveUserStats,
  getMaterialUsageStats,
  getStockWarningList
} from '@/api/key-dm'

export default {
  name: 'chart-analysis',
  data () {
    return {
      summaryData: {
        leaveCount: 0,
        borrowCount: 0,
        inboundCount: 0
      },
      leaveTypeChart: null,
      leaveUserChart: null,
      materialUsageChart: null,
      chartHeight: 240,
      stockWarningData: [],
      stockWarningColumns: [
        { title: '用品名称', key: 'material_name', align: 'center', minWidth: 50 },
        { title: '现有数量', key: 'available_quantity', align: 'center', minWidth: 50 },
        { title: '阙值范围', slot: 'threshold', align: 'center', minWidth: 50 },
        { title: '状态', slot: 'status', align: 'center', minWidth: 50 }
      ]
    }
  },
  mounted () {
    this.loadData()
  },
  beforeDestroy () {
    if (this.leaveTypeChart) {
      this.leaveTypeChart.dispose()
    }
    if (this.leaveUserChart) {
      this.leaveUserChart.dispose()
    }
    if (this.materialUsageChart) {
      this.materialUsageChart.dispose()
    }
  },
  methods: {
    loadData () {
      this.loadSummaryStats()
      this.loadLeaveTypeStats()
      this.loadLeaveUserStats()
      this.loadMaterialUsageStats()
      this.loadStockWarningList()
    },
    loadSummaryStats () {
      getSummaryStats().then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.summaryData = ret.data.data || this.summaryData
        }
      }).catch(() => {
        this.$Message.error('获取统计数据失败')
      })
    },
    loadLeaveTypeStats () {
      getLeaveTypeStats().then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.initLeaveTypeChart(ret.data.data || [])
        }
      }).catch(() => {
        this.$Message.error('获取请假类型统计失败')
      })
    },
    loadLeaveUserStats () {
      getLeaveUserStats().then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.initLeaveUserChart(ret.data.data || [])
        }
      }).catch(() => {
        this.$Message.error('获取人员请假统计失败')
      })
    },
    loadMaterialUsageStats () {
      getMaterialUsageStats().then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.initMaterialUsageChart(ret.data.data || [])
        }
      }).catch(() => {
        this.$Message.error('获取用品领用统计失败')
      })
    },
    loadStockWarningList () {
      getStockWarningList().then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.stockWarningData = ret.data.data || []
        }
      }).catch(() => {
        this.$Message.error('获取库存预警数据失败')
      })
    },
    initLeaveTypeChart (data) {
      this.$nextTick(() => {
        const chartDom = this.$refs.leaveTypeChart
        if (!chartDom) return

        this.leaveTypeChart = echarts.init(chartDom)
        const colors = ['#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#91cc75', '#fac858', '#ee6666']
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            textStyle: {
              fontSize: 12
            }
          },
          color: colors,
          series: [
            {
              name: '请假类型',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: true,
                position: 'outside',
                formatter: '{b}: {c}',
                fontSize: 12
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 10
              },
              data: data.map((item, index) => ({
                value: item.count,
                name: item.type_name,
                itemStyle: {
                  color: colors[index % colors.length]
                }
              }))
            }
          ]
        }
        this.leaveTypeChart.setOption(option)
      })
    },
    initLeaveUserChart (data) {
      this.$nextTick(() => {
        const chartDom = this.$refs.leaveUserChart
        if (!chartDom) return

        this.leaveUserChart = echarts.init(chartDom)
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.user_name),
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '请假次数',
              type: 'bar',
              data: data.map(item => item.leave_count),
              itemStyle: {
                color: '#409EFF'
              }
            }
          ]
        }
        this.leaveUserChart.setOption(option)
      })
    },
    initMaterialUsageChart (data) {
      this.$nextTick(() => {
        const chartDom = this.$refs.materialUsageChart
        if (!chartDom) return

        this.materialUsageChart = echarts.init(chartDom)
        const colors = ['#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#91cc75', '#fac858', '#ee6666']
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            textStyle: {
              fontSize: 12
            }
          },
          color: colors,
          series: [
            {
              name: '领用量',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: true,
                position: 'outside',
                formatter: '{b}: {c}',
                fontSize: 12
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 10
              },
              data: data.map((item, index) => ({
                value: item.total_quantity,
                name: item.material_name,
                itemStyle: {
                  color: colors[index % colors.length]
                }
              }))
            }
          ]
        }
        this.materialUsageChart.setOption(option)
      })
    }
  }
}
</script>

<style scoped>
.chart-analysis-wrapper {
  padding: 20px;
}

.header-container {
  margin: 20px 0 10px 0;
}

.title-wrapper {
  display: flex;
  align-items: center;
}

.title-bar {
  width: 4px;
  height: 20px;
  background-color: #409EFF;
  margin-right: 10px;
}

.title-text {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.statistics-bar {
  margin-bottom: 20px;
}

.statistics-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin: 0 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.statistics-item.leave-count {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.statistics-item.borrow-count {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.statistics-item.inbound-count {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon {
  color: white;
  margin-right: 20px;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 8px;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  color: white;
  margin-bottom: 4px;
  display: inline;
}

.stat-unit {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  display: inline;
}

.chart-container {
  width: 100%;
  height: 240px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  text-align: center;
}

.stock-warning-card {
  height: 315px;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  overflow: hidden;
}
</style>
