<template>
  <div class="budget-container">
    <!-- 顶部预算总金额 -->
    <div class="budget-header">
      <div class="budget-title">
        <h1>预算总金额</h1>
        <el-button type="text" @click="showBudgetDialog" class="set-amount-btn">设置金额</el-button>
      </div>
      <div class="budget-summary">
        <div class="summary-item">
          <span class="summary-value">{{ budgetTotal }}元</span>
        </div>
        <div class="divider">|</div>
        <div class="summary-item">
          <span class="summary-label">已执行总金额</span>
          <span class="summary-value">{{ executedTotal }}万元</span>
        </div>
        <div class="divider">|</div>
        <div class="summary-item">
          <span class="summary-label">预算执行差额</span>
          <span class="summary-value">{{ budgetDifference }}元</span>
        </div>
      </div>
    </div>

    <!-- 预算设置对话框 -->
    <el-dialog
        v-model="budgetDialogVisible"
        title="预算设置"
        width="800px"
        :before-close="handleBudgetDialogClose"
    >
      <div class="budget-form">
        <div class="dimension-selector">
          <el-select v-model="selectedDimension" placeholder="请选择统计维度" @change="handleDimensionChange">
            <el-option label="年度" value="year" />
            <el-option label="季度" value="quarter" />
            <el-option label="月份" value="month" />
          </el-select>
          <el-tooltip
              effect="dark"
              content="预算统计维度：选择最低统计维度。如选择季度，那么可以按照年度或者季度查看预算执行与实际预算的差值"
              placement="top"
          >
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
        </div>

        <el-table :data="budgetItems" border style="width: 100%">
          <el-table-column prop="name" label="费用类型" width="180" />
          <el-table-column label="预算金额">
            <template #default="{ row }">
              <el-input-number
                  v-model="row.amount"
                  :min="0"
                  :step="1000"
                  controls-position="right"
                  @change="calculateTotal"
              >
                <template #append>元</template>
              </el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="budgetDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBudget">确定</el-button>
      </template>
    </el-dialog>

    <!-- 预算图表 -->
    <div class="budget-chart">
      <div class="chart-header">
        <h2>预算执行情况</h2>
        <el-select v-model="selectedYear" placeholder="选择年份" style="width: 120px">
          <el-option label="全部" value="all" />
          <el-option label="2025" value="2025" />
        </el-select>
      </div>
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'

// 预算数据
const budgetItems = ref([
  { name: '人员人工费用', amount: 0 },
  { name: '直接投入费用', amount: 0 },
  { name: '折旧费用与长期待摊费用', amount: 0 },
  { name: '无形资产摊销', amount: 0 },
  { name: '设计费用', amount: 0 },
  { name: '装备调试费用与试验费用', amount: 0 },
  { name: '委托研发费用', amount: 0 },
  { name: '其它相关费用', amount: 0 }
])

// 预算总金额
const budgetTotal = ref('0')
const executedTotal = ref('0.00')
const budgetDifference = ref('0')

// 对话框控制
const budgetDialogVisible = ref(false)
const selectedDimension = ref('month')

// 图表相关
const chartRef = ref(null)
const selectedYear = ref('all')
let chartInstance = null

// 显示预算设置对话框
const showBudgetDialog = () => {
  budgetDialogVisible.value = true
}

// 关闭对话框
const handleBudgetDialogClose = (done) => {
  done()
}

// 计算预算总金额
const calculateTotal = () => {
  const total = budgetItems.value.reduce((sum, item) => sum + (item.amount || 0), 0)
  budgetTotal.value = total.toLocaleString()
  budgetDifference.value = (total - parseFloat(executedTotal.value) * 10000).toLocaleString()
}

// 保存预算
const saveBudget = () => {
  calculateTotal()
  budgetDialogVisible.value = false
  initChart()
}

// 切换统计维度
const handleDimensionChange = (val) => {
  ElMessageBox.confirm(
      '确认切换预算统计维度吗？点击确认，将会删除当前维度的数据!',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 这里可以添加切换维度的逻辑
    ElMessage.success('维度切换成功')
  }).catch(() => {
    // 取消切换，恢复原值
    selectedDimension.value = 'month'
  })
}

// 初始化图表
const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: function(params) {
        let tooltipHtml = `<div style="font-weight:bold;margin-bottom:10px;">${params[0].axisValue}</div>`
        tooltipHtml += '<table style="width:100%;border-collapse:collapse;">'
        tooltipHtml += '<tr><td style="padding:5px 0;border-bottom:1px solid #eee;font-weight:bold;">类型</td><td style="padding:5px 0;border-bottom:1px solid #eee;font-weight:bold;">金额</td></tr>'

        // 预算数据
        tooltipHtml += `<tr>
          <td style="padding:5px 0;border-bottom:1px solid #eee;">预算总金额</td>
          <td style="padding:5px 0;border-bottom:1px solid #eee;">${budgetTotal.value}元</td>
        </tr>`

        // 已执行数据
        tooltipHtml += `<tr>
          <td style="padding:5px 0;border-bottom:1px solid #eee;">已执行总金额</td>
          <td style="padding:5px 0;border-bottom:1px solid #eee;">${executedTotal.value}万元</td>
        </tr>`

        // 各项费用
        budgetItems.value.forEach(item => {
          tooltipHtml += `<tr>
            <td style="padding:5px 0;border-bottom:1px solid #eee;">${item.name}</td>
            <td style="padding:5px 0;border-bottom:1px solid #eee;">${item.amount}元</td>
          </tr>`
        })

        tooltipHtml += '</table>'
        return tooltipHtml
      }
    },
    legend: {
      data: ['预算总金额', '已执行总金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisPointer: {
        type: 'shadow'
      }
    },
    yAxis: {
      type: 'value',
      name: '金额（万元）',
      min: 0,
      max: 6000,
      interval: 1000,
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '预算总金额',
        type: 'bar',
        barWidth: '30%',
        itemStyle: {
          color: '#409EFF'
        },
        data: [5000, 4500, 4800, 5200, 5500, 5800, 6000, 5900, 5700, 5400, 5100, 4800]
      },
      {
        name: '已执行总金额',
        type: 'bar',
        barWidth: '30%',
        itemStyle: {
          color: '#67C23A'
        },
        data: [3200, 2800, 3500, 3800, 4200, 4500, 4800, 4600, 4400, 4100, 3800, 3500]
      }
    ]
  }

  chartInstance.setOption(option)

  // 响应式调整
  window.addEventListener('resize', function() {
    chartInstance.resize()
  })
}

// 监听年份选择
watch(selectedYear, (newVal) => {
  initChart()
})

// 初始化
onMounted(() => {
  initChart()
})
</script>

<style scoped>
.budget-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.budget-header {
  margin-bottom: 30px;
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.budget-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.budget-title h1 {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
  color: #303133;
}

.set-amount-btn {
  margin-left: 20px;
  color: #409EFF;
  font-size: 16px;
}

.budget-summary {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  margin: 0 15px;
}

.summary-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.divider {
  color: #dcdfe6;
  font-size: 20px;
}

.budget-form {
  padding: 10px;
}

.dimension-selector {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.dimension-selector .el-select {
  width: 200px;
  margin-right: 10px;
}

.budget-chart {
  margin-top: 30px;
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h2 {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}
</style>
