<template>
  <!-- 存款计划列表 -->
  <div class="budget-list">
    <template v-if="budgets?.length > 0">
      <BudgetCard
        v-for="budget in budgets"
        :key="budget.id"
        :budget="budget"
        :progress-color="getProgressColor(budget)"
        :percent-class="{ income: budget.current / budget.limit >= 1 }"
        :period-label="getPeriodLabel(budget.type)"
        style="margin: 0 12px 12px"
        @show-detail="handleShowDetail"
      >
        <template #amount-info>
          <div class="info-item">
            <div class="label">
              已存
            </div>
            <div class="value income">
              ¥{{ formatMoney(budget.current) }}
            </div>
          </div>
          <div class="info-item">
            <div class="label">
              计划存款
            </div>
            <div class="value">
              ¥{{ formatMoney(budget.limit) }}
            </div>
          </div>
          <div class="info-item">
            <div class="label">
              还差
            </div>
            <div class="value expense">
              ¥{{ formatMoney(Math.max(0, budget.limit - budget.current)) }}
            </div>
          </div>
        </template>

        <template #footer>
          <div class="card-footer-actions">
            <van-button
              size="small"
              icon="arrow-left"
              plain
              type="primary"
              @click.stop="$emit('savings-nav', budget, -1)"
            />
            <span class="current-date-label">
              {{ getSavingsDateLabel(budget) }}
            </span>
            <van-button
              size="small"
              icon="arrow"
              plain
              type="primary"
              icon-position="right"
              :disabled="disabledSavingsNextNav(budget)"
              @click.stop="$emit('savings-nav', budget, 1)"
            />
          </div>
        </template>
      </BudgetCard>
    </template>
    <van-empty
      v-else
      description="暂无存款计划"
    />
  </div>

  <!-- 计划存款明细弹窗 -->
  <van-popup
    v-model:show="showDetailPopup"
    position="bottom"
    round
    :style="{ height: '80%' }"
  >
    <div class="detail-popup-content">
      <div class="popup-header">
        <h3 class="popup-title">
          计划存款明细
        </h3>
        <van-icon
          name="cross"
          size="20"
          class="close-icon"
          @click="showDetailPopup = false"
        />
      </div>
      <div class="popup-body">
        <div
          v-if="currentBudget"
          class="detail-content"
        >
          <div class="detail-section income-section">
            <div class="section-title">
              <van-icon name="balance-o" />
              收入预算
            </div>
            <div class="section-content">
              <div class="detail-row">
                <span class="detail-label">预算限额</span>
                <span class="detail-value income">¥{{ formatMoney(incomeLimit) }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">实际收入</span>
                <span class="detail-value">¥{{ formatMoney(incomeCurrent) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section expense-section">
            <div class="section-title">
              <van-icon name="bill-o" />
              支出预算
            </div>
            <div class="section-content">
              <div class="detail-row">
                <span class="detail-label">预算限额</span>
                <span class="detail-value expense">¥{{ formatMoney(expenseLimit) }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">实际支出</span>
                <span class="detail-value">¥{{ formatMoney(expenseCurrent) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section formula-section">
            <div class="section-title">
              <van-icon name="calculator-o" />
              计划存款公式
            </div>
            <div class="formula-box">
              <div class="formula-item">
                <span class="formula-label">收入预算</span>
                <span class="formula-value income">¥{{ formatMoney(incomeLimit) }}</span>
              </div>
              <div class="formula-operator">
                -
              </div>
              <div class="formula-item">
                <span class="formula-label">支出预算</span>
                <span class="formula-value expense">¥{{ formatMoney(expenseLimit) }}</span>
              </div>
              <div class="formula-operator">
                =
              </div>
              <div class="formula-item">
                <span class="formula-label">计划存款</span>
                <span class="formula-value">¥{{ formatMoney(currentBudget.limit) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section result-section">
            <div class="section-title">
              <van-icon name="chart-trending-o" />
              存款结果
            </div>
            <div class="section-content">
              <div class="detail-row">
                <span class="detail-label">计划存款</span>
                <span class="detail-value">¥{{ formatMoney(currentBudget.limit) }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">实际存款</span>
                <span
                  class="detail-value"
                  :class="{ income: currentBudget.current >= currentBudget.limit }"
                >¥{{ formatMoney(currentBudget.current) }}</span>
              </div>
              <div class="detail-row highlight">
                <span class="detail-label">还差</span>
                <span class="detail-value expense">¥{{
                  formatMoney(Math.max(0, currentBudget.limit - currentBudget.current))
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, computed } from 'vue'
import BudgetCard from '@/components/Budget/BudgetCard.vue'
import { BudgetPeriodType } from '@/constants/enums'

// Props
const props = defineProps({
  budgets: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['savings-nav'])

// 明细弹窗状态
const showDetailPopup = ref(false)
const currentBudget = ref(null)

// 处理显示明细
const handleShowDetail = (budget) => {
  currentBudget.value = budget
  showDetailPopup.value = true
}

// 辅助函数
const formatMoney = (val) => {
  return parseFloat(val || 0).toLocaleString(undefined, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  })
}

const getPeriodLabel = (type) => {
  if (type === BudgetPeriodType.Month) {
    return '月度'
  }
  if (type === BudgetPeriodType.Year) {
    return '年度'
  }
  return '周期'
}

const getSavingsDateLabel = (budget) => {
  if (!budget.periodStart) {
    return ''
  }
  const date = new Date(budget.periodStart)
  if (budget.type === BudgetPeriodType.Year) {
    return `${date.getFullYear()}年`
  } else {
    return `${date.getFullYear()}年${date.getMonth() + 1}月`
  }
}

const disabledSavingsNextNav = (budget) => {
  if (!budget.periodStart) {
    return true
  }
  const date = new Date(budget.periodStart)
  const now = new Date()
  if (budget.type === BudgetPeriodType.Year) {
    return date.getFullYear() === now.getFullYear()
  } else {
    return date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth()
  }
}

const getProgressColor = (budget) => {
  if (!budget.limit || budget.limit === 0) {
    return 'var(--van-primary-color)'
  }

  const ratio = Math.min(Math.max(budget.current / budget.limit, 0), 1)

  const interpolate = (start, end, t) => {
    return Math.round(start + (end - start) * t)
  }

  const getGradientColor = (value, stops) => {
    let startStop = stops[0]
    let endStop = stops[stops.length - 1]

    for (let i = 0; i < stops.length - 1; i++) {
      if (value >= stops[i].p && value <= stops[i + 1].p) {
        startStop = stops[i]
        endStop = stops[i + 1]
        break
      }
    }

    const range = endStop.p - startStop.p
    const t = (value - startStop.p) / range

    const r = interpolate(startStop.c.r, endStop.c.r, t)
    const g = interpolate(startStop.c.g, endStop.c.g, t)
    const b = interpolate(startStop.c.b, endStop.c.b, t)

    return `rgb(${r}, ${g}, ${b})`
  }

  const stops = [
    { p: 0, c: { r: 245, g: 34, b: 45 } },
    { p: 0.45, c: { r: 255, g: 204, b: 204 } },
    { p: 0.5, c: { r: 240, g: 242, b: 245 } },
    { p: 0.55, c: { r: 186, g: 231, b: 255 } },
    { p: 1, c: { r: 24, g: 144, b: 255 } }
  ]

  return getGradientColor(ratio, stops)
}
</script>

<style scoped lang="scss">
.budget-list {
  padding-top: 8px;
  padding-bottom: 20px;
}

.card-footer-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid var(--van-border-color);
}

.current-date-label {
  font-size: 14px;
  font-weight: bold;
  color: var(--van-text-color);
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-item .label {
  font-size: 12px;
  color: var(--van-text-color-2);
  margin-bottom: 4px;
}

.info-item .value {
  font-size: 16px;
  font-weight: 600;
  font-family:
    DIN Alternate,
    system-ui;
}

.info-item .value.expense {
  color: var(--van-danger-color);
}

.info-item .value.income {
  color: var(--van-success-color);
}

.detail-popup-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--van-background-2);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--van-border-color);
  background-color: var(--van-background-2);
}

.popup-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--van-text-color);
}

.close-icon {
  color: var(--van-text-color-2);
  cursor: pointer;
  padding: 8px;
}

.popup-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-section {
  background-color: var(--van-background);
  border-radius: 12px;
  padding: 16px;
  border: 1px solid var(--van-border-color);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 600;
  color: var(--van-text-color);
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--van-border-color);
}

.income-section .section-title {
  color: var(--van-success-color);
}

.expense-section .section-title {
  color: var(--van-danger-color);
}

.section-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.detail-row.highlight {
  margin-top: 8px;
  padding-top: 12px;
  border-top: 1px dashed var(--van-border-color);
  font-weight: 600;
}

.detail-label {
  font-size: 14px;
  color: var(--van-text-color-2);
}

.detail-value {
  font-size: 15px;
  font-weight: 600;
  color: var(--van-text-color);
}

.detail-value.income {
  color: var(--van-success-color);
}

.detail-value.expense {
  color: var(--van-danger-color);
}

.formula-box {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  background-color: var(--van-light-gray);
  border-radius: 8px;
}

.formula-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  flex: 1;
  min-width: 100px;
}

.formula-label {
  font-size: 12px;
  color: var(--van-text-color-2);
}

.formula-value {
  font-size: 14px;
  font-weight: 600;
  color: var(--van-text-color);
}

.formula-operator {
  font-size: 20px;
  font-weight: 600;
  color: var(--van-text-color-2);
  padding: 0 8px;
}
</style>
