<template>
  <div class="modern-inventory-container" ref="appPanel">
    <!-- 背景装饰 -->
    <div class="grid-background"></div>
    <div class="gradient-orb orb-1"></div>
    <div class="gradient-orb orb-2"></div>
    <div class="gradient-orb orb-3"></div>

    <!-- 顶部统计卡片区域 -->
    <div class="stats-section">
      <div class="stat-card stat-card-primary">
        <div class="stat-icon-wrapper">
          <div class="stat-icon">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
        <div class="stat-content">
          <div class="stat-label">库存总价</div>
          <div class="stat-value">{{ totalMoney }}<span class="stat-unit">元</span></div>
        </div>
        <div class="stat-sparkle sparkle-1"></div>
        <div class="stat-sparkle sparkle-2"></div>
      </div>

      <div class="stat-card stat-card-secondary">
        <div class="stat-icon-wrapper">
          <div class="stat-icon">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect x="3" y="3" width="7" height="7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <rect x="14" y="3" width="7" height="7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <rect x="14" y="14" width="7" height="7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <rect x="3" y="14" width="7" height="7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
        <div class="stat-content">
          <div class="stat-label">总计数量</div>
          <div class="stat-value">{{ shelvesNum }}<span class="stat-unit">件</span></div>
        </div>
        <div class="stat-sparkle sparkle-1"></div>
        <div class="stat-sparkle sparkle-2"></div>
      </div>
    </div>

    <!-- 工具栏区域 -->
    <div class="toolbar-section" ref="toolPanel">
      <div class="toolbar-actions">
        <el-button
          class="modern-btn modern-btn-export"
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['system:stock:export']"
        >导出数据</el-button>
        <el-button
          class="modern-btn modern-btn-search"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          class="modern-btn modern-btn-refresh"
          icon="el-icon-refresh"
          size="small"
          @click="resetQuery"
        >刷新</el-button>
      </div>

      <right-toolbar
        ref="toolBarRef"
        @customCols="customColsHandler"
        :showSearch.sync="showSearch"
        showColumnsType="transfer"
        :columns="columns"
      ></right-toolbar>
    </div>

    <!-- 搜索区域 -->
    <transition name="search-expand">
      <div class="search-panel" ref="searchPanel" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="85px"
          class="modern-search-form"
        >
          <el-form-item label="仓库名称" prop="storageId">
            <el-select
              v-model="queryParams.storageId"
              placeholder="请选择仓库名称"
              clearable
            >
              <el-option
                v-for="storage in storageList"
                :key="storage.storageId"
                :label="storage.storageShortName"
                :value="storage.storageId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="库位编号" prop="locationId">
            <el-input
              v-model="queryParams.locationId"
              placeholder="请输入库位编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="物料编号" prop="goodsId">
            <el-input
              v-model="queryParams.goodsId"
              placeholder="请输入物料编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="规格型号" prop="specification">
            <el-input
              v-model="queryParams.specification"
              placeholder="请输入规格型号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="物料名称" prop="goodsName">
            <el-input
              v-model="queryParams.goodsName"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="物料描述" prop="recoil">
            <el-input
              v-model="queryParams.recoil"
              placeholder="请输入物料描述"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="需求部门" prop="needDept">
            <el-input
              v-model="queryParams.needDept"
              placeholder="请输入需求部门"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="需求人" prop="needPerson">
            <el-input
              v-model="queryParams.needPerson"
              placeholder="请输入需求人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="子需求编号" prop="salesOrderNumber">
            <el-input
              v-model="queryParams.salesOrderNumber"
              placeholder="请输入子需求编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="容器编号" prop="ctl">
            <el-input
              v-model="queryParams.ctl"
              placeholder="请输入容器编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="入库时间" prop="date">
            <el-date-picker
              v-model="queryParams.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @keyup.enter.native="handleQuery"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="库级选择" prop="levelType">
            <el-select
              v-model="queryParams.levelType"
              placeholder="请选库级"
              clearable>
              <el-option
                v-for="dict in dict.type.level_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 表格区域 -->
    <div class="table-section" ref="mainTablePanel">
      <div class="table-scroll-wrapper">
        <el-table
          :key="rndKey"
          ref="filterTable"
          v-loading="loading"
          size="small"
          height="650px"
          :data="tMiStockList"
          @header-dragend="handleHeaderDragEnd"
          show-summary
          :summary-method="getSummaries"
          @selection-change="handleSelectionChange"
          :row-class-name="getRowClassName"
          class="modern-table"
        >
        <el-table-column type="selection" width="55" align="center" fixed="left"/>
        <el-table-column
          v-for="item in columns"
          sortable
          :key="item.seq"
          :label="item.label"
          align="center"
          :prop="item.columnName"
          v-if="item.visible"
          :min-width="item.minWidth || 130"
          :filters="item.filters"
          :filter-method="filterHandler"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <dict-tag
              v-if="item.columnName === 'status'"
              :options="dict.type.common_status"
              :value="scope.row[item.columnName]"
            />
            <dict-tag
              v-else-if="item.columnName === 'levelType'"
              :options="dict.type.level_type"
              :value="scope.row[item.columnName]"
            />
            <span v-else-if="['price', 'totalMoney'].includes(item.columnName)" class="money-cell">
              {{ formatCurrency(scope.row[item.columnName]) }}
            </span>
            <span v-else>{{ scope.row[item.columnName] }}</span>
          </template>
        </el-table-column>
      </el-table>
      </div>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import {
  addStock,
  delStock,
  getStock,
  listStock,
  updateStock,
  listTotal
} from "@/api/system/tMiStock";
import {selectStorageList} from "@/api/system/storage";
import TableMixin from "@/api/tableMixin";
import * as echarts from 'echarts';
import {listCOLUMN} from "@/api/system/column";

export default {
  name: "TMiStock",
  dicts: ["storage_classification", "common_status", "level_type"],
  mixins: [TableMixin],
  data() {
    return {
      rndKey: 0,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      tMiStockList: [],
      tMiStockLists: [],
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "tMiStock",
      rightToolbarShow: false,
      tableNo: 0,
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 100,
      },
      storageList: [],
      form: {},
      rules: {},
      columns: [],
      charts: {
        inventoryDistribution: null,
        inventoryTrend: null,
        levelTypeDistribution: null,
        monthlyValueTrend: null
      },
      totalMoney: '',
      shelvesNum: '',
      selectedRowKeys: [],
    };
  },
  created() {
    this.getStorageList();
    this.getList();
    this.getTotal();
  },
  mounted() {
    this.computedTableHeight();
    this.generateFilters();
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  watch: {
    'showSearch': function () {
      this.computedTableHeight();
    },
    tMiStockLists: {
      handler() {
        this.$nextTick(() => {
          this.updateCharts();
        });
      },
      deep: true
    },
    'tMiStockList': {
      handler(newList) {
        newList.forEach(item => {
          const price = parseFloat(item.price) || 0;
          const shelvesNum = parseFloat(item.shelvesNum) || 0;
          item.totalMoney = (price * shelvesNum).toFixed(2);
        });
      },
      deep: true
    }
  },
  methods: {
    getHideColumn() {
      var queryHideColumnParams = {
        pageNum: 1,
        pageSize: 100,
        businessCode: this.businessCodeTrk,
        tableNo: this.tableNo
      };
      listCOLUMN(queryHideColumnParams).then(response => {
        if (response.rows.length > 0) {
          var row = response.rows[0];
          var columnHide = row.columnHide.split(",");
          if (columnHide.length > 0) {
            for (let item in this.columns) {
              if (columnHide.indexOf(this.columns[item].columnName) > -1) {
                this.columns[item].visible = false;
              }
            }
          }
        }
        this.rightToolbarShow = true;
      });
    },
    getStorageList() {
      selectStorageList({}).then((response) => {
        if (response.code == 200) {
          this.storageList = [];
          response.data.forEach((element, index) => {
            this.storageList.push({...element, key: element.id || `unique-${index}`});
          });
        } else {
          this.$modal.msgError("查询仓库失败");
        }
      });
    },
    handleHeaderDragEnd(newWidth, oldWidth, column, event) {
      this.columns.forEach((obj) => {
        if (obj.columnName === column.property) obj.width = newWidth;
      });
      this.$refs.toolBarRef.saveConfig(this.columns);
    },
    customColsHandler(columns) {
      this.columns = columns;
      this.rndKey = Math.random();
    },
    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel ? this.$refs.searchPanel.clientHeight : 0;
        var tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;
        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = tablePanelHeight - 25 + "px";
      });
    },
    async getTotal() {
      try {
        const response = await listTotal(this.queryParams);
        this.tMiStockLists = response.data;
        this.totalMoney = this.tMiStockLists.reduce((sum, item) => {
          return sum + (parseFloat(item.totalMoney) || 0);
        }, 0).toFixed(2);
        this.shelvesNum = this.tMiStockLists.reduce((sum, item) => {
          return sum + (parseFloat(item.shelvesNum) || 0);
        }, 0).toFixed(2);
      } catch (error) {
        console.error('Error loading total data:', error);
      }
    },
    getList() {
      this.loading = true;
      listStock(this.queryParams).then((response) => {
        if (this.columns.length === 0) {
          this.columns = response.columns.map(col => ({
            ...col,
            minWidth: this.getColumnMinWidth(col.columnName)
          }));
        }
        this.tMiStockList = response.rows;
        this.total = response.total;
        this.generateFilters();
        this.loading = false;
      });
    },
    getColumnMinWidth(columnName) {
      // 为不同类型的列设置合理的最小宽度，确保内容适度显示
      const widthMap = {
        'goodsId': 160,           // 物料编号
        'goodsName': 200,         // 物料名称
        'specification': 160,     // 规格型号
        'recoil': 220,           // 物料描述
        'locationId': 130,       // 库位编号
        'storageShortName': 130, // 仓库简称
        'storageName': 160,      // 仓库名称
        'warehouseName': 130,    // 库房名称
        'shelvesNum': 110,       // 数量
        'price': 110,            // 单价
        'totalMoney': 130,       // 总金额
        'needDept': 140,         // 需求部门
        'needPerson': 110,       // 需求人
        'salesOrderNumber': 160, // 子需求编号
        'ctl': 130,              // 容器编号
        'levelType': 110,        // 库级
        'status': 100,           // 状态
        'wareDate': 140,         // 入库日期
        'operatorName': 110,     // 操作人
      };
      return widthMap[columnName] || 130; // 默认最小宽度增加到130
    },
    generateFilters() {
      this.columns.forEach(column => {
        let uniqueValues;
        if (column.columnName === 'status') {
          uniqueValues = [...new Set(this.tMiStockList.map(item => item[column.columnName]))];
          column.filters = uniqueValues.map(value => ({
            text: this.dict.type.common_status.find(status => status.value === value)?.label || value,
            value
          }));
          column.filterMethod = (value, row) => row[column.columnName] === value;
          column.formatter = (row, column, cellValue, index) => {
            return this.dict.type.common_status.find(status => status.value === cellValue)?.label || cellValue;
          };
        } else {
          uniqueValues = [...new Set(this.tMiStockList.map(item => item[column.columnName]))];
          column.filters = uniqueValues.map(value => ({text: value, value}));
          column.filterMethod = (value, row) => row[column.columnName] === value;
        }
      });
    },
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] === value;
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      const sumFields = ['shelvesNum', 'price', "totalMoney"];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
        } else if (sumFields.includes(column.property)) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = this.formatCurrency(sums[index]);
          } else {
            sums[index] = ' ';
          }
        } else {
          sums[index] = '/';
        }
      });
      return sums;
    },
    formatCurrency(value) {
      return Number(value).toFixed(2);
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getTotal();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
      this.$refs.filterTable.clearFilter();
    },
    handleExport() {
      this.download(
        "system/stock/export",
        {
          ...this.queryParams,
        },
        `tMiStock_${new Date().getTime()}.xlsx`
      );
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectedRowKeys = selection.map(item => item.id)
    },
    getRowClassName({ row }) {
      if (this.selectedRowKeys.includes(row.id)) {
        return 'selected-row'
      }
      return ''
    },
    initCharts() {
      if (this.$refs.inventoryDistributionChart) {
        this.charts.inventoryDistribution = echarts.init(this.$refs.inventoryDistributionChart);
      }
      if (this.$refs.inventoryTrendChart) {
        this.charts.inventoryTrend = echarts.init(this.$refs.inventoryTrendChart);
      }
      if (this.$refs.levelTypeDistributionChart) {
        this.charts.levelTypeDistribution = echarts.init(this.$refs.levelTypeDistributionChart);
      }
      if (this.$refs.monthlyValueTrendChart) {
        this.charts.monthlyValueTrend = echarts.init(this.$refs.monthlyValueTrendChart);
      }
    },
    updateCharts() {
      this.updateInventoryDistributionChart();
      this.updateInventoryTrendChart();
      this.updateLevelTypeDistributionChart();
      this.updateMonthlyValueTrendChart();
    },
    updateInventoryDistributionChart() {
      if (!this.charts.inventoryDistribution || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const storageData = this.tMiStockLists.reduce((acc, item) => {
        acc[item.storageShortName] = (acc[item.storageShortName] || 0) + 1;
        return acc;
      }, {});

      const chartData = Object.keys(storageData).map(key => ({
        name: `仓库 ${key}`,
        value: storageData[key]
      }));

      const option = {
        title: {
          text: '库存分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '库存分布',
            type: 'pie',
            radius: '50%',
            data: chartData
          }
        ]
      };

      this.charts.inventoryDistribution.setOption(option);
    },
    updateInventoryTrendChart() {
      if (!this.charts.inventoryTrend || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const monthlyData = this.tMiStockLists.reduce((acc, item) => {
        const date = new Date(item.wareDate);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;

        if (!acc[monthKey]) {
          acc[monthKey] = {
            totalItems: 0,
            totalMoney: 0
          };
        }

        acc[monthKey].totalItems += 1;
        acc[monthKey].totalMoney += Number(item.totalMoney);

        return acc;
      }, {});

      const sortedMonths = Object.keys(monthlyData).sort().slice(-3);
      const itemsData = [];
      const moneyData = [];

      sortedMonths.forEach(month => {
        const data = monthlyData[month];
        itemsData.push(data.totalItems);
        moneyData.push(this.formatCurrency(data.totalMoney));
      });

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['库存条数', '库存金额']
        },
        xAxis: [
          {
            type: 'category',
            data: sortedMonths,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '库存条数',
            min: 0,
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '库存金额',
            min: 0,
            axisLabel: {
              formatter: '{value} 元'
            }
          }
        ],
        series: [
          {
            name: '库存条数',
            type: 'bar',
            data: itemsData
          },
          {
            name: '库存金额',
            type: 'line',
            yAxisIndex: 1,
            data: moneyData
          }
        ]
      };

      this.charts.inventoryTrend.setOption(option);
    },
    updateLevelTypeDistributionChart() {
      if (!this.charts.levelTypeDistribution || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const levelTypeData = this.tMiStockLists.reduce((acc, item) => {
        const levelType = this.dict.type.level_type.find(dict =>
          dict.value === item.levelType)?.label || '未知';
        acc[levelType] = (acc[levelType] || 0) + 1;
        return acc;
      }, {});

      const chartData = Object.keys(levelTypeData).map(key => ({
        name: key,
        value: levelTypeData[key]
      }));

      const option = {
        title: {
          text: '库级分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '库级分布',
            type: 'pie',
            radius: '50%',
            data: chartData
          }
        ]
      };

      this.charts.levelTypeDistribution.setOption(option);
    },
    updateMonthlyValueTrendChart() {
      if (!this.charts.monthlyValueTrend || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const monthlyData = this.tMiStockLists.reduce((acc, item) => {
        const date = new Date(item.wareDate);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;

        if (!acc[monthKey]) {
          acc[monthKey] = 0;
        }

        acc[monthKey] += Number(item.totalMoney);

        return acc;
      }, {});

      const sortedMonths = Object.keys(monthlyData).sort();
      const valueData = sortedMonths.map(month => this.formatCurrency(monthlyData[month]));

      const option = {
        title: {
          text: '月度金额趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c} 元'
        },
        xAxis: {
          type: 'category',
          data: sortedMonths
        },
        yAxis: {
          type: 'value',
          name: '金额',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        series: [{
          data: valueData,
          type: 'line',
          smooth: true
        }]
      };

      this.charts.monthlyValueTrend.setOption(option);
    },
  }
};
</script>

<style lang="scss" scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap');

// 丰富的配色方案
$bg-light: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%);
$bg-white: #ffffff;
$bg-card: #ffffff;
$bg-hover: #f0f9ff;
$bg-stripe: #fafbfc;

// 主色系 - 蓝色到青色
$primary-start: #0ea5e9;
$primary-end: #06b6d4;
$primary-light: #e0f2fe;

// 次色系 - 紫色到粉色
$secondary-start: #8b5cf6;
$secondary-end: #ec4899;
$secondary-light: #fae8ff;

// 强调色系 - 橙色到红色
$accent-start: #f97316;
$accent-end: #ef4444;
$accent-light: #ffedd5;

// 绿色系 - 绿松石
$success-start: #14b8a6;
$success-end: #10b981;
$success-light: #d1fae5;

// 文本颜色
$text-primary: #0f172a;
$text-secondary: #64748b;
$text-muted: #94a3af;

// 边框和阴影
$border-color: #e2e8f0;
$border-hover: #cbd5e1;
$shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.06);
$shadow-md: 0 4px 16px rgba(0, 0, 0, 0.08);
$shadow-lg: 0 12px 40px rgba(0, 0, 0, 0.12);
$shadow-color-blue: 0 8px 32px rgba(14, 165, 233, 0.25);
$shadow-color-purple: 0 8px 32px rgba(139, 92, 246, 0.25);
$shadow-color-orange: 0 8px 32px rgba(249, 115, 22, 0.25);
$shadow-color-teal: 0 8px 32px rgba(20, 184, 166, 0.25);

.modern-inventory-container {
  position: relative;
  min-height: 100vh;
  background: $bg-light;
  padding: 24px;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  color: $text-primary;
  overflow-x: hidden;

  // 背景网格装饰
  .grid-background {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      linear-gradient(rgba(14, 165, 233, 0.04) 1.5px, transparent 1.5px),
      linear-gradient(90deg, rgba(14, 165, 233, 0.04) 1.5px, transparent 1.5px);
    background-size: 40px 40px;
    pointer-events: none;
    z-index: 0;
  }

  // 多彩渐变装饰球
  .gradient-orb {
    position: fixed;
    border-radius: 50%;
    filter: blur(100px);
    opacity: 0.15;
    pointer-events: none;
    z-index: 0;
    animation: float 30s ease-in-out infinite;

    &.orb-1 {
      width: 500px;
      height: 500px;
      background: radial-gradient(circle, $primary-start, transparent);
      top: -200px;
      right: -200px;
    }

    &.orb-2 {
      width: 450px;
      height: 450px;
      background: radial-gradient(circle, $secondary-start, transparent);
      bottom: -180px;
      left: -180px;
      animation-delay: -15s;
    }

    &.orb-3 {
      width: 400px;
      height: 400px;
      background: radial-gradient(circle, $success-start, transparent);
      top: 50%;
      left: 50%;
      animation-delay: -7s;
    }
  }

  @keyframes float {
    0%, 100% { transform: translate(0, 0) rotate(0deg); }
    25% { transform: translate(50px, -50px) rotate(90deg); }
    50% { transform: translate(-30px, 40px) rotate(180deg); }
    75% { transform: translate(40px, -30px) rotate(270deg); }
  }

  > * {
    position: relative;
    z-index: 1;
  }

  // 统计卡片 - 使用鲜艳的渐变色
  .stats-section {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 20px;
    margin-bottom: 24px;
    animation: slideDown 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);

    .stat-card {
      position: relative;
      background: $bg-card;
      border: 2px solid transparent;
      border-radius: 20px;
      padding: 30px;
      display: flex;
      align-items: center;
      gap: 24px;
      overflow: hidden;
      box-shadow: $shadow-md;
      transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);

      &::before {
        content: '';
        position: absolute;
        inset: 0;
        border-radius: 20px;
        padding: 2px;
        background: linear-gradient(135deg, transparent 0%, currentColor 100%);
        -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        opacity: 0;
        transition: opacity 0.4s;
      }

      &:hover {
        transform: translateY(-8px) scale(1.02);
        box-shadow: $shadow-lg;

        &::before {
          opacity: 1;
        }

        .stat-icon-wrapper {
          transform: scale(1.15) rotate(10deg);
        }

        .stat-sparkle {
          animation: sparkle 1.5s ease-in-out infinite;
        }
      }

      &.stat-card-primary {
        color: $primary-start;

        &:hover {
          box-shadow: $shadow-color-blue;
        }

        .stat-icon-wrapper {
          background: linear-gradient(135deg, $primary-start, $primary-end);
        }

        .stat-value {
          background: linear-gradient(135deg, $primary-start, $primary-end);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      }

      &.stat-card-secondary {
        color: $secondary-start;

        &:hover {
          box-shadow: $shadow-color-purple;
        }

        .stat-icon-wrapper {
          background: linear-gradient(135deg, $secondary-start, $secondary-end);
        }

        .stat-value {
          background: linear-gradient(135deg, $secondary-start, $secondary-end);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      }

      .stat-icon-wrapper {
        position: relative;
        flex-shrink: 0;
        width: 72px;
        height: 72px;
        border-radius: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: $shadow-md;
        transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);

        .stat-icon {
          color: white;

          svg {
            width: 36px;
            height: 36px;
            filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
          }
        }
      }

      .stat-content {
        flex: 1;
        min-width: 0;

        .stat-label {
          font-size: 13px;
          font-weight: 600;
          color: $text-secondary;
          margin-bottom: 10px;
          text-transform: uppercase;
          letter-spacing: 1px;
        }

        .stat-value {
          font-family: 'JetBrains Mono', monospace;
          font-size: 36px;
          font-weight: 800;
          line-height: 1;
          letter-spacing: -1px;

          .stat-unit {
            font-size: 18px;
            font-weight: 600;
            margin-left: 8px;
            opacity: 0.8;
          }
        }
      }

      .stat-sparkle {
        position: absolute;
        width: 8px;
        height: 8px;
        background: currentColor;
        border-radius: 50%;
        opacity: 0;

        &.sparkle-1 {
          top: 20%;
          right: 15%;
        }

        &.sparkle-2 {
          bottom: 25%;
          right: 20%;
          animation-delay: 0.5s;
        }
      }
    }
  }

  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateY(-30px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  @keyframes sparkle {
    0%, 100% {
      opacity: 0;
      transform: scale(0);
    }
    50% {
      opacity: 0.8;
      transform: scale(1.5);
    }
  }

  // 工具栏
  .toolbar-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 18px 24px;
    background: $bg-card;
    border: 1px solid $border-color;
    border-radius: 16px;
    box-shadow: $shadow-sm;
    animation: slideDown 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) 0.1s both;

    .toolbar-actions {
      display: flex;
      gap: 12px;
    }
  }

  // 多彩按钮设计
  .modern-btn {
    padding: 10px 24px !important;
    border-radius: 10px !important;
    font-weight: 600 !important;
    font-size: 13px !important;
    border: none !important;
    color: white !important;
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) !important;
    box-shadow: $shadow-sm !important;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      inset: 0;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), transparent);
      opacity: 0;
      transition: opacity 0.3s;
    }

    &:hover {
      transform: translateY(-3px) scale(1.05);
      box-shadow: $shadow-md !important;

      &::before {
        opacity: 1;
      }
    }

    &:active {
      transform: translateY(-1px) scale(1.02);
    }

    &.modern-btn-export {
      background: linear-gradient(135deg, $accent-start, $accent-end) !important;

      &:hover {
        box-shadow: $shadow-color-orange !important;
      }
    }

    &.modern-btn-search {
      background: linear-gradient(135deg, $primary-start, $primary-end) !important;

      &:hover {
        box-shadow: $shadow-color-blue !important;
      }
    }

    &.modern-btn-refresh {
      background: linear-gradient(135deg, $success-start, $success-end) !important;

      &:hover {
        box-shadow: $shadow-color-teal !important;
      }
    }
  }

  // 搜索面板
  .search-panel {
    margin-bottom: 20px;
    padding: 28px;
    background: $bg-card;
    border: 1px solid $border-color;
    border-radius: 16px;
    box-shadow: $shadow-sm;
    animation: slideDown 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) 0.2s both;

    .modern-search-form {
      ::v-deep .el-form-item {
        margin-bottom: 16px;

        .el-form-item__label {
          color: $text-secondary;
          font-weight: 600;
          font-size: 13px;
        }

        .el-input__inner,
        .el-select .el-input__inner,
        .el-date-editor .el-input__inner {
          background: $bg-white;
          border: 2px solid $border-color;
          border-radius: 10px;
          color: $text-primary;
          transition: all 0.3s;
          font-size: 13px;

          &:hover {
            border-color: $border-hover;
            box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.05);
          }

          &:focus {
            border-color: $primary-start;
            box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.1);
          }

          &::placeholder {
            color: $text-muted;
          }
        }
      }
    }
  }

  .search-expand-enter-active,
  .search-expand-leave-active {
    transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
    max-height: 800px;
    overflow: hidden;
  }

  .search-expand-enter,
  .search-expand-leave-to {
    opacity: 0;
    max-height: 0;
    transform: translateY(-20px);
  }

  // 灵动优雅的表格
  .table-section {
    margin-bottom: 20px;
    animation: slideDown 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) 0.3s both;

    .table-scroll-wrapper {
      overflow-x: auto;
      overflow-y: hidden;
      border-radius: 16px;
      background: $bg-card;
      box-shadow: $shadow-md;
      position: relative;

      // 优雅的滚动条样式
      &::-webkit-scrollbar {
        height: 12px;
      }

      &::-webkit-scrollbar-track {
        background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);
        border-radius: 0 0 16px 16px;
        margin: 0 16px;
      }

      &::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, $primary-start, $primary-end);
        border-radius: 10px;
        border: 2px solid transparent;
        background-clip: padding-box;
        transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        box-shadow: 0 2px 8px rgba(14, 165, 233, 0.3);

        &:hover {
          background: linear-gradient(135deg, darken($primary-start, 5%), darken($primary-end, 5%));
          box-shadow: 0 4px 12px rgba(14, 165, 233, 0.4);
          transform: scaleY(1.2);
        }

        &:active {
          background: linear-gradient(135deg, darken($primary-start, 10%), darken($primary-end, 10%));
        }
      }

      // 滚动条按钮（如果需要）
      &::-webkit-scrollbar-button {
        display: none;
      }
    }

    ::v-deep .modern-table {
      background: $bg-card;
      border-radius: 16px;
      overflow: visible;
      box-shadow: none;
      width: 100%;

      // 隐藏默认的外边框
      &::before,
      &::after {
        display: none;
      }

      .el-table__border-left-patch {
        display: none;
      }

      // 确保表格列宽自适应且对齐
      .el-table__header-wrapper,
      .el-table__body-wrapper,
      .el-table__footer-wrapper {
        .el-table__header,
        .el-table__body,
        .el-table__footer {
          width: 100% !important;
        }
      }

      // 统一所有单元格的内部padding控制
      th, td {
        .cell {
          padding-left: 0 !important;
          padding-right: 0 !important;
        }
      }

      // 确保行高度自动计算
      .el-table__row {
        height: auto !important;
      }

      // Checkbox列样式优化
      .el-table-column--selection {
        .cell {
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .el-checkbox {
          margin: 0;

          .el-checkbox__inner {
            border-radius: 6px;
            border: 2px solid rgba(14, 165, 233, 0.3);
            transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);

            &:hover {
              border-color: $primary-start;
              transform: scale(1.1);
            }
          }

          &.is-checked {
            .el-checkbox__inner {
              background: linear-gradient(135deg, $primary-start, $primary-end);
              border-color: $primary-start;
            }
          }
        }
      }

      // 固定列样式 - 确保完美对齐
      .el-table__fixed {
        height: 100% !important;
        background: transparent;
        z-index: 3;

        &::before {
          display: none;
        }

        // 添加右侧阴影分隔效果
        &::after {
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          width: 3px;
          background: linear-gradient(90deg,
            rgba(14, 165, 233, 0.15) 0%,
            rgba(14, 165, 233, 0.05) 50%,
            transparent 100%
          );
          pointer-events: none;
        }

        .el-table__fixed-header-wrapper {
          background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);

          th {
            background: transparent !important;
            border-right: 2px solid rgba(14, 165, 233, 0.25);
            border-bottom: 2px solid rgba(14, 165, 233, 0.1);
            padding: 18px 12px !important;
            height: auto !important;
            color: $text-primary;
            font-weight: 700;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.8px;

            .cell {
              line-height: 1.4;
              padding: 0 !important;
            }
          }
        }

        .el-table__fixed-body-wrapper {
          background: transparent;

          .el-table__body {
            width: 100% !important;
          }

          td {
            background: $bg-white !important;
            border-right: 2px solid rgba(14, 165, 233, 0.25);
            border-bottom: 1px solid rgba(226, 232, 240, 0.5);
            padding: 16px 12px !important;
            height: auto !important;
            font-size: 13px;
            color: $text-primary;

            .cell {
              line-height: 1.4;
              padding: 0 !important;
            }
          }

          .el-table__row {
            &:nth-child(even) td {
              background: $bg-stripe !important;
            }

            &:hover td {
              background: linear-gradient(90deg, rgba(14, 165, 233, 0.08), rgba(6, 182, 212, 0.08)) !important;
            }

            &.selected-row td {
              background: linear-gradient(90deg, rgba(139, 92, 246, 0.1), rgba(236, 72, 153, 0.1)) !important;
              box-shadow: inset 4px 0 0 0 $secondary-start;

              &:hover {
                background: linear-gradient(90deg, rgba(139, 92, 246, 0.15), rgba(236, 72, 153, 0.15)) !important;
              }
            }
          }
        }

        .el-table__fixed-footer-wrapper {
          background: linear-gradient(135deg, #fef3c7 0%, #fed7aa 100%);

          td {
            background: transparent !important;
            border-right: 2px solid rgba(249, 115, 22, 0.25);
            border-top: 2px solid rgba(249, 115, 22, 0.2);
            border-bottom: none;
            padding: 18px 12px !important;
            height: auto !important;
            color: $text-primary;
            font-weight: 700;
            font-size: 14px;

            .cell {
              line-height: 1.4;
              padding: 0 !important;
              font-family: 'JetBrains Mono', monospace;
            }
          }
        }
      }

      .el-table__fixed-right {
        &::before {
          display: none;
        }
      }

      // 表头 - 渐变背景
      .el-table__header-wrapper {
        background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);

        th {
          background: transparent !important;
          border-right: 1px solid rgba(226, 232, 240, 0.3);
          border-bottom: 2px solid rgba(14, 165, 233, 0.1);
          color: $text-primary;
          font-weight: 700;
          font-size: 13px;
          text-transform: uppercase;
          letter-spacing: 0.8px;
          padding: 18px 12px !important;
          height: auto !important;

          &:last-child {
            border-right: none;
          }

          .cell {
            color: $text-primary;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            line-height: 1.4;
          }
        }
      }

      // 表体 - 斑马纹 + 圆润边框
      .el-table__body-wrapper {
        background: $bg-white;

        tr {
          background: transparent;
          transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);

          &:nth-child(even) {
            background: $bg-stripe;
          }

          &:hover > td {
            background: linear-gradient(90deg, rgba(14, 165, 233, 0.08), rgba(6, 182, 212, 0.08)) !important;
            transform: scale(1.005);
          }

          td {
            border-right: 1px solid rgba(226, 232, 240, 0.3);
            border-bottom: 1px solid rgba(226, 232, 240, 0.5);
            color: $text-primary;
            padding: 16px 12px !important;
            font-size: 13px;
            transition: all 0.3s;
            height: auto !important;

            &:first-child {
              border-top-left-radius: 8px;
              border-bottom-left-radius: 8px;
            }

            &:last-child {
              border-right: none;
              border-top-right-radius: 8px;
              border-bottom-right-radius: 8px;
            }

            .cell {
              color: $text-primary;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              line-height: 1.4;
            }

            .money-cell {
              font-family: 'JetBrains Mono', monospace;
              font-weight: 700;
              font-size: 14px;
              background: linear-gradient(135deg, $success-start, $success-end);
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
              background-clip: text;
            }
          }
        }

        // 选中行 - 渐变高亮
        .selected-row {
          background: linear-gradient(90deg, rgba(139, 92, 246, 0.1), rgba(236, 72, 153, 0.1)) !important;

          > td {
            background: linear-gradient(90deg, rgba(139, 92, 246, 0.1), rgba(236, 72, 153, 0.1)) !important;
            border-bottom-color: rgba(139, 92, 246, 0.2);
          }

          &:hover > td {
            background: linear-gradient(90deg, rgba(139, 92, 246, 0.15), rgba(236, 72, 153, 0.15)) !important;
          }
        }
      }

      // 合计行 - 渐变背景
      .el-table__footer-wrapper {
        background: linear-gradient(135deg, #fef3c7 0%, #fed7aa 100%);

        td {
          border-right: 1px solid rgba(249, 115, 22, 0.2);
          border-top: 2px solid rgba(249, 115, 22, 0.2);
          border-bottom: none;
          color: $text-primary;
          font-weight: 700;
          font-size: 14px;
          padding: 18px 12px !important;
          height: auto !important;

          &:last-child {
            border-right: none;
          }

          .cell {
            color: $text-primary;
            font-family: 'JetBrains Mono', monospace;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            line-height: 1.4;
          }
        }
      }

      // 空数据
      .el-table__empty-block {
        background: transparent;

        .el-table__empty-text {
          color: $text-secondary;
        }
      }
    }
  }

  // 分页
  .pagination-section {
    display: flex;
    justify-content: center;
    padding: 20px;
    background: $bg-card;
    border: 1px solid $border-color;
    border-radius: 16px;
    box-shadow: $shadow-sm;
    animation: slideDown 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) 0.4s both;

    ::v-deep .el-pagination {
      .btn-prev,
      .btn-next,
      .el-pager li {
        background: $bg-white;
        border: 2px solid $border-color;
        color: $text-primary;
        border-radius: 10px;
        min-width: 36px;
        height: 36px;
        line-height: 32px;
        font-weight: 600;
        transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        box-shadow: $shadow-sm;

        &:hover {
          background: linear-gradient(135deg, $primary-light, rgba(6, 182, 212, 0.1));
          border-color: $primary-start;
          color: $primary-start;
          transform: translateY(-2px);
        }

        &.active {
          background: linear-gradient(135deg, $primary-start, $primary-end);
          border-color: transparent;
          color: white;
          box-shadow: $shadow-color-blue;
          transform: scale(1.1);
        }
      }

      .el-pagination__sizes,
      .el-pagination__jump {
        .el-input__inner {
          background: $bg-white;
          border: 2px solid $border-color;
          color: $text-primary;
          border-radius: 10px;
          font-weight: 600;

          &:hover {
            border-color: $primary-start;
          }
        }
      }
    }
  }
}

// Element UI 组件全局样式
::v-deep {
  // 下拉菜单
  .el-select-dropdown {
    background: $bg-white;
    border: 2px solid $border-color;
    border-radius: 12px;
    box-shadow: $shadow-lg;

    .el-select-dropdown__item {
      color: $text-primary;
      font-size: 13px;
      font-weight: 500;
      border-radius: 6px;
      margin: 4px 8px;

      &:hover {
        background: linear-gradient(135deg, $primary-light, rgba(6, 182, 212, 0.1));
        color: $primary-start;
      }

      &.selected {
        background: linear-gradient(135deg, $primary-start, $primary-end);
        color: white;
        font-weight: 700;
      }
    }
  }

  // 日期选择器
  .el-picker-panel {
    background: $bg-white;
    border: 2px solid $border-color;
    border-radius: 12px;
    box-shadow: $shadow-lg;

    .el-date-picker__header {
      color: $text-primary;
    }

    .el-date-table th {
      color: $text-secondary;
      font-weight: 600;
    }

    .el-date-table td {
      color: $text-primary;

      &.available:hover {
        color: $primary-start;
      }

      &.current:not(.disabled) span {
        background: linear-gradient(135deg, $primary-start, $primary-end);
        color: white;
        font-weight: 700;
      }
    }
  }

  // Loading 遮罩
  .el-loading-mask {
    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(8px);

    .el-loading-spinner {
      .path {
        stroke: $primary-start;
      }

      .el-loading-text {
        color: $text-primary;
        font-weight: 600;
      }
    }
  }

  // 消息提示
  .el-message {
    background: $bg-white;
    border: 2px solid $border-color;
    border-radius: 12px;
    box-shadow: $shadow-lg;
    color: $text-primary;
  }

  // Tooltip 提示框美化 - 精致的暗色主题
  .el-tooltip__popper {
    background: linear-gradient(135deg, rgba(15, 23, 42, 0.98), rgba(30, 41, 59, 0.98)) !important;
    border: 2px solid rgba(14, 165, 233, 0.4) !important;
    border-radius: 12px !important;
    padding: 14px 18px !important;
    box-shadow:
      0 20px 60px rgba(0, 0, 0, 0.3),
      0 0 0 1px rgba(255, 255, 255, 0.08) inset,
      0 4px 12px rgba(14, 165, 233, 0.2) !important;
    color: #ffffff !important;
    font-size: 13px !important;
    font-weight: 500 !important;
    line-height: 1.7 !important;
    max-width: 450px !important;
    word-break: break-word;
    backdrop-filter: blur(16px);
    animation: tooltipFadeIn 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
    z-index: 9999 !important;

    // 添加光晕效果
    &::before {
      content: '';
      position: absolute;
      inset: -2px;
      background: linear-gradient(135deg, rgba(14, 165, 233, 0.2), rgba(6, 182, 212, 0.2));
      border-radius: 12px;
      z-index: -1;
      opacity: 0.5;
      filter: blur(8px);
    }

    // 箭头样式
    &[x-placement^="top"] .popper__arrow {
      border-top-color: rgba(14, 165, 233, 0.4) !important;

      &::after {
        border-top-color: rgba(15, 23, 42, 0.98) !important;
        margin-top: -2px;
      }
    }

    &[x-placement^="bottom"] .popper__arrow {
      border-bottom-color: rgba(14, 165, 233, 0.4) !important;

      &::after {
        border-bottom-color: rgba(15, 23, 42, 0.98) !important;
        margin-bottom: -2px;
      }
    }

    &[x-placement^="left"] .popper__arrow {
      border-left-color: rgba(14, 165, 233, 0.4) !important;

      &::after {
        border-left-color: rgba(15, 23, 42, 0.98) !important;
        margin-left: -2px;
      }
    }

    &[x-placement^="right"] .popper__arrow {
      border-right-color: rgba(14, 165, 233, 0.4) !important;

      &::after {
        border-right-color: rgba(15, 23, 42, 0.98) !important;
        margin-right: -2px;
      }
    }

    .popper__arrow {
      filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
    }
  }

  @keyframes tooltipFadeIn {
    from {
      opacity: 0;
      transform: scale(0.92) translateY(-8px);
    }
    to {
      opacity: 1;
      transform: scale(1) translateY(0);
    }
  }
}
</style>
