<!--
  PositionForecastView - 分行头寸预报页面
  ================================
  本页面用于展示分行头寸预报的总览数据、待处理任务以及偏离度计算结果。
  主要包含三个模块：
    1. 分行头寸预报总览（饼图 + 指标表格）
    2. 待处理任务列表
    3. 分行头寸预报偏离度计算结果表（含筛选、分页）
-->
<template>
  <section class="position-forecast-page">
    <!-- ======== 上半部分：左侧总览 + 右侧待处理任务，两列布局 ======== -->
    <el-row :gutter="18" class="top-grid">
      <!-- 左列：分行头寸预报总览 -->
      <el-col :xs="24" :lg="12">
        <el-card class="dashboard-card overview-card" shadow="never">
          <template #header>
            <h2 class="card-title"><span aria-hidden="true"></span>分行头寸预报总览</h2>
          </template>

          <div class="overview-body">
            <!-- 图例区域：展示两个分类的颜色标识 -->
            <div style="display: flex; gap: 24px; font-size: 13px; color: #111827; padding-top: 4px">
              <span><i style="display: inline-block; width: 10px; height: 10px; border-radius: 2px; background: #126bff; vertical-align: -1px; margin-right: 6px"></i>本分行头寸预报</span>
              <span><i style="display: inline-block; width: 10px; height: 10px; border-radius: 2px; background: #0bb06e; vertical-align: -1px; margin-right: 6px"></i>收支预报</span>
            </div>

            <!-- 内容区域：左侧饼图 + 右侧指标表格 -->
            <div style="display: grid; flex: 1; grid-template-columns: 1fr 1fr; align-items: center; column-gap: 14px">
              <!-- 饼图容器，由 ECharts 渲染，展示本分行头寸预报和收支预报的占比 -->
              <div ref="pieChartRef" style="width: 100%; height: 180px"></div>

              <!-- 指标表格：展示各项目在今日、本月、今年的完成比例 -->
              <el-table :data="forecastData" size="small" :show-header="true" :header-cell-style="{ background: 'transparent', fontWeight: 600 }" :cell-style="{ fontSize: '13px' }">
                <!-- 项目名称列，带颜色圆点标识 -->
                <el-table-column prop="name" label="项目" min-width="90">
                  <template #default="{ row }">
                    <span><i :style="{ display: 'inline-block', width: '8px', height: '8px', borderRadius: '50%', background: row.color, verticalAlign: '-1px', marginRight: '6px' }"></i>{{ row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="today" label="今日" align="center" />
                <el-table-column prop="month" label="本月" align="center" />
                <el-table-column prop="year" label="今年" align="center" />
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右列：待处理任务 -->
      <el-col :xs="24" :lg="12">
        <el-card class="dashboard-card task-card" shadow="never">
          <template #header>
            <h2 class="card-title"><span aria-hidden="true"></span>待处理任务</h2>
          </template>

          <!-- 待处理任务表格 -->
          <!-- 状态列：使用 el-checkbox 展示是否完成 -->
          <!-- 任务结果列：使用 el-tag 展示成功/警告状态 -->
          <el-table :data="pendingTasks" size="small" :show-header="true" :header-cell-style="{ background: 'transparent', fontWeight: 600 }" :cell-style="{ fontSize: '13px' }">
            <el-table-column prop="status" label="状态" align="center" width="60">
              <template #default="{ row }">
                <el-checkbox :model-value="row.status"  />
              </template>
            </el-table-column>
            <el-table-column prop="process" label="流程" align="center" />
            <el-table-column prop="task" label="任务" align="center" />
            <el-table-column prop="pending" label="待办" align="center" />
            <el-table-column prop="delay" label="延迟" align="center" />
            <el-table-column prop="timeout" label="超时" align="center" />
            <!-- 任务结果：success 显示绿色勾，warning 显示橙色叹号 -->
            <el-table-column prop="result" label="任务" align="center" width="60">
              <template #default="{ row }">
                <el-tag :type="row.result === 'success' ? 'success' : 'warning'" size="small" effect="dark" style="border: none" round>
                  <el-icon><component :is="row.result === 'success' ? Check : Warning" /></el-icon>
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- ======== 下半部分：分行头寸预报偏离度计算结果表 ======== -->
    <el-card class="dashboard-card result-card" shadow="never">
      <template #header>
        <h2 class="card-title"><span aria-hidden="true"></span>分行头寸预报偏离度计算结果表</h2>
      </template>

      <!-- 筛选栏：支持按管辖分行、日期范围、偏离度类型、确认结果进行筛选 -->
      <div style="display: flex; align-items: center; justify-content: space-between; padding: 12px 0">
        <div style="display: flex; align-items: center; gap: 12px">
          <!-- 管辖分行筛选 -->
          <el-select v-model="filter.region" placeholder="请选择管辖分行" style="width: 200px" clearable>
            <el-option label="全部" value="" />
            <el-option label="14分行" value="14分行" />
            <el-option label="本行头寸预报本行" value="本行头寸预报本行" />
          </el-select>
          <!-- 日期范围筛选 -->
          <el-date-picker
            v-model="filter.dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="截止日期"
            range-separator=""
            style="width: 240px"
          />
          <!-- 偏离度类型筛选 -->
          <span style="font-size: 13px; color: #1f2937">偏离度类型</span>
          <el-select v-model="filter.type" style="width: 100px">
            <el-option label="全部类型" value="" />
            <el-option label="总账活期" value="总账活期" />
            <el-option label="总账定期" value="总账定期" />
          </el-select>
          <!-- 确认结果筛选 -->
          <span style="font-size: 13px; color: #1f2937">确认结果</span>
          <el-select v-model="filter.result" style="width: 90px">
            <el-option label="全部" value="" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="未确认" value="unconfirmed" />
          </el-select>
          <!-- 操作按钮 -->
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="primary" @click="search">查询</el-button>
        </div>
      </div>

      <!-- 偏离度计算结果表格：展示辖区、分行内码、来源类型、预报日期等详细信息 -->
      <el-table :data="positionResults" class="result-table" border>
        <el-table-column type="index" label="#" width="74" align="center" />
        <el-table-column prop="region" label="辖区" min-width="170" align="center" />
        <el-table-column prop="branchCode" label="分行内码" min-width="170" align="center" />
        <el-table-column prop="sourceType" label="头寸预报来源类型" min-width="190" align="center" />
        <el-table-column prop="forecastDate" label="预报日期" min-width="190" align="center" />
        <el-table-column prop="receiveTime" label="数据接收时间" min-width="190" align="center" />
        <el-table-column prop="responsibleBranch" label="数据预报责任岗" min-width="190" align="center" />
        <el-table-column prop="deviation" label="偏离度" min-width="170" align="center" />
        <!-- 详情操作列：支持预览和查看 -->
        <el-table-column label="详情" width="170" align="center">
          <template #default>
            <el-button link type="primary">预览</el-button>
            <el-button link type="primary">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件：使用 Element Plus 内置分页，支持总数显示、每页条数切换、页码跳转 -->
      <div style="display: flex; justify-content: flex-end; padding-top: 16px">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>
  </section>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'
import { Check, Warning } from '@element-plus/icons-vue'

/**
 * 日期范围类型定义
 * 用于筛选栏的 el-date-picker，值为 [开始日期, 结束日期] 或空数组
 */
type DateRange = [Date, Date] | []

/** 饼图 DOM 容器引用 */
const pieChartRef = ref<HTMLElement | null>(null)

/** ECharts 实例，用于后续 resize 和 dispose */
let pieChart: echarts.ECharts | null = null

/** 筛选条件表单 */
const filter = ref({
  region: '',           // 管辖分行
  dateRange: [] as DateRange, // 计算日期范围
  type: '',             // 偏离度类型：总账活期 / 总账定期
  result: '',           // 确认结果：confirmed / unconfirmed
})

/** 分页相关状态 */
const currentPage = ref(1)  // 当前页码
const pageSize = ref(10)    // 每页条数
const total = ref(47)       // 总记录数

/**
 * 分行头寸预报总览数据
 * name: 项目名称
 * today/month/year: 今日/本月/今年的完成比例
 * color: 对应的颜色标识
 */
const forecastData = [
  { name: '借款', today: '125%', month: '-', year: '264.95%', color: '#ff9500' },
  { name: '结算性存款', today: '35%', month: '14.61%', year: '136.92%', color: '#ff9500' },
  { name: '保证金存款', today: '52%', month: '14.35%', year: '166.25%', color: '#0bb06e' },
  { name: '拆放款', today: '-', month: '-', year: '-', color: '#126bff' },
]

/**
 * 待处理任务数据
 * status: 是否已完成（true=已完成，显示勾选框）
 * process: 所属流程名称
 * task: 具体任务名称
 * pending/delay/timeout: 待办/延迟/超时的数量
 * result: 任务执行结果（success=成功，warning=警告）
 */
const pendingTasks = [
  { status: true, process: '头寸预报', task: '待办处理', pending: '37235', delay: '1259.34', timeout: '', result: 'success' },
  { status: false, process: '额度管理', task: '额度审批', pending: '57285', delay: '13785', timeout: '', result: 'success' },
  { status: false, process: '监控与预警', task: '预警处理', pending: '696', delay: '', timeout: '1522.22', result: 'warning' },
]

/**
 * 偏离度计算结果数据
 * region: 辖区
 * branchCode: 分行内码
 * sourceType: 头寸预报来源类型（总账活期/总账定期）
 * forecastDate: 预报日期
 * receiveTime: 数据接收时间（此处实际存储的是管辖分行信息）
 * responsibleBranch: 数据预报责任岗
 * deviation: 偏离度数值
 */
const positionResults = [
  { region: '本行头寸预报本行', branchCode: '20210114-027', sourceType: '总账活期', forecastDate: '2021-06-52 16:33', receiveTime: '14分行', responsibleBranch: '岗1', deviation: '12.300000' },
  { region: '分行头寸预报本行', branchCode: '20210114-027', sourceType: '总账定期', forecastDate: '2021-06-52 16:33', receiveTime: '14分行', responsibleBranch: '岗1', deviation: '12.300000' },
  { region: '本行头寸预报本行', branchCode: '20210114-027', sourceType: '总账活期', forecastDate: '2021-04-58 12:33', receiveTime: '14分行', responsibleBranch: '岗1', deviation: '12.300000' },
  { region: '分行头寸预报本行', branchCode: '20210114-027', sourceType: '总账活期', forecastDate: '2021-02-58 10:33', receiveTime: '14分行', responsibleBranch: '岗1', deviation: '12.300000' },
  { region: '分行头寸预报本行', branchCode: '20210114-027', sourceType: '总账活期', forecastDate: '2021-01-53 16:33', receiveTime: '14分行', responsibleBranch: '岗1', deviation: '12.300000' },
]

/**
 * 初始化饼图
 * 使用 ECharts 渲染环形图，展示本分行头寸预报和收支预报的占比
 * 中心文字显示收支预报的总百分比
 */
const initPieChart = () => {
  if (!pieChartRef.value) return

  pieChart = echarts.init(pieChartRef.value)
  const option: echarts.EChartsOption = {
    color: ['#126bff', '#ffb73f'],
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const item = Array.isArray(params) ? params[0] : params
        return item ? `${item.name}<br/>${item.value}%` : ''
      },
    },
    // 中心文字：显示总百分比和副标题
    graphic: [
      {
        type: 'text',
        left: 'center',
        top: '42%',
        style: {
          text: '7539%',
          fill: '#126bff',
          fontSize: 20,
          fontWeight: 700,
        },
      },
      {
        type: 'text',
        left: 'center',
        top: '56%',
        style: {
          text: '收支预报',
          fill: '#6b7280',
          fontSize: 12,
        },
      },
    ],
    series: [
      {
        type: 'pie',
        radius: ['52%', '76%'], // 内外半径，形成环形图
        center: ['50%', '50%'],
        startAngle: 90,
        minAngle: 14,
        avoidLabelOverlap: true,
        // 标签：显示百分比数值
        label: {
          show: true,
          formatter: ({ value }) => `${value}%`,
          color: '#126bff',
          fontSize: 12,
          fontWeight: 600,
        },
        // 标签引导线
        labelLine: {
          show: true,
          length: 18,
          length2: 52,
          lineStyle: { width: 1 },
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
        },
        // 两个数据系列：本分行头寸预报（蓝色）和收支预报（橙色）
        data: [
          {
            value: 96.28,
            name: '本分行头寸预报',
            itemStyle: { color: '#126bff' },
            label: { color: '#126bff' },
            labelLine: { lineStyle: { color: '#126bff' } },
          },
          {
            value: 22.28,
            name: '收支预报',
            itemStyle: { color: '#ffb73f' },
            label: { color: '#ff9500' },
            labelLine: { lineStyle: { color: '#ff9500' } },
          },
        ],
      },
    ],
  }

  pieChart.setOption(option)
}

/** 窗口 resize 时重新调整饼图尺寸 */
const handleResize = () => {
  pieChart?.resize()
}

/** 重置筛选条件为初始状态 */
const resetFilter = () => {
  filter.value = {
    region: '',
    dateRange: [],
    type: '',
    result: '',
  }
}

/** 执行查询（待接入后端接口） */
const search = () => {
  console.log('搜索条件:', filter.value)
}

/**
 * 生命周期：组件挂载后初始化饼图，并监听窗口 resize 事件
 * 使用 nextTick 确保 DOM 已渲染完成
 */
onMounted(() => {
  nextTick(() => {
    initPieChart()
    window.addEventListener('resize', handleResize)
  })
})

/**
 * 生命周期：组件卸载前清理资源
 * 移除 resize 监听，销毁 ECharts 实例释放内存
 */
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  pieChart?.dispose()
})
</script>

<style scoped>
/* 页面根容器，宽度自适应父组件 */
.position-forecast-page {
  width: 100%;
  padding: 0;
  color: #1f2937;
}

/* 上半部分两列之间的底部间距 */
.top-grid {
  margin-bottom: 16px;
}

/* 所有卡片的头部样式：去掉底部边框，调整内边距 */
.dashboard-card :deep(.el-card__header) {
  border-bottom: 0;
  padding: 14px 20px 6px;
}

/* 所有卡片的内容区域样式 */
.dashboard-card :deep(.el-card__body) {
  padding: 0 20px 16px;
}

/* 卡片标题样式：左侧带蓝色竖条装饰 */
.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  color: #111827;
  font-size: 15px;
  font-weight: 600;
  line-height: 1;
}

/* 标题左侧的蓝色竖条 */
.card-title span {
  width: 4px;
  height: 14px;
  border-radius: 1px;
  background: #126bff;
}

/* 上半部分左右两张卡片的固定高度 */
.overview-card,
.task-card {
  height: 270px;
}

/* 总览卡片内容区域的纵向布局 */
.overview-body {
  display: flex;
  flex-direction: column;
}

/* 偏离度结果表卡片头部额外上边距 */
.result-card :deep(.el-card__header) {
  padding-top: 14px;
}

/* 偏离度结果表的表头背景色和加粗 */
.result-table :deep(.el-table__header th) {
  background: #f7f9fd;
  font-weight: 600;
}
</style>
