/**
 * 充电桩大盘 - 数据分析模块
 */

import { CONFIG } from './config.js';
import { createTimedCache } from './perf-cache.js';
import { refreshIcons } from './utils.js';

// Chart.js 实例缓存
let hourlyChart = null;
let trendChart = null;
let rankChart = null;
let visitChart = null;

// 当前选择的天数
let currentDays = 7;
let currentGroupId = null;
const analyticsCache = createTimedCache(5 * 60 * 1000);

/**
 * 检查是否为 Mock 模式
 */
function isMockMode() {
  const params = new URLSearchParams(window.location.search);
  return params.get('mock') === 'true';
}

/**
 * 生成 Mock 分析数据
 */
function getMockAnalyticsData(type) {
  const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const connectors = [
    { name: '1号枪', type: 'AC' },
    { name: '2号桩', type: 'AC' },
    { name: '3号桩', type: 'AC' },
    { name: '16号枪', type: 'DC' },
    { name: '17号枪', type: 'DC' },
    { name: '18号桩(公牛)', type: 'DC' },
    { name: '19号桩(公牛)', type: 'DC' },
    { name: 'J01号桩(公牛)', type: 'AC' },
    { name: 'J02号桩(公牛)', type: 'AC' },
    { name: 'J03号桩(公牛)', type: 'AC' },
  ];

  // 根据 currentDays 调整数据量
  const multiplier = currentDays / 7;

  if (type === 'hourly') {
    const data = [];
    days.forEach(day => {
      for (let hour = 0; hour < 24; hour++) {
        // 根据时间段生成合理的使用率
        let baseUtil = 20;
        if (hour >= 9 && hour <= 18) baseUtil = 60 + Math.random() * 30;
        else if (hour >= 7 && hour <= 20) baseUtil = 40 + Math.random() * 20;
        else baseUtil = 10 + Math.random() * 15;

        // 周末使用率较低
        if (day === '周六' || day === '周日') {
          baseUtil *= 0.5;
        }

        // 根据 days 参数调整
        baseUtil *= multiplier;

        data.push({
          day,
          hour,
          utilization: Math.round(baseUtil * (0.8 + Math.random() * 0.4))
        });
      }
    });
    return data;
  }

  if (type === 'rank') {
    return connectors.map(c => {
      // 公牛桩名称映射
      let connectorName = c.name;
      if (c.name.includes('18号桩(公牛)')) {
        connectorName = 'Giant内部充电桩（SSL-18）01';
      } else if (c.name.includes('19号桩(公牛)')) {
        connectorName = 'Giant内部充电桩（SSL-19）01';
      } else if (c.name.includes('J01号桩(公牛)')) {
        connectorName = 'Giant内部充电桩（JSF-01）01';
      } else if (c.name.includes('J02号桩(公牛)')) {
        connectorName = 'Giant内部充电桩（JSF-02）01';
      } else if (c.name.includes('J03号桩(公牛)')) {
        connectorName = 'Giant内部充电桩（JSF-03）01';
      }
      return {
        connector_id: c.name,
        connector_name: connectorName,
        connector_type: c.type,
        utilization: Math.round((40 + Math.random() * 50) * multiplier)
      };
    }).sort((a, b) => b.utilization - a.utilization);
  }

  if (type === 'overview') {
    return {
      subscription_count: Math.round(12 * multiplier),
      ac_avg_charging_minutes: Math.round(180 + Math.random() * 60),
      dc_avg_charging_minutes: Math.round(45 + Math.random() * 30),
      grab_hour: '09:15',
      charging_sessions: Math.round(150 * multiplier),
      estimated_kwh: Math.round(2500 * multiplier)
    };
  }

  if (type === 'trend') {
    // 工作日 9:00-10:00 满载时刻
    const workdays = ['周一', '周二', '周三', '周四', '周五'];
    return workdays.map(day => ({
      day,
      minute: Math.floor(Math.random() * 55) + 5, // 5-59 分钟
      time: `9:${String(Math.floor(Math.random() * 55) + 5).padStart(2, '0')}`,
      full: true
    }));
  }

  if (type === 'visit') {
    const data = [];
    const today = new Date();
    for (let i = currentDays - 1; i >= 0; i--) {
      const d = new Date(today);
      d.setDate(d.getDate() - i);
      const dateStr = d.toISOString().split('T')[0];
      const isWeekend = d.getDay() === 0 || d.getDay() === 6;
      const basePv = isWeekend ? 30 : 80;
      const pv = Math.round(basePv + Math.random() * 50);
      const uv = Math.round(pv * (0.4 + Math.random() * 0.3));
      data.push({ date: dateStr, pv, uv });
    }
    return data;
  }

  return null;
}

/**
 * 初始化数据分析页面
 */
export async function initAnalytics(groupId) {
  currentGroupId = groupId;
  await loadAnalyticsData();
}

/**
 * 加载分析数据
 */
async function loadAnalyticsData() {
  let hourly, rank, overview, trend, visitData;

  // Mock 模式下使用模拟数据
  if (isMockMode()) {
    hourly = getMockAnalyticsData('hourly');
    rank = getMockAnalyticsData('rank');
    overview = getMockAnalyticsData('overview');
    trend = getMockAnalyticsData('trend');
    visitData = getMockAnalyticsData('visit');
  } else {
    try {
      [hourly, rank, overview, trend, visitData] = await Promise.all([
        fetchAPI(`/api/analytics/${currentGroupId}/hourly`),
        fetchAPI(`/api/analytics/${currentGroupId}/rank`),
        fetchAPI(`/api/analytics/${currentGroupId}/overview`),
        fetchAPI(`/api/analytics/${currentGroupId}/trend`),
        fetchAPI('/api/visit/history'),
      ]);
    } catch (e) {
      console.warn('API 请求失败:', e);
      hourly = [];
      rank = [];
      overview = {
        subscription_count: '-',
        ac_avg_charging_minutes: '-',
        dc_avg_charging_minutes: '-',
        grab_hour: '-',
        charging_sessions: '-',
        estimated_kwh: '-',
      };
      trend = [];
      visitData = [];
    }
  }

  renderOverviewCards(overview);
  renderHeatmap(hourly);
  renderTrendChart(trend);
  renderRankChart(rank);
  renderVisitChart(visitData);
  updateDateRangeDisplay();

  refreshIcons();
}

/**
 * 切换时间范围
 */
export function setAnalyticsDays(days) {
  if (days === currentDays) return;
  currentDays = days;

  // 更新按钮样式
  const baseClasses = 'px-3 py-1.5 rounded-full text-xs font-medium transition-all duration-300';
  [7, 14, 30].forEach(d => {
    const btn = document.getElementById(`days-${d}`);
    if (btn) {
      btn.className = baseClasses + (d === days
        ? ' bg-slate-800 text-white'
        : ' text-slate-500 hover:text-slate-300');
    }
  });

  // 显示 loading 状态
  showAnalyticsLoading();

  // 重新加载数据
  if (currentGroupId) {
    loadAnalyticsData();
  }
}

/**
 * 显示 loading 状态
 */
function showAnalyticsLoading() {
  // 概览卡片区域
  const overviewContainer = document.getElementById('overview-cards');
  if (overviewContainer) {
    overviewContainer.innerHTML = `
      <div class="col-span-6 flex items-center justify-center py-8">
        <div class="flex items-center gap-3 text-slate-400">
          <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span class="text-sm">加载中...</span>
        </div>
      </div>
    `;
  }

  // 热力图区域
  const heatmapContainer = document.getElementById('heatmap-container');
  if (heatmapContainer) {
    heatmapContainer.innerHTML = `
      <div class="flex items-center justify-center py-16 text-slate-500">
        <svg class="animate-spin h-5 w-5 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span class="text-sm">加载中...</span>
      </div>
    `;
  }

  // 图表区域 - 隐藏 canvas，显示 loading
  ['trend-chart', 'rank-chart', 'visit-chart'].forEach(id => {
    const canvas = document.getElementById(id);
    if (canvas) canvas.style.display = 'none';
    const empty = document.getElementById(`${id}-empty`);
    if (empty) {
      empty.classList.remove('hidden');
      empty.innerHTML = `
        <div class="flex items-center gap-2 text-slate-500">
          <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span class="text-sm">加载中...</span>
        </div>
      `;
    }
  });
}

/**
 * 更新日期范围显示
 */
function updateDateRangeDisplay() {
  const el = document.getElementById('analytics-date-range');
  if (!el) return;

  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - currentDays + 1);

  const fmt = (d) => `${d.getMonth() + 1}月${d.getDate()}日`;
  el.textContent = `${fmt(start)} - ${fmt(end)}，共 ${currentDays} 天数据`;

  // 更新图表标题
  const prefix = `近 ${currentDays} 天`;
  const heatmapTitle = document.getElementById('heatmap-title');
  const trendTitle = document.getElementById('trend-title');
  const visitChartTitle = document.getElementById('visit-chart-title');

  if (heatmapTitle) heatmapTitle.textContent = `${prefix}每小时使用热力图`;
  if (trendTitle) trendTitle.textContent = `${prefix}抢桩时刻分布`;
  if (visitChartTitle) visitChartTitle.textContent = `${prefix}访问统计`;
}

/**
 * API 请求封装
 */
async function fetchAPI(path) {
  // path 格式: /api/analytics/xxx
  // CONFIG.API_BASE 在 localhost 是 http://localhost:5001/api，非 localhost 是 /api
  // 所以需要去掉 path 开头的 /api，然后用 CONFIG.API_BASE 拼接
  const apiPath = path.replace(/^\/api/, '');
  const url = `${CONFIG.API_BASE}${apiPath}${path.includes('?') ? '&' : '?'}days=${currentDays}`;
  const cacheKey = `${url}`;
  const cached = analyticsCache.get(cacheKey);
  if (cached) return cached;

  const resp = await fetch(url);
  const data = await resp.json();
  if (!data.success) throw new Error(data.message);
  return analyticsCache.set(cacheKey, data.data);
}

/**
 * 渲染数据概览卡片
 */
function renderOverviewCards(data) {
  const container = document.getElementById('overview-cards');
  if (!container) return;

  const cards = [
    {
      icon: 'mail',
      label: '订阅用户',
      value: data.subscription_count || 0,
      unit: '人',
      color: 'purple',
    },
    {
      icon: 'clock',
      label: 'AC 平均充电',
      value: data.ac_avg_charging_minutes || 0,
      unit: '分钟',
      color: 'emerald',
    },
    {
      icon: 'clock',
      label: 'DC 平均充电',
      value: data.dc_avg_charging_minutes || 0,
      unit: '分钟',
      color: 'cyan',
    },
    {
      icon: 'alarm-clock',
      label: '抢桩截止',
      value: data.grab_hour || '--',
      unit: '',
      color: 'orange',
    },
    {
      icon: 'activity',
      label: '充电次数',
      value: data.charging_sessions || 0,
      unit: '次',
      color: 'blue',
    },
    {
      icon: 'battery',
      label: '预估电量',
      value: data.estimated_kwh || 0,
      unit: 'kWh',
      color: 'yellow',
    },
  ];

  const colorMap = {
    cyan: 'from-cyan-500/20 to-cyan-600/10 border-cyan-500/20 text-cyan-400',
    emerald: 'from-emerald-500/20 to-emerald-600/10 border-emerald-500/20 text-emerald-400',
    blue: 'from-blue-500/20 to-blue-600/10 border-blue-500/20 text-blue-400',
    purple: 'from-purple-500/20 to-purple-600/10 border-purple-500/20 text-purple-400',
    orange: 'from-orange-500/20 to-orange-600/10 border-orange-500/20 text-orange-400',
    yellow: 'from-yellow-500/20 to-yellow-600/10 border-yellow-500/20 text-yellow-400',
  };

  container.innerHTML = cards.map((c, i) => `
    <div class="bg-[#12141d]/80 backdrop-blur-md rounded-2xl border border-slate-700/50 p-4 animate-in" style="animation-delay: ${i * 0.05}s">
      <div class="flex items-center gap-2 mb-3">
        <div class="p-1.5 bg-gradient-to-br ${colorMap[c.color]} rounded-lg border">
          <i data-lucide="${c.icon}" class="w-4 h-4"></i>
        </div>
        <span class="text-xs text-slate-500 font-medium">${c.label}</span>
      </div>
      <div class="text-2xl font-bold text-white font-mono">
        ${typeof c.value === 'number' ? c.value.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 }) : c.value}<span class="text-sm font-normal text-slate-500 ml-1">${c.unit}</span>
      </div>
    </div>
  `).join('');
}

/**
 * 渲染热力图
 */
function renderHeatmap(data) {
  const container = document.getElementById('heatmap-container');
  if (!container || !data.length) return;

  const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const hours = Array.from({ length: 24 }, (_, i) => i);

  // 构建矩阵
  const matrix = {};
  data.forEach(d => {
    const key = `${d.day}-${d.hour}`;
    matrix[key] = d.utilization;
  });

  // 找最大值用于颜色映射
  const maxVal = Math.max(...data.map(d => d.utilization), 1);

  let html = '<div class="heatmap-grid">';

  // 表头：小时
  html += '<div class="heatmap-header"><div class="heatmap-label"></div>';
  hours.forEach(h => {
    html += `<div class="heatmap-hour">${h}</div>`;
  });
  html += '</div>';

  // 数据行
  days.forEach(day => {
    html += `<div class="heatmap-row"><div class="heatmap-label">${day}</div>`;
    hours.forEach(h => {
      const key = `${day}-${h}`;
      const val = matrix[key] || 0;
      const intensity = val / maxVal;
      const bg = getHeatmapColor(intensity);
      const textColor = intensity > 0.5 ? '#fff' : '#94a3b8';
      html += `<div class="heatmap-cell heatmap-cell-text" style="background:${bg};color:${textColor}" title="${day} ${h}:00 - 使用率 ${val}%">${val}</div>`;
    });
    html += '</div>';
  });

  // 图例
  html += `<div class="heatmap-legend">
    <span class="text-xs text-slate-500">低</span>
    <div class="heatmap-cell" style="background:${getHeatmapColor(0)}"></div>
    <div class="heatmap-cell" style="background:${getHeatmapColor(0.25)}"></div>
    <div class="heatmap-cell" style="background:${getHeatmapColor(0.5)}"></div>
    <div class="heatmap-cell" style="background:${getHeatmapColor(0.75)}"></div>
    <div class="heatmap-cell" style="background:${getHeatmapColor(1)}"></div>
    <span class="text-xs text-slate-500">高</span>
  </div>`;

  html += '</div>';
  container.innerHTML = html;
}

/**
 * 热力图颜色映射
 */
function getHeatmapColor(intensity) {
  if (intensity === 0) return 'rgba(30, 41, 59, 0.5)';
  if (intensity < 0.25) return 'rgba(52, 211, 153, 0.2)';
  if (intensity < 0.5) return 'rgba(52, 211, 153, 0.4)';
  if (intensity < 0.75) return 'rgba(52, 211, 153, 0.6)';
  return 'rgba(52, 211, 153, 0.9)';
}

/**
 * 渲染抢桩时刻趋势
 * 显示工作日 9:00-10:00 每天的满载时刻
 */
function renderTrendChart(trendData) {
  const ctx = document.getElementById('trend-chart');
  const emptyEl = document.getElementById('trend-chart-empty');
  if (!ctx) return;

  if (trendChart) trendChart.destroy();

  // 恢复空状态 HTML
  if (emptyEl) {
    emptyEl.innerHTML = `
      <div class="text-center text-slate-500">
        <i data-lucide="trending-up" class="w-12 h-12 mx-auto mb-2 opacity-30"></i>
        <p class="text-sm">暂无数据</p>
      </div>
    `;
  }

  // 检查空状态
  if (!trendData || trendData.length === 0) {
    ctx.style.display = 'none';
    if (emptyEl) emptyEl.classList.remove('hidden');
    return;
  }

  ctx.style.display = 'block';
  if (emptyEl) emptyEl.classList.add('hidden');

  // 工作日顺序
  const dayOrder = ['周一', '周二', '周三', '周四', '周五'];

  // 构建 day -> minute 映射
  const dayMap = {};
  trendData.forEach(d => {
    dayMap[d.day] = d.minute;
  });

  const labels = dayOrder;
  const values = dayOrder.map(day => dayMap[day] ?? null);

  trendChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels,
      datasets: [{
        label: '满载时刻',
        data: values,
        backgroundColor: values.map(v => v !== null ? 'rgba(52, 211, 153, 0.6)' : 'rgba(100, 116, 139, 0.3)'),
        borderColor: values.map(v => v !== null ? '#34d399' : '#64748b'),
        borderWidth: 1,
        borderRadius: 6,
        barPercentage: 0.6,
      }],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: (context) => {
              const val = context.raw;
              if (val === null) return '未满载';
              return `9:${String(val).padStart(2, '0')} 满载`;
            }
          }
        }
      },
      scales: {
        x: { grid: { display: false }, ticks: { color: '#94a3b8' } },
        y: {
          grid: { color: 'rgba(148, 163, 184, 0.1)' },
          ticks: {
            color: '#64748b',
            callback: v => v !== null ? `9:${String(v).padStart(2, '0')}` : ''
          },
          min: 0,
          max: 60,
          title: { display: true, text: '满载时刻 (分钟)', color: '#64748b' }
        },
      },
    },
  });
}

/**
 * 简化充电桩名称（与 render.js 保持一致）
 */
function simplifyConnectorName(name) {
  // 公牛桩名称匹配
  const sslMatch = name.match(/SSL-(\d+)/);
  if (sslMatch) {
    return `${sslMatch[1]}号桩(公牛)`;
  }
  const jsfMatch = name.match(/JSF-(\d+)/);
  if (jsfMatch) {
    return `J${jsfMatch[1]}号桩(公牛)`;
  }
  return name;
}

/**
 * 渲染使用率排名水平柱状图
 */
function renderRankChart(data) {
  const ctx = document.getElementById('rank-chart');
  const emptyEl = document.getElementById('rank-chart-empty');
  if (!ctx) return;

  if (rankChart) rankChart.destroy();

  // 恢复空状态 HTML
  if (emptyEl) {
    emptyEl.innerHTML = `
      <div class="text-center text-slate-500">
        <i data-lucide="trophy" class="w-12 h-12 mx-auto mb-2 opacity-30"></i>
        <p class="text-sm">暂无数据</p>
      </div>
    `;
  }

  // 检查空状态
  if (!data || data.length === 0) {
    ctx.style.display = 'none';
    if (emptyEl) emptyEl.classList.remove('hidden');
    return;
  }

  ctx.style.display = 'block';
  if (emptyEl) emptyEl.classList.add('hidden');

  // 简化充电桩名称
  const labels = data.map(d => simplifyConnectorName(d.connector_name));
  const values = data.map(d => d.utilization);
  const colors = data.map(d =>
    d.connector_type === 'DC' ? 'rgba(34, 211, 238, 0.7)' : 'rgba(52, 211, 153, 0.7)'
  );
  const borderColors = data.map(d =>
    d.connector_type === 'DC' ? '#22d3ee' : '#34d399'
  );

  rankChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels,
      datasets: [{
        label: '使用率',
        data: values,
        backgroundColor: colors,
        borderColor: borderColors,
        borderWidth: 1,
        borderRadius: 4,
        barPercentage: 0.7,
      }],
    },
    options: {
      indexAxis: 'y',
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { display: false },
      },
      scales: {
        x: {
          grid: { color: 'rgba(148, 163, 184, 0.1)' },
          ticks: { color: '#64748b', callback: v => v + '%' },
          min: 0,
          max: 100,
        },
        y: {
          grid: { display: false },
          ticks: { color: '#94a3b8', font: { size: 12 } },
        },
      },
    },
  });
}

/**
 * 渲染访问统计图表（UV/PV）
 */
function renderVisitChart(data) {
  const ctx = document.getElementById('visit-chart');
  const emptyEl = document.getElementById('visit-chart-empty');
  if (!ctx) return;

  if (visitChart) visitChart.destroy();

  // 恢复空状态 HTML
  if (emptyEl) {
    emptyEl.innerHTML = `
      <div class="text-center text-slate-500">
        <i data-lucide="users" class="w-12 h-12 mx-auto mb-2 opacity-30"></i>
        <p class="text-sm">暂无数据</p>
      </div>
    `;
  }

  if (!data || data.length === 0) {
    ctx.style.display = 'none';
    if (emptyEl) emptyEl.classList.remove('hidden');
    return;
  }

  ctx.style.display = 'block';
  if (emptyEl) emptyEl.classList.add('hidden');

  // 日期标签格式化
  const labels = data.map(d => {
    const parts = d.date.split('-');
    return `${parseInt(parts[1])}/${parseInt(parts[2])}`;
  });
  const pvValues = data.map(d => d.pv);
  const uvValues = data.map(d => d.uv);

  visitChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels,
      datasets: [
        {
          label: 'PV',
          data: pvValues,
          borderColor: '#fb7185',
          backgroundColor: 'rgba(251, 113, 133, 0.1)',
          borderWidth: 2,
          pointRadius: 4,
          pointBackgroundColor: '#fb7185',
          pointBorderColor: '#1e293b',
          pointBorderWidth: 2,
          tension: 0.3,
          fill: true,
        },
        {
          label: 'UV',
          data: uvValues,
          borderColor: '#22d3ee',
          backgroundColor: 'rgba(34, 211, 238, 0.1)',
          borderWidth: 2,
          pointRadius: 4,
          pointBackgroundColor: '#22d3ee',
          pointBorderColor: '#1e293b',
          pointBorderWidth: 2,
          tension: 0.3,
          fill: true,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        mode: 'index',
        intersect: false,
      },
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: (context) => {
              const label = context.dataset.label;
              return `${label}: ${context.raw} 次`;
            }
          }
        }
      },
      scales: {
        x: {
          grid: { display: false },
          ticks: { color: '#94a3b8', font: { size: 11 } },
        },
        y: {
          grid: { color: 'rgba(148, 163, 184, 0.1)' },
          ticks: { color: '#64748b' },
          min: 0,
          title: { display: true, text: '访问次数', color: '#64748b' },
        },
      },
    },
  });
}

/**
 * 销毁图表实例（切换页面时调用）
 */
export function destroyCharts() {
  if (hourlyChart) { hourlyChart.destroy(); hourlyChart = null; }
  if (trendChart) { trendChart.destroy(); trendChart = null; }
  if (rankChart) { rankChart.destroy(); rankChart = null; }
  if (visitChart) { visitChart.destroy(); visitChart = null; }
}
