<template>
  <div>
    <warning-bar title="注：本页面为数据采集管理，支持对密码设施采集服务的配置与管理，并查看设施运行趋势" />
    <div class="gva-table-box">
      <!--按钮区域-->
      <div class="gva-btn-list">
        <el-button
          v-preReClick
          icon="plus"
          type="primary"
          @click="addService"
        >
          新增采集服务
        </el-button>
        <el-button
          v-preReClick
          icon="refresh"
          type="warning"
          @click="refreshData"
        >
          刷新数据
        </el-button>
        <el-button
          v-preReClick
          icon="refresh"
          type="success"
          plain
          @click="triggerCollect"
        >
          手动采集
        </el-button>
      </div>

      <!--筛选区域-->
      <div class="filter-area">
        <span class="filter-label">密码设施名称：</span>
        <el-input
          v-model="filterName"
          clearable
          placeholder="请输入名称（模糊查询）"
          style="width: 180px"
          @change="handleFilterChange"
          @clear="handleFilterChange"
        />
        <span class="filter-label" style="margin-left: 12px">密码设施IP：</span>
        <el-input
          v-model="filterIP"
          clearable
          placeholder="请输入IP地址"
          style="width: 160px"
          @change="handleFilterChange"
          @clear="handleFilterChange"
        />
        <span class="filter-label" style="margin-left: 12px">密码设施标识：</span>
        <el-input
          v-model="filterIdentifier"
          clearable
          placeholder="请输入标识"
          style="width: 160px"
          @change="handleFilterChange"
          @clear="handleFilterChange"
        />
        <span class="filter-label" style="margin-left: 12px">检测状态：</span>
        <el-select
          v-model="filterStatus"
          clearable
          placeholder="全部"
          style="width: 120px"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="启用" value="1" />
          <el-option label="停用" value="2" />
        </el-select>
        <el-button
          v-preReClick
          type="primary"
          style="margin-left: 16px"
          @click="handleFilterChange"
        >
          查询
        </el-button>
        <el-button
          v-preReClick
          @click="resetFilter"
        >
          重置
        </el-button>
      </div>

      <!--数据表格-->
      <el-table
        :data="tableData"
        row-key="ID"
        style="margin-top: 12px"
      >
        <el-table-column
          align="left"
          label="ID"
          min-width="60"
          prop="ID"
        />
        <el-table-column
          align="left"
          label="密码设施名称"
          min-width="150"
          prop="facilityName"
          show-overflow-tooltip
        />
        <el-table-column
          align="left"
          label="密码设施标识"
          min-width="160"
          prop="facilityIdentifier"
          show-overflow-tooltip
        />
        <el-table-column
          align="left"
          label="密码设施IP"
          min-width="140"
          prop="facilityIP"
        />
        <el-table-column
          align="left"
          label="密码机端口"
          min-width="120"
          prop="facilityPort"
        />
        <el-table-column
          align="left"
          label="密码设施类型"
          min-width="140"
        >
          <template #default="scope">
            <el-tag
              :type="getFacilityTypeTag(scope.row.facilityType)"
              effect="light"
              size="default"
            >
              {{ scope.row.facilityType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="检测状态"
          min-width="100"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.detectStatus"
              :active-value="1"
              :inactive-value="2"
              inline-prompt
              @change="() => { switchStatus(scope.row) }"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="服务创建时间"
          min-width="180"
          prop="createTime"
        />
        <el-table-column
          align="center"
          label="趋势分析"
          min-width="120"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              v-preReClick
              icon="trend-chart"
              type="primary"
              link
              @click="openTrendAnalysis(scope.row)"
            >
              查看趋势
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          min-width="160"
        >
          <template #default="scope">
            <el-popover
              v-model:visible="scope.row.visible"
              placement="top"
              width="160"
            >
              <p>确定要删除此采集服务吗？</p>
              <div style="text-align: right; margin-top: 8px">
                <el-button
                  v-preReClick
                  link
                  type="primary"
                  @click="scope.row.visible = false"
                >
                  取消
                </el-button>
                <el-button
                  v-preReClick
                  type="primary"
                  @click="deleteService(scope.row)"
                >
                  确定
                </el-button>
              </div>
              <template #reference>
                <el-button
                  v-preReClick
                  icon="delete"
                  link
                  type="primary"
                >
                  删除
                </el-button>
              </template>
            </el-popover>
            <el-button
              v-preReClick
              icon="edit"
              link
              type="primary"
              @click="openEdit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!--新增/编辑采集服务弹窗-->
    <el-dialog
      v-model="addDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :title="dialogFlag === 'add' ? '新增采集服务' : '编辑采集服务'"
      width="580px"
    >
      <div style="max-height: 65vh; overflow: auto; padding: 0 12px">
        <el-form
          ref="serviceFormRef"
          :model="serviceForm"
          :rules="formRules"
          label-width="130px"
        >
          <el-form-item
            label="密码设施名称"
            prop="facilityName"
          >
            <el-input
              v-model="serviceForm.facilityName"
              placeholder="请输入密码设施名称"
            />
          </el-form-item>
          <el-form-item
            label="密码设施标识"
            prop="facilityIdentifier"
          >
            <el-input
              v-model="serviceForm.facilityIdentifier"
              placeholder="系统自动生成"
              readonly
            />
            <span style="font-size: 12px; color: #909399; margin-left: 8px">自动生成</span>
          </el-form-item>
          <el-form-item
            label="密码设施IP"
            prop="facilityIP"
          >
            <el-input
              v-model="serviceForm.facilityIP"
              placeholder="请输入设施网络IP，如 192.168.1.100"
            />
          </el-form-item>
          <el-form-item
            label="密码机端口"
            prop="facilityPort"
          >
            <el-input-number
              v-model="serviceForm.facilityPort"
              :min="1"
              :max="65535"
              placeholder="请输入端口号"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item
            label="密码设施类型"
            prop="facilityType"
          >
            <el-select
              v-model="serviceForm.facilityType"
              placeholder="请选择密码设施类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in facilityTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="检测状态"
            prop="detectStatus"
          >
            <el-switch
              v-model="serviceForm.detectStatus"
              :active-value="1"
              :inactive-value="2"
              inline-prompt
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-preReClick
            @click="closeDialog"
          >
            取 消
          </el-button>
          <el-button
            v-preReClick
            type="primary"
            @click="submitService"
          >
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--趋势分析弹窗-->
    <el-dialog
      v-model="trendDialogVisible"
      :close-on-click-modal="true"
      title="趋势分析"
      width="900px"
      destroy-on-close
    >
      <div style="padding: 0 8px">
        <div style="display: flex; align-items: center; margin-bottom: 16px; gap: 24px; flex-wrap: wrap">
          <div>
            <span style="font-weight: bold; color: #303133">设施名称：</span>
            <span>{{ trendTarget?.facilityName || '-' }}</span>
          </div>
          <div>
            <span style="font-weight: bold; color: #303133">设施标识：</span>
            <span>{{ trendTarget?.facilityIdentifier || '-' }}</span>
          </div>
          <div>
            <span style="font-weight: bold; color: #303133">设施IP：</span>
            <span>{{ trendTarget?.facilityIP || '-' }}</span>
          </div>
          <div>
            <span style="font-weight: bold; color: #303133">设施类型：</span>
            <span>{{ trendTarget?.facilityType || '-' }}</span>
          </div>
        </div>

        <el-divider content-position="left">资源使用率（实时）</el-divider>
        <div class="trend-metrics">
          <div class="metric-card">
            <div class="metric-label">CPU 使用率</div>
            <el-progress
              :percentage="trendData.cpuUsage"
              :color="getProgressColor(trendData.cpuUsage)"
              :stroke-width="14"
              striped
              striped-flow
            />
            <div class="metric-value">{{ trendData.cpuUsage }}%</div>
          </div>
          <div class="metric-card">
            <div class="metric-label">磁盘利用率</div>
            <el-progress
              :percentage="trendData.diskUsage"
              :color="getProgressColor(trendData.diskUsage)"
              :stroke-width="14"
              striped
              striped-flow
            />
            <div class="metric-value">{{ trendData.diskUsage }}%</div>
          </div>
          <div class="metric-card">
            <div class="metric-label">内存利用率</div>
            <el-progress
              :percentage="trendData.memoryUsage"
              :color="getProgressColor(trendData.memoryUsage)"
              :stroke-width="14"
              striped
              striped-flow
            />
            <div class="metric-value">{{ trendData.memoryUsage }}%</div>
          </div>
          <div class="metric-card total-calls">
            <div class="metric-label">接口调用总次数</div>
            <div class="total-calls-number">{{ trendData.totalCalls.toLocaleString() }}</div>
            <div style="font-size: 12px; color: #909399; margin-top: 4px">近7天累计</div>
          </div>
        </div>

        <el-divider content-position="left">接口调用趋势（近7天）</el-divider>
        <div ref="chartRef" class="trend-chart" />
      </div>
      <template #footer>
        <el-button
          v-preReClick
          type="primary"
          @click="trendDialogVisible = false"
        >
          关 闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import WarningBar from '@/components/warningBar/warningBar.vue'
import * as echarts from 'echarts'

defineOptions({
  name: 'DataCollectionManagement'
})

// 常量与配置
const facilityTypeOptions = [
  { label: '密码机', value: '密码机' },
  { label: '密码服务中台', value: '密码服务中台' },
  { label: '密码网关', value: '密码网关' },
  { label: '密钥管理系统', value: '密钥管理系统' },
  { label: '安全认证网关', value: '安全认证网关' }
]

// Mock 数据生成
// 生成随机数
const random = (min, max) => Math.round(Math.random() * (max - min) + min)

// 生成设施标识
const generateIdentifier = () => {
  const now = new Date()
  const ts = now.getFullYear() +
    String(now.getMonth() + 1).padStart(2, '0') +
    String(now.getDate()).padStart(2, '0') +
    String(now.getHours()).padStart(2, '0') +
    String(now.getMinutes()).padStart(2, '0') +
    String(now.getSeconds()).padStart(2, '0')
  const rand = String(Math.floor(Math.random() * 10000)).padStart(4, '0')
  return `FAC-${ts}-${rand}`
}

// 生成时间字符串
const getNowStr = () => {
  const d = new Date()
  return d.getFullYear() + '-' +
    String(d.getMonth() + 1).padStart(2, '0') + '-' +
    String(d.getDate()).padStart(2, '0') + ' ' +
    String(d.getHours()).padStart(2, '0') + ':' +
    String(d.getMinutes()).padStart(2, '0') + ':' +
    String(d.getSeconds()).padStart(2, '0')
}

// 生成近7天调用趋势数据
const generateTrendData = () => {
  const days = 7
  const result = []
  const now = new Date()
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date(now)
    d.setDate(d.getDate() - i)
    const label = (d.getMonth() + 1) + '/' + d.getDate()
    const value = random(80, 450)
    result.push({ label, value })
  }
  return result
}

// 初始 Mock 列表
let nextId = 1
const mockDataList = ref([
  {
    ID: nextId++,
    facilityName: '主密码机-01',
    facilityIdentifier: generateIdentifier(),
    facilityIP: '192.168.1.100',
    facilityPort: 8443,
    facilityType: '密码机',
    detectStatus: 1,
    createTime: '2026-07-15 09:30:00',
    visible: false,
    // 趋势数据
    cpuUsage: random(20, 75),
    diskUsage: random(30, 85),
    memoryUsage: random(25, 70),
    totalCalls: random(800, 2500),
    trendDetail: generateTrendData()
  },
  {
    ID: nextId++,
    facilityName: '密码服务中台-生产',
    facilityIdentifier: generateIdentifier(),
    facilityIP: '192.168.1.105',
    facilityPort: 8444,
    facilityType: '密码服务中台',
    detectStatus: 1,
    createTime: '2026-07-16 14:20:00',
    visible: false,
    cpuUsage: random(15, 60),
    diskUsage: random(40, 80),
    memoryUsage: random(30, 65),
    totalCalls: random(1200, 3800),
    trendDetail: generateTrendData()
  },
  {
    ID: nextId++,
    facilityName: '密钥管理系统-主',
    facilityIdentifier: generateIdentifier(),
    facilityIP: '192.168.1.110',
    facilityPort: 8445,
    facilityType: '密钥管理系统',
    detectStatus: 2,
    createTime: '2026-07-17 11:00:00',
    visible: false,
    cpuUsage: random(10, 45),
    diskUsage: random(20, 55),
    memoryUsage: random(15, 50),
    totalCalls: random(300, 900),
    trendDetail: generateTrendData()
  },
  {
    ID: nextId++,
    facilityName: '安全认证网关-01',
    facilityIdentifier: generateIdentifier(),
    facilityIP: '192.168.1.115',
    facilityPort: 8446,
    facilityType: '安全认证网关',
    detectStatus: 1,
    createTime: '2026-07-18 16:45:00',
    visible: false,
    cpuUsage: random(30, 80),
    diskUsage: random(35, 70),
    memoryUsage: random(40, 75),
    totalCalls: random(600, 1800),
    trendDetail: generateTrendData()
  },
  {
    ID: nextId++,
    facilityName: '密码服务中台-测试',
    facilityIdentifier: generateIdentifier(),
    facilityIP: '192.168.1.120',
    facilityPort: 8447,
    facilityType: '密码服务中台',
    detectStatus: 2,
    createTime: '2026-07-19 08:30:00',
    visible: false,
    cpuUsage: random(5, 30),
    diskUsage: random(10, 40),
    memoryUsage: random(8, 35),
    totalCalls: random(50, 300),
    trendDetail: generateTrendData()
  },
  {
    ID: nextId++,
    facilityName: '密码网关-核心',
    facilityIdentifier: generateIdentifier(),
    facilityIP: '192.168.1.125',
    facilityPort: 8448,
    facilityType: '密码网关',
    detectStatus: 1,
    createTime: '2026-07-20 13:15:00',
    visible: false,
    cpuUsage: random(25, 65),
    diskUsage: random(45, 75),
    memoryUsage: random(35, 60),
    totalCalls: random(900, 2200),
    trendDetail: generateTrendData()
  }
])

// 响应式状态
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 筛选条件
const filterName = ref('')
const filterIP = ref('')
const filterIdentifier = ref('')
const filterStatus = ref('')

// 弹窗
const addDialogVisible = ref(false)
const trendDialogVisible = ref(false)
const dialogFlag = ref('add') // 'add' | 'edit'

// 表单
const serviceFormRef = ref(null)
const serviceForm = reactive({
  ID: null,
  facilityName: '',
  facilityIdentifier: '',
  facilityIP: '',
  facilityPort: 8443,
  facilityType: '密码机',
  detectStatus: 1
})

// 表单验证规则
const formRules = {
  facilityName: [
    { required: true, message: '请输入密码设施名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  facilityIP: [
    { required: true, message: '请输入密码设施IP', trigger: 'blur' },
    {
      pattern: /^(\d{1,3}\.){3}\d{1,3}$/,
      message: '请输入合法的IP地址',
      trigger: 'blur'
    }
  ],
  facilityPort: [
    { required: true, message: '请输入密码机端口', trigger: 'blur' }
  ],
  facilityType: [
    { required: true, message: '请选择密码设施类型', trigger: 'change' }
  ]
}

// 趋势分析
const trendTarget = ref(null)
const trendData = reactive({
  cpuUsage: 0,
  diskUsage: 0,
  memoryUsage: 0,
  totalCalls: 0,
  trendDetail: []
})
const chartRef = ref(null)
let chartInstance = null

// 工具函数
const getFacilityTypeTag = (type) => {
  const map = {
    '密码机': 'primary',
    '密码服务中台': 'success',
    '密码网关': 'warning',
    '密钥管理系统': 'danger',
    '安全认证网关': 'info'
  }
  return map[type] || 'info'
}

const getProgressColor = (val) => {
  if (val < 50) return '#67c23a'
  if (val < 75) return '#e6a23c'
  return '#f56c6c'
}

// 数据操作
// 获取过滤后的列表
const getFilteredList = () => {
  let list = [...mockDataList.value]
  if (filterName.value) {
    const kw = filterName.value.toLowerCase()
    list = list.filter(item => item.facilityName.toLowerCase().includes(kw))
  }
  if (filterIP.value) {
    list = list.filter(item => item.facilityIP.includes(filterIP.value))
  }
  if (filterIdentifier.value) {
    list = list.filter(item => item.facilityIdentifier.includes(filterIdentifier.value))
  }
  if (filterStatus.value) {
    list = list.filter(item => item.detectStatus === Number(filterStatus.value))
  }
  return list
}

// 刷新表格
const getTableData = () => {
  const filtered = getFilteredList()
  total.value = filtered.length
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  tableData.value = filtered.slice(start, end).map(item => ({
    ...item,
    visible: item.visible || false
  }))
}

// 重置筛选
const resetFilter = () => {
  filterName.value = ''
  filterIP.value = ''
  filterIdentifier.value = ''
  filterStatus.value = ''
  page.value = 1
  getTableData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const handleFilterChange = () => {
  page.value = 1
  getTableData()
}

// 刷新
const refreshData = () => {
  // 模拟刷新，更新一些随机数据
  mockDataList.value.forEach(item => {
    item.cpuUsage = random(10, 80)
    item.diskUsage = random(20, 85)
    item.memoryUsage = random(15, 75)
    item.totalCalls = random(300, 3000)
    item.trendDetail = generateTrendData()
  })
  getTableData()
  ElMessage.success('数据已刷新')
}

// 手动采集
const triggerCollect = () => {
  ElMessage.info('正在采集底层密码设施数据...')
  setTimeout(() => {
    refreshData()
    ElMessage.success('数据采集完成')
  }, 1200)
}

// 新增/编辑
const addService = () => {
  dialogFlag.value = 'add'
  Object.assign(serviceForm, {
    ID: null,
    facilityName: '',
    facilityIdentifier: generateIdentifier(),
    facilityIP: '',
    facilityPort: 8443,
    facilityType: '密码机',
    detectStatus: 1
  })
  addDialogVisible.value = true
  nextTick(() => {
    serviceFormRef.value?.resetFields()
  })
}

const openEdit = (row) => {
  dialogFlag.value = 'edit'
  Object.assign(serviceForm, {
    ID: row.ID,
    facilityName: row.facilityName,
    facilityIdentifier: row.facilityIdentifier,
    facilityIP: row.facilityIP,
    facilityPort: row.facilityPort,
    facilityType: row.facilityType,
    detectStatus: row.detectStatus
  })
  addDialogVisible.value = true
  nextTick(() => {
    serviceFormRef.value?.clearValidate()
  })
}

const closeDialog = () => {
  serviceFormRef.value?.resetFields()
  addDialogVisible.value = false
}

const submitService = async() => {
  await serviceFormRef.value?.validate((valid) => {
    if (!valid) return

    const now = getNowStr()

    if (dialogFlag.value === 'add') {
      // 新增
      const newItem = {
        ID: nextId++,
        facilityName: serviceForm.facilityName,
        facilityIdentifier: serviceForm.facilityIdentifier || generateIdentifier(),
        facilityIP: serviceForm.facilityIP,
        facilityPort: serviceForm.facilityPort,
        facilityType: serviceForm.facilityType,
        detectStatus: serviceForm.detectStatus,
        createTime: now,
        visible: false,
        cpuUsage: random(5, 40),
        diskUsage: random(10, 50),
        memoryUsage: random(8, 45),
        totalCalls: random(100, 800),
        trendDetail: generateTrendData()
      }
      mockDataList.value.unshift(newItem)
      ElMessage.success('新增采集服务成功')
    } else {
      // 编辑
      const index = mockDataList.value.findIndex(item => item.ID === serviceForm.ID)
      if (index !== -1) {
        mockDataList.value[index] = {
          ...mockDataList.value[index],
          facilityName: serviceForm.facilityName,
          facilityIP: serviceForm.facilityIP,
          facilityPort: serviceForm.facilityPort,
          facilityType: serviceForm.facilityType,
          detectStatus: serviceForm.detectStatus
        }
        ElMessage.success('编辑采集服务成功')
      }
    }
    closeDialog()
    getTableData()
  })
}

// 删除
const deleteService = (row) => {
  const index = mockDataList.value.findIndex(item => item.ID === row.ID)
  if (index !== -1) {
    mockDataList.value.splice(index, 1)
    row.visible = false
    ElMessage.success('删除成功')
    getTableData()
  }
}

// 检测状态切换
const switchStatus = async(row) => {
  const index = mockDataList.value.findIndex(item => item.ID === row.ID)
  if (index !== -1) {
    mockDataList.value[index].detectStatus = row.detectStatus
    const text = row.detectStatus === 1 ? '启用' : '停用'
    ElMessage.success(`检测状态已${text}`)
    getTableData()
  }
}

// 趋势分析
const openTrendAnalysis = (row) => {
  trendTarget.value = row
  // 从mock数据中获取趋势数据
  const source = mockDataList.value.find(item => item.ID === row.ID)
  if (source) {
    trendData.cpuUsage = source.cpuUsage ?? random(20, 75)
    trendData.diskUsage = source.diskUsage ?? random(30, 80)
    trendData.memoryUsage = source.memoryUsage ?? random(25, 70)
    trendData.totalCalls = source.totalCalls ?? random(500, 2000)
    trendData.trendDetail = source.trendDetail?.length ? source.trendDetail : generateTrendData()
  }
  trendDialogVisible.value = true
  // 等待DOM渲染完成后再初始化图表
  nextTick(() => {
    initChart()
  })
}

// 初始化ECharts图表
const initChart = () => {
  if (!chartRef.value) return
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  chartInstance = echarts.init(chartRef.value)

  const dates = trendData.trendDetail.map(item => item.label)
  const values = trendData.trendDetail.map(item => item.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const p = params[0]
        return `${p.name}<br/>调用次数：<strong>${p.value}</strong> 次`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '8%',
      top: '6%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false,
      axisLabel: {
        fontWeight: 500
      }
    },
    yAxis: {
      type: 'value',
      name: '调用次数',
      nameTextStyle: {
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#e8e8e8'
        }
      }
    },
    series: [
      {
        name: '接口调用',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          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)' }
          ])
        },
        itemStyle: {
          color: '#409eff'
        },
        data: values
      }
    ]
  }

  chartInstance.setOption(option)
  chartInstance.resize()
}

// 窗口变化自适应
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 监听趋势弹窗显示状态，在关闭时销毁图表
watch(trendDialogVisible, (val) => {
  if (!val && chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 生命周期
onMounted(() => {
  getTableData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
import { onBeforeUnmount } from 'vue'
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style lang="scss" scoped>
.filter-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 16px;
  padding: 0 4px;
  gap: 4px 0;

  .filter-label {
    font-size: 14px;
    color: #606266;
    margin-right: 4px;
    white-space: nowrap;
  }
}

.gva-btn-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 趋势分析样式 */
.trend-metrics {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 8px;

  .metric-card {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 16px 18px;
    text-align: center;
    border: 1px solid #e8ecf1;
    transition: box-shadow 0.2s;

    &:hover {
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    }

    .metric-label {
      font-size: 14px;
      color: #606266;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .metric-value {
      font-size: 22px;
      font-weight: 600;
      color: #303133;
      margin-top: 6px;
    }

    :deep(.el-progress) {
      .el-progress-bar__outer {
        border-radius: 10px;
        background-color: #e8ecf1;
      }
      .el-progress-bar__inner {
        border-radius: 10px;
      }
    }
  }

  .total-calls {
    background: linear-gradient(135deg, #f0f7ff 0%, #e8f0fe 100%);
    border-color: #d6e4ff;

    .total-calls-number {
      font-size: 32px;
      font-weight: 700;
      color: #409eff;
      line-height: 1.2;
    }
  }
}

.trend-chart {
  width: 100%;
  height: 280px;
  margin-top: 4px;
}

/* 响应式 */
@media (max-width: 768px) {
  .trend-metrics {
    grid-template-columns: repeat(2, 1fr);
  }
  .filter-area {
    .filter-label {
      font-size: 13px;
    }
    .el-input,
    .el-select {
      width: 140px !important;
    }
  }
}

@media (max-width: 480px) {
  .trend-metrics {
    grid-template-columns: 1fr;
  }
}
</style>
