<template>
  <el-dialog title="数据库测试连接" class="avue-dialog db" destroy-on-close append-to-body :close-on-click-modal="false"
    modal-append-to-body v-model="box" width="90%">
    <div class="db__box">
      <ul class="db__table">
        <div class="db__table-header">
          <span class="title">数据表</span>
          <div class="actions">
            <el-button type="primary" size="small" icon="el-icon-refresh" @click="handleGetTable">
              刷新
            </el-button>
          </div>
        </div>

        <div class="db__search">
          <el-input v-model="tableSearch" placeholder="搜索表名" clearable prefix-icon="el-icon-search">
          </el-input>
        </div>

        <div class="db__table-list">
          <div v-for="(item, index) in filteredTables" :key="index" class="table-item"
            :class="{ 'is-active': item.name == selectTable }" @click="handleGetColumn(item)">
            <i class="icon el-icon-tickets"></i>
            <span class="name" :title="item.name">{{ item.name }}</span>
          </div>
        </div>
      </ul>

      <ul class="db__column">
        <div class="db__column-header">
          <span class="title">数据字段</span>
          <div class="actions">
            <el-button type="primary" size="small" icon="el-icon-document-copy" @click="copyColumnNames">
              复制字段
            </el-button>
          </div>
        </div>

        <div class="db__search">
          <el-input v-model="columnSearch" placeholder="搜索字段" clearable prefix-icon="el-icon-search">
          </el-input>
        </div>

        <div class="db__column-list">
          <div v-for="(item, index) in filteredColumns" :key="index" class="column-item">
            <i class="icon el-icon-key" v-if="item.isPrimary"></i>
            <i class="icon el-icon-coin" v-else></i>
            <span class="name" :title="item.name">{{ item.name }}</span>
            <span class="type">{{ item.type }}</span>
          </div>
        </div>
      </ul>
      <div class="db__content">
        <div class="db__input">
          <div class="db__toolbar">
            <el-button-group>
              <el-button type="primary" icon="el-icon-video-play" @click="handleRun">
                运行
              </el-button>
              <el-button type="info" icon="el-icon-magic-stick" @click="handleFormat">
                格式化
              </el-button>
            </el-button-group>

            <el-button-group>
              <el-button type="success" icon="el-icon-download" @click="handleExport">
                导出结果
              </el-button>
            </el-button-group>
          </div>

          <monaco-editor v-model="sql" language="sql" height="200" @ctrlEnter="handleRun">
          </monaco-editor>
        </div>

        <!-- 执行信息 -->
        <div class="db__info" v-if="execInfo.time">
          <span>执行时间: {{ execInfo.time }}ms</span>
          <span>影响行数: {{ execInfo.affectedRows }}</span>
        </div>

        <!-- 自定义 tabs -->
        <div class="db__tabs">
          <div class="db__tabs-header">
            <div class="db__tabs-item" :class="{ 'is-active': activeTab === 'result' }" @click="activeTab = 'result'">
              查询结果
            </div>
            <div class="db__tabs-item" :class="{ 'is-active': activeTab === 'analysis' }"
              @click="activeTab = 'analysis'">
              数据分析
            </div>
            <div class="db__tabs-item" :class="{ 'is-active': activeTab === 'history' }" @click="activeTab = 'history'">
              执行历史
            </div>
            <div class="db__tabs-item" :class="{ 'is-active': activeTab === 'favorites' }"
              @click="activeTab = 'favorites'">
              收藏SQL
            </div>
          </div>

          <div class="db__tabs-content">
            <!-- 查询结果面板 -->
            <div v-show="activeTab === 'result'" class="db__result-content">
              <avue-crud style="width:100%;" v-if="data.length" :option="option" :data="data">
              </avue-crud>
              <div v-else class="db__empty">
                <el-empty description="暂无数据" image-size="40">
                  <template #description>
                    <p>{{ emptyText }}</p>
                  </template>
                </el-empty>
              </div>
            </div>

            <!-- 数据分析面板 -->
            <div v-show="activeTab === 'analysis'" class="db__analysis-content">
              <div class="analysis-header">
                <div class="stats-cards">
                  <div class="stats-card">
                    <div class="label">总记录数</div>
                    <div class="value">{{ data.length }}</div>
                  </div>
                  <div class="stats-card">
                    <div class="label">字段数</div>
                    <div class="value">{{ Object.keys(data[0] || {}).length }}</div>
                  </div>
                  <div class="stats-card">
                    <div class="label">执行耗时</div>
                    <div class="value">{{ execInfo.time }}ms</div>
                  </div>
                </div>
              </div>

              <div class="analysis-charts" v-if="data.length">
                <div class="chart-item">
                  <div class="chart-title">数据类型分布</div>
                  <el-progress v-for="(count, type) in dataTypeStats" :key="type"
                    :percentage="(count / data.length) * 100" :format="() => `${type}: ${count}`" :stroke-width="15"
                    :color="getChartColor(type)">
                  </el-progress>
                </div>

                <div class="chart-item">
                  <div class="chart-title">空值统计</div>
                  <el-table :data="nullValueStats" size="small" border>
                    <el-table-column prop="field" label="字段"></el-table-column>
                    <el-table-column prop="nullCount" label="空值数"></el-table-column>
                    <el-table-column prop="percentage" label="占比">
                      <template #default="{ row }">
                        {{ row.percentage }}%
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>

            <!-- 历史记录面板 -->
            <div v-show="activeTab === 'history'" class="db__history-content">
              <div v-for="(item, index) in sqlHistory" :key="index" class="history-item" @click="loadHistory(item)">
                <div class="history-item__header">
                  <span class="time">{{ item.time }}</span>
                  <span class="status" :class="item.status">
                    {{ item.status === 'success' ? '成功' : '失败' }}
                  </span>
                </div>
                <div class="sql">{{ item.sql }}</div>
                <div class="info" v-if="item.execTime">
                  执行时间: {{ item.execTime }}ms | 影响行数: {{ item.affectedRows }}
                </div>
              </div>
            </div>

            <!-- 收藏SQL面板 -->
            <div v-show="activeTab === 'favorites'" class="db__favorites-content">
              <div class="favorites-toolbar">
                <el-button type="primary" size="small" icon="el-icon-star-off" @click="saveFavorite">
                  收藏当前SQL
                </el-button>
                <el-input v-model="favoriteSearch" size="small" placeholder="搜索收藏的SQL" clearable>
                </el-input>
              </div>

              <div class="favorites-list">
                <div v-for="(item, index) in filteredFavorites" :key="index" class="favorite-item">
                  <div class="favorite-header">
                    <span class="name">{{ item.name }}</span>
                    <div class="actions">
                      <el-button type="text" icon="el-icon-edit" @click="editFavorite(item)">
                      </el-button>
                      <el-button type="text" icon="el-icon-delete" @click="deleteFavorite(index)">
                      </el-button>
                    </div>
                  </div>
                  <div class="sql" @click="loadFavorite(item)">{{ item.sql }}</div>
                  <div class="info">
                    <span class="time">收藏于: {{ item.time }}</span>
                    <span class="tags">
                      <el-tag v-for="tag in item.tags" :key="tag" size="mini">
                        {{ tag }}
                      </el-tag>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import MonacoEditor from '@/page/components/monaco-editor'
import { dynamicSql, getDetail } from "@/api/db";
import crypto from '@/utils/crypto'
import { format as sqlFormat } from 'sql-formatter'

export default {
  components: {
    MonacoEditor
  },
  data() {
    return {
      form: {},
      data: [],
      box: false,
      id: null,
      sql: '',
      selectTable: '',
      tableList: [],
      columnList: [],
      sqlHistory: [], // SQL执行历史
      execInfo: {    // 执行信息
        time: 0,
        affectedRows: 0
      },
      activeTab: 'result', // 当前激活的 tab
      emptyText: '请输入 SQL 查询语句并执行', // 添加空状态文本
      tableSearch: '',
      columnSearch: '',
      favoriteSearch: '',
      favorites: [], // 从 localStorage 加载
      chartColors: {
        number: 'var(--primary-color)',
        string: 'var(--success-color)',
        date: 'var(--warning-color)',
        boolean: 'var(--error-color)'
      }
    }
  },
  computed: {
    option() {
      let column = []
      let obj = this.data[0]
      if (obj) {
        Object.keys(obj).forEach(ele => {
          column.push({
            label: ele,
            prop: ele,
            overHidden: true
          })
        })
      }
      return {
        height: 300,
        menu: false,
        header: false,
        column
      }
    },
    filteredTables() {
      if (!this.tableSearch) return this.tableList;
      return this.tableList.filter(item =>
        item.name.toLowerCase().includes(this.tableSearch.toLowerCase())
      );
    },
    filteredColumns() {
      if (!this.columnSearch) return this.columnList;
      return this.columnList.filter(item =>
        item.name.toLowerCase().includes(this.columnSearch.toLowerCase())
      );
    },
    filteredFavorites() {
      if (!this.favoriteSearch) return this.favorites;
      const search = this.favoriteSearch.toLowerCase();
      return this.favorites.filter(item =>
        item.name.toLowerCase().includes(search) ||
        item.sql.toLowerCase().includes(search) ||
        item.tags.some(tag => tag.toLowerCase().includes(search))
      );
    },
    dataTypeStats() {
      if (!this.data.length) return {};
      const stats = {};
      const sample = this.data[0];

      Object.entries(sample).forEach(([key, value]) => {
        const type = this.getValueType(value);
        stats[type] = (stats[type] || 0) + 1;
      });

      return stats;
    },
    nullValueStats() {
      if (!this.data.length) return [];
      const stats = [];
      const fields = Object.keys(this.data[0]);

      fields.forEach(field => {
        const nullCount = this.data.filter(row =>
          row[field] === null || row[field] === undefined || row[field] === ''
        ).length;

        stats.push({
          field,
          nullCount,
          percentage: ((nullCount / this.data.length) * 100).toFixed(2)
        });
      });

      return stats;
    }
  },
  methods: {
    getSql(sql) {
      return JSON.stringify({
        id: this.id,
        sql: sql
      })
      return crypto.encrypt(JSON.stringify({
        id: this.id,
        sql: sql
      }))
    },
    handleOpen(id) {
      this.id = id;
      this.data = []
      this.sql = ''
      this.selectTable = ''
      this.tableList = []
      this.columnList = []
      getDetail(id).then(res => {
        this.form = res.data.data;
        this.handleGetTable()
        this.box = true
      })
    },
    handleRun() {
      if (!this.sql.trim()) {
        this.$message.warning('请输入 SQL 语句');
        return;
      }

      // 检查是否包含 SELECT 语句但未选择表
      if (this.sql.toUpperCase().includes('SELECT') && !this.selectTable) {
        this.$message.warning('请先选择一个数据表');
        return;
      }

      this.data = [];
      this.execInfo = { time: 0, affectedRows: 0 };
      this.activeTab = 'result';
      this.emptyText = '正在查询...';

      const startTime = Date.now();

      let sql = this.getSql(this.sql);
      dynamicSql(sql).then(res => {
        const list = res.data.data || [];

        this.execInfo = {
          time: Date.now() - startTime,
          affectedRows: list.length
        };

        this.data = list;
        this.emptyText = list.length ? '' : '查询结果为空';

        // 记录到历史
        this.addHistory(this.sql, 'success');
      }).catch(err => {
        this.$message.error('SQL执行失败：' + err.message);
        this.emptyText = 'SQL执行出错，请检查语法';
        this.addHistory(this.sql, 'error');
      });
    },
    handleGetColumn(item) {
      this.selectTable = item.name;
      this.columnSearch = ''; // 重置字段搜索

      let sqlList = {
        'com.mysql.cj.jdbc.Driver': `
          SELECT 
            COLUMN_NAME as name,
            COLUMN_TYPE as type,
            COLUMN_KEY = 'PRI' as isPrimary,
            IS_NULLABLE as nullable,
            COLUMN_COMMENT as comment
          FROM INFORMATION_SCHEMA.COLUMNS 
          WHERE TABLE_NAME = '${this.selectTable}'
        `,
        'com.microsoft.sqlserver.jdbc.SQLServerDriver': `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '${this.selectTable}';`,
        'org.postgresql.Driver': `SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_name ='${this.selectTable}'`,
        'oracle.jdbc.OracleDriver': `SELECT column_name as name,
                data_type,
                data_length,
                data_precision,
                data_scale,
                nullable,
                column_id
          FROM user_tab_columns
          WHERE table_name = '${this.selectTable}'
          ORDER BY column_id;`
      }
      let sql = this.getSql(sqlList[this.form.driverClass])
      dynamicSql(sql).then(res => {
        this.columnList = res.data.data.map(col => ({
          name: col.name ?? col.NAME,
          type: col.type,
          isPrimary: col.isPrimary === 1,
          nullable: col.nullable === 'YES',
          comment: col.comment
        }));
      })
      let pageList = {
        'com.mysql.cj.jdbc.Driver': `select * from ${this.selectTable} limit 0,10`,
        'com.microsoft.sqlserver.jdbc.SQLServerDriver': `SELECT TOP 10 * FROM ${this.selectTable};`,
        'org.postgresql.Driver': `SELECT * FROM ${this.selectTable} LIMIT 10;`, // PostgreSQL分页查询语法
        'oracle.jdbc.OracleDriver': `SELECT column_name as name,
                data_type,
                data_length,
                data_precision,
                data_scale,
                nullable,
                column_id
          FROM user_tab_columns
          WHERE table_name = '${this.selectTable}'
          ORDER BY column_id;`
      }
      this.sql = pageList[this.form.driverClass]
      this.handleRun()
    },
    handleGetTable() {
      let sqlList = {
        'com.mysql.cj.jdbc.Driver': 'SHOW TABLES',
        'com.microsoft.sqlserver.jdbc.SQLServerDriver': `SELECT name FROM sys.tables`,
        'org.postgresql.Driver': "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname='public';",
        'oracle.jdbc.OracleDriver': 'SELECT table_name FROM user_tables ORDER BY table_name;'
      }
      console.log(sqlList[this.form.driverClass])
      let sql = this.getSql(sqlList[this.form.driverClass])
      dynamicSql(sql).then(res => {
        let list = res.data.data;
        let result = []
        list.forEach(ele => {
          Object.keys(ele).forEach(key => {
            result.push({
              name: ele[key]
            })
          })
        })
        this.tableList = result
      })
    },
    // 格式化SQL
    handleFormat() {
      try {
        this.sql = sqlFormat(this.sql, {
          language: 'spark',
          tabWidth: 2,
          keywordCase: 'upper',
          linesBetweenQueries: 2,
        });
      } catch (err) {
        this.$message.error('SQL格式化失败');
      }
    },

    // 修改记录历史的方法,增加更多信息
    addHistory(sql, status = 'success') {
      this.sqlHistory.unshift({
        sql,
        time: new Date().toLocaleTimeString(),
        status,
        execTime: this.execInfo.time,
        affectedRows: this.execInfo.affectedRows
      });

      if (this.sqlHistory.length > 20) {
        this.sqlHistory.pop();
      }
    },

    // 加载历史记录
    loadHistory(item) {
      this.sql = item.sql;
    },

    // 导出结果
    handleExport() {
      if (!this.data.length) {
        this.$message.warning('没有可导出的数据');
        return;
      }

      const csv = this.convertToCSV(this.data);
      const blob = new Blob([csv], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `query_result_${new Date().getTime()}.csv`;
      a.click();
      window.URL.revokeObjectURL(url);
    },

    // 转换为CSV格式
    convertToCSV(data) {
      const headers = Object.keys(data[0]);
      const rows = data.map(row =>
        headers.map(header => JSON.stringify(row[header])).join(',')
      );
      return [headers.join(','), ...rows].join('\n');
    },

    copyColumnNames() {
      const names = this.columnList.map(col => col.name).join(',\n');
      navigator.clipboard.writeText(names).then(() => {
        this.$message.success('字段名已复制到剪贴板');
      }).catch(() => {
        this.$message.error('复制失败');
      });
    },

    async saveFavorite() {
      if (!this.sql.trim()) {
        this.$message.warning('请先输入SQL语句');
        return;
      }

      try {
        const { value: name } = await this.$prompt('请输入收藏名称', '收藏SQL', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: value => !!value.trim()
        });

        this.favorites.unshift({
          name: name.trim(),
          sql: this.sql,
          time: new Date().toLocaleString(),
          tags: []
        });

        this.saveFavoritesToStorage();
        this.$message.success('收藏成功');
      } catch (e) {
        // 用户取消操作
      }
    },

    async editFavorite(item) {
      try {
        const { value: newName } = await this.$prompt('请输入新的收藏名称', '编辑收藏', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: item.name,
          inputValidator: value => !!value.trim()
        });

        item.name = newName.trim();
        this.saveFavoritesToStorage();
        this.$message.success('编辑成功');
      } catch (e) {
        // 用户取消操作
      }
    },

    deleteFavorite(index) {
      this.$confirm('确定要删除这条收藏吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.favorites.splice(index, 1);
        this.saveFavoritesToStorage();
        this.$message.success('删除成功');
      }).catch(() => {
        // 用户取消操作
      });
    },

    loadFavorite(item) {
      this.sql = item.sql;
      this.activeTab = 'result'; // 切换到结果标签页
      this.$nextTick(() => {
        this.handleRun(); // 自动执行SQL
      });
    },

    getChartColor(type) {
      return this.chartColors[type] || '#909399';
    },

    getValueType(value) {
      if (value === null || value === undefined) return 'null';
      if (typeof value === 'number') return 'number';
      if (typeof value === 'boolean') return 'boolean';
      if (value instanceof Date) return 'date';
      return 'string';
    },

    saveFavoritesToStorage() {
      localStorage.setItem('sql_favorites', JSON.stringify(this.favorites));
    },

    loadFavoritesFromStorage() {
      try {
        const saved = localStorage.getItem('sql_favorites');
        this.favorites = saved ? JSON.parse(saved) : [];
      } catch (e) {
        this.favorites = [];
      }
    },
  },
  created() {
    this.loadFavoritesFromStorage();
  }
}
</script>

<style lang="scss">
.db {
  .el-dialog__body {
    padding: 0;
  }

  ul {
    box-sizing: border-box;
    position: absolute;
    padding: 20px;
    height: 100%;
    overflow: scroll;
    background-color: var(--bg-color-secondary);
    border-right: 2px solid var(--border-color-base);

    .is-active {
      color: var(--primary-color);
      font-weight: bold;
    }
  }

  li {
    padding-left: 8px;
    font-size: 12px;
    color: var(--text-color-primary);
    list-style: none;
    line-height: 32px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    &:hover {
      cursor: pointer;
    }
  }

  &__box {
    display: flex;
    height: 500px;
    background-color: var(--bg-color-secondary);
  }

  &__title {
    margin-bottom: 10px;
    font-weight: bold;
    color: var(--text-color-primary);
  }

  &__run {
    margin-right: 15px;
    float: right;
  }

  &__table {
    left: 0;
    width: 200px;
  }

  &__column {
    left: 200px;
    width: 250px;

    li {
      color: var(--text-color-secondary);
      display: flex;
      justify-content: space-between;
    }
  }

  &__content {
    height: 100%;
    left: 450px;
    position: absolute;
    width: calc(100% - 450px);
    display: flex;
    flex-direction: column;
    background-color: var(--bg-color-secondary);
    overflow: hidden;
  }

  &__input {}

  &__result {}

  &__toolbar {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    background: var(--bg-color-tertiary);
  }

  &__info {
    padding: 5px 10px;
    background: var(--bg-color-tertiary);
    color: var(--text-color-primary);
    font-size: 12px;

    span {
      margin-right: 15px;
    }
  }

  &__tabs {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;

    &-header {
      display: flex;
      background: var(--bg-color-tertiary);
      padding: 0 10px;
      border-bottom: 1px solid var(--border-color-base);
    }

    &-item {
      padding: 0 20px;
      line-height: 40px;
      color: var(--text-color-placeholder);
      cursor: pointer;
      position: relative;
      transition: color 0.3s;

      &:hover {
        color: var(--text-color-primary);
      }

      &.is-active {
        color: var(--primary-color);

        &:after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 2px;
          background: var(--primary-color);
        }
      }
    }

    &-content {
      flex: 1;
      overflow: hidden;
      position: relative;
    }
  }

  &__result-content,
  &__history-content,
  &__analysis-content,
  &__favorites-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 10px;
    overflow-y: auto;
    background: var(--bg-color-secondary);
  }

  .history-item {
    margin-bottom: 12px;
    padding: 12px;
    border-radius: 4px;
    background: var(--bg-color-tertiary);
    cursor: pointer;

    &:hover {
      background: var(--bg-color-hover);
    }

    &__header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;

      .time {
        color: var(--text-color-placeholder);
        font-size: 11px;
      }

      .status {
        padding: 2px 8px;
        border-radius: 3px;
        font-size: 11px;

        &.success {
          background: var(--success-color);
          color: var(--text-color-primary);
        }

        &.error {
          background: var(--error-color);
          color: var(--text-color-primary);
        }
      }
    }

    .sql {
      color: var(--text-color-regular);
      font-family: monospace;
      margin: 8px 0;
      white-space: pre-wrap;
      word-break: break-all;
      font-size: 12px;
    }

    .info {
      color: var(--text-color-placeholder);
      font-size: 11px;
    }
  }

  &__empty {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-color-placeholder);

    .empty-image {
      width: 120px;
      height: 120px;
    }

    :deep(.el-empty__description) {
      margin-top: 10px;

      p {
        color: var(--text-color-placeholder);
        font-size: 14px;
      }
    }
  }

  &__search {
    padding: 10px;

    .el-input {
      .el-input__inner {
        background: var(--bg-color-tertiary);
        border: 1px solid var(--border-color-base);
        color: var(--text-color-primary);

        &::placeholder {
          color: var(--text-color-placeholder);
        }
      }
    }
  }

  &__table-header,
  &__column-header {
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid var(--border-color-base);

    .title {
      font-weight: bold;
      color: var(--text-color-primary);
    }

    .actions {
      .el-button {
        padding: 4px 8px;
        font-size: 12px;
      }
    }
  }

  &__table-list,
  &__column-list {
    height: calc(100% - 100px);
    overflow-y: auto;
  }

  .table-item,
  .column-item {
    padding: 8px 12px;
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 12px;

    &:hover {
      background: var(--bg-color-tertiary);
    }

    &.is-active {
      background: var(--primary-light-color);
      color: var(--primary-color);
    }

    .icon {
      margin-right: 10px;
      font-size: 14px;
    }

    .name {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .type {
      margin-left: 10px;
      color: var(--text-color-placeholder);
      font-size: 11px;
    }
  }

  &__analysis-content {
    padding: 20px;

    .analysis-header {
      margin-bottom: 20px;
    }

    .stats-cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }

    .stats-card {
      background: var(--bg-color-tertiary);
      padding: 15px;
      border-radius: 8px;
      text-align: center;

      .label {
        color: var(--text-color-placeholder);
        font-size: 12px;
        margin-bottom: 8px;
      }

      .value {
        color: var(--text-color-primary);
        font-size: 20px;
        font-weight: bold;
      }
    }

    .analysis-charts {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 20px;
    }

    .chart-item {
      background: var(--bg-color-tertiary);
      padding: 20px;
      border-radius: 8px;

      .chart-title {
        color: var(--text-color-primary);
        font-size: 13px;
        margin-bottom: 12px;
      }
    }
  }

  &__favorites-content {
    padding: 20px;

    .favorites-toolbar {
      display: flex;
      gap: 10px;
      margin-bottom: 20px;
    }

    .favorite-item {
      background: var(--bg-color-tertiary);
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 16px;

      .favorite-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .name {
          color: var(--text-color-primary);
          font-weight: bold;
          font-size: 13px;
        }
      }

      .sql {
        color: var(--text-color-regular);
        font-family: monospace;
        font-size: 12px;
        padding: 12px;
        background: var(--bg-color-secondary);
        border-radius: 4px;
        margin: 12px 0;
        cursor: pointer;

        &:hover {
          background: var(--bg-color-hover);
        }
      }

      .info {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .time {
          color: var(--text-color-placeholder);
          font-size: 11px;
        }

        .tags {
          display: flex;
          gap: 6px;

          .el-tag {
            font-size: 11px;
            height: 20px;
            line-height: 18px;
          }
        }
      }
    }
  }
}
</style>