<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <div class="search-section">
      <mobile-search-form
        :model="queryParams"
        @search="handleQuery"
        @reset="resetQuery"
      >
        <template #form="{ expanded }">
          <el-form 
            :model="queryParams" 
            ref="queryForm" 
            size="small" 
            :inline="true" 
            v-show="showSearch" 
            label-width="68px"
          >
            <el-form-item label="京粉账号" prop="unionId">
              <el-select v-model="queryParams.unionId" placeholder="请选择京粉账号" clearable style="width: 240px">
                <el-option 
                  v-for="admin in adminList" 
                  :key="admin.value || admin.id" 
                  :label="admin.label || (admin.name + ' (' + admin.wxid + ')')" 
                  :value="admin.value || admin.id" 
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号" prop="orderId">
              <el-input v-model="queryParams.orderId" placeholder="请输入订单号" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="商品名称" prop="skuName">
              <el-input v-model="queryParams.skuName" placeholder="请输入商品名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="商品SKU" prop="skuId">
              <el-input v-model="queryParams.skuId" placeholder="SKU ID" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="订单状态" prop="statusGroup">
              <el-select v-model="queryParams.statusGroup" placeholder="订单状态" clearable style="width: 240px">
                <el-option v-for="status in mergedStatusList" :key="status.value" :label="status.label" :value="status.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单时间">
              <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <!-- 桌面端搜索按钮 -->
            <el-form-item v-if="!expanded">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </template>
      </mobile-search-form>

      <!-- 统计悬浮模块 -->
      <el-card class="statistics-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span><i class="el-icon-data-analysis"></i> 佣金统计</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="toggleStatistics">
            {{ showStatistics ? '收起' : '展开' }}
          </el-button>
        </div>
        <div v-show="showStatistics" class="statistics-content">
          <el-row :gutter="16" type="flex" justify="start" class="stat-summary-row">
            <el-col :xs="12" :sm="8" :md="4" :lg="4">
              <div class="stat-item">
                <div class="stat-label">总订单数</div>
                <div class="stat-value">{{ statistics.totalOrders }}</div>
              </div>
            </el-col>
            <el-col :xs="12" :sm="8" :md="4" :lg="4">
              <div class="stat-item">
                <div class="stat-label">总计佣金额</div>
                <div class="stat-value">¥{{ statistics.totalCosPrice.toFixed(2) }}</div>
              </div>
            </el-col>
            <el-col :xs="12" :sm="8" :md="4" :lg="4">
              <div class="stat-item" title="排除取消单（validCode=3），其余状态预估佣金累加">
                <div class="stat-label">预估佣金</div>
                <div class="stat-value">¥{{ statistics.totalEstimateFee.toFixed(2) }}</div>
              </div>
            </el-col>
            <el-col :xs="12" :sm="8" :md="4" :lg="4">
              <div class="stat-item" title="已付款未收货结算（validCode=16）的预估佣金合计">
                <div class="stat-label">已付款（待结算）</div>
                <div class="stat-value">¥{{ (statistics.estimatePaidPending || 0).toFixed(2) }}</div>
              </div>
            </el-col>
            <el-col :xs="12" :sm="8" :md="8" :lg="4">
              <div class="stat-item" title="仅已完成（validCode=17）的实际佣金累加">
                <div class="stat-label">实际佣金</div>
                <div class="stat-value">¥{{ statistics.totalActualFee.toFixed(2) }}</div>
              </div>
            </el-col>
          </el-row>
          
          <el-divider></el-divider>
          
          <el-row :gutter="20" class="status-chart-row">
            <el-col :xs="24" :sm="24" :md="10" :lg="9">
              <div class="status-pie-wrap">
                <h4>订单状态分布</h4>
                <div ref="statusPieRef" class="status-pie-chart"></div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="24" :md="14" :lg="15">
              <div class="status-stats-expanded">
                <h4>按状态统计</h4>
                <div class="status-list status-list-expanded">
                  <div
                    v-for="{ key, stat } in orderedStatusStatRows"
                    :key="key"
                    class="status-item status-item-expanded"
                  >
                    <div class="status-item-left">
                      <el-tag :type="getStatusTypeByKey(key)" size="small">{{ stat.label }}</el-tag>
                      <span class="status-count">{{ stat.count }}单</span>
                    </div>
                    <div class="status-item-amounts">
                      <span class="status-amt-est" title="分组内预估；顶部「预估佣金」为排除取消后的合计">预估 ¥{{ stat.estimateAmount.toFixed(2) }}</span>
                      <span class="status-amt-act" title="分组内实际；顶部「实际佣金」仅统计已完成(17)">实际 ¥{{ stat.actualAmount.toFixed(2) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 操作按钮区域（移动端单独显示） -->
      <div class="action-buttons-section mobile-only">
        <mobile-button-group
          :buttons="actionButtons"
          :primary-count="2"
        />
      </div>

      <!-- 桌面端按钮组 -->
      <el-row :gutter="10" class="mb8 desktop-only">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:orderrows:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:orderrows:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:orderrows:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:orderrows:export']">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-picture-outline"
            size="mini"
            :loading="backfillLoading"
            @click="handleBackfillGoodsInfo"
          >一键补全商品图</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <!-- 表格区域 - 可滚动 -->
    <div class="table-section">
      <el-table v-loading="loading" :data="orderrowsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="账号" align="center" prop="unionId" width="50">
          <template slot-scope="scope">
            <span>{{ getAdminName(scope.row.unionId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单号" align="center" prop="orderId" width="148">
          <template slot-scope="scope">
            <span class="order-id-text">{{ scope.row.orderId }}</span>
            <el-popover
              v-if="scope.row.linkedJdOrder"
              placement="right"
              width="340"
              trigger="click"
            >
              <div class="linked-jd-popover">
                <div class="linked-jd-title">已关联本地慢单</div>
                <div class="linked-jd-row"><span>内部单号</span>{{ scope.row.linkedJdOrder.remark || '-' }}</div>
                <div class="linked-jd-row"><span>型号</span>{{ formatLinkedModel(scope.row.linkedJdOrder) }}</div>
                <div class="linked-jd-row"><span>下单人</span>{{ scope.row.linkedJdOrder.buyer || '-' }}</div>
                <div class="linked-jd-row"><span>付款</span>¥{{ scope.row.linkedJdOrder.paymentAmount != null ? scope.row.linkedJdOrder.paymentAmount : '-' }}</div>
                <div class="linked-jd-row"><span>后返</span>¥{{ scope.row.linkedJdOrder.rebateAmount != null ? scope.row.linkedJdOrder.rebateAmount : '-' }}</div>
                <div class="linked-jd-row"><span>状态</span>{{ scope.row.linkedJdOrder.status || '-' }}</div>
                <div class="linked-jd-actions">
                  <el-button type="primary" size="mini" @click="goToSlowOrder(scope.row)">打开慢单</el-button>
                </div>
              </div>
              <i
                slot="reference"
                class="el-icon-link linked-jd-icon"
                title="已关联慢单，点击查看"
                @click.stop
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="skuName" :show-overflow-tooltip="true" min-width="200" />
        <el-table-column label="计佣金额" align="center" prop="estimateCosPrice" width="100" sortable="custom" @sort-change="handleSortChange">
          <template slot-scope="scope">
            <span>¥{{ scope.row.estimateCosPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品数量" align="center" prop="skuNum" width="80" />
        <el-table-column label="订单状态" align="center" prop="validCode" width="240">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.validCode)">
              {{ getStatusText(scope.row.validCode) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="佣金比例" align="center" prop="commissionRate" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.commissionRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="预估佣金" align="center" prop="estimateFee" width="100">
          <template slot-scope="scope">
            <span>¥{{ scope.row.estimateFee }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际佣金" align="center" prop="actualFee" width="100">
          <template slot-scope="scope">
            <span>¥{{ scope.row.actualFee }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单时间" align="center" prop="orderTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成时间" align="center" prop="finishTime" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.finishTime ? parseTime(scope.row.finishTime) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:orderrows:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:orderrows:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

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

    <!-- 查看订单详情对话框 -->
    <el-dialog :title="'订单详情 - ' + currentOrder.orderId" :visible.sync="viewDialogVisible" width="900px" append-to-body>
      <div v-loading="viewLoading">
      <el-descriptions :column="2" border>
        <!-- 基本信息 -->
        <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="主单号">{{ currentOrder.parentId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="本地慢单" :span="2" v-if="currentOrder.linkedJdOrder">
          <span>{{ currentOrder.linkedJdOrder.remark || '-' }}</span>
          <span v-if="formatLinkedModel(currentOrder.linkedJdOrder) !== '-'" style="margin-left: 8px; color: #909399;">
            {{ formatLinkedModel(currentOrder.linkedJdOrder) }}
          </span>
          <el-button type="text" size="mini" style="margin-left: 8px;" @click="goToSlowOrder(currentOrder)">打开慢单</el-button>
        </el-descriptions-item>
        <el-descriptions-item label="商品ID">{{ currentOrder.skuId }}</el-descriptions-item>
        <el-descriptions-item label="商品名称" :span="2">{{ currentOrder.skuName }}</el-descriptions-item>
        <el-descriptions-item label="店铺名称" :span="2">{{ goodsDetailShopName }}</el-descriptions-item>
        <el-descriptions-item label="商品主图" :span="2">
          <img
            v-if="goodsDetailImageUrl && !detailImageFailed"
            :src="goodsDetailImageUrl"
            referrerpolicy="no-referrer"
            class="detail-goods-img"
            @error="detailImageFailed = true"
          >
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="商品价格">¥{{ currentOrder.price }}</el-descriptions-item>
        <el-descriptions-item label="商品数量">{{ currentOrder.skuNum }}</el-descriptions-item>
        <el-descriptions-item label="已退货数量">{{ currentOrder.skuReturnNum || 0 }}</el-descriptions-item>
        <el-descriptions-item label="售后中数量">{{ currentOrder.skuFrozenNum || 0 }}</el-descriptions-item>
        
        <!-- 订单状态 -->
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.validCode)">
            {{ getStatusText(currentOrder.validCode) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发货状态">
          <el-tag :type="currentOrder.expressStatus === 10 ? 'warning' : 'success'">
            {{ currentOrder.expressStatus === 10 ? '待发货' : '已发货' }}
          </el-tag>
        </el-descriptions-item>
        
        <!-- 佣金信息 -->
        <el-descriptions-item label="佣金比例">{{ currentOrder.commissionRate }}%</el-descriptions-item>
        <el-descriptions-item label="分成比例">{{ currentOrder.subSideRate }}%</el-descriptions-item>
        <el-descriptions-item label="补贴比例">{{ currentOrder.subsidyRate }}%</el-descriptions-item>
        <el-descriptions-item label="最终分佣比例">{{ currentOrder.finalRate }}%</el-descriptions-item>
        <el-descriptions-item label="预估计佣金额">¥{{ currentOrder.estimateCosPrice }}</el-descriptions-item>
        <el-descriptions-item label="预估佣金">¥{{ currentOrder.estimateFee }}</el-descriptions-item>
        <el-descriptions-item label="实际计佣金额">¥{{ currentOrder.actualCosPrice }}</el-descriptions-item>
        <el-descriptions-item label="实际佣金">¥{{ currentOrder.actualFee }}</el-descriptions-item>
        
        <!-- 时间信息 -->
        <el-descriptions-item label="下单时间">{{ parseTime(currentOrder.orderTime) }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ currentOrder.finishTime ? parseTime(currentOrder.finishTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(currentOrder.modifyTime) }}</el-descriptions-item>
        <el-descriptions-item label="预估结算时间">{{ currentOrder.payMonth !== '0' ? currentOrder.payMonth : '-' }}</el-descriptions-item>
        
        <!-- 推广信息 -->
        <el-descriptions-item label="推客ID">{{ currentOrder.unionId }}</el-descriptions-item>
        <el-descriptions-item label="推广位ID">{{ currentOrder.positionId }}</el-descriptions-item>
        <el-descriptions-item label="应用ID">{{ currentOrder.siteId }}</el-descriptions-item>
        <el-descriptions-item label="商家ID">{{ currentOrder.popId }}</el-descriptions-item>
        <el-descriptions-item label="PID">{{ currentOrder.pid || '-' }}</el-descriptions-item>
        <el-descriptions-item label="子渠道标识">{{ currentOrder.subUnionId || '-' }}</el-descriptions-item>
        
        <!-- 商品分类 -->
        <el-descriptions-item label="商品分类" :span="2">
          {{ currentOrder.cid1 }} > {{ currentOrder.cid2 }} > {{ currentOrder.cid3 }}
        </el-descriptions-item>
        
        <!-- 订单属性 -->
        <el-descriptions-item label="下单设备">
          <el-tag :type="currentOrder.orderEmt === 1 ? 'primary' : 'success'">
            {{ currentOrder.orderEmt === 1 ? 'PC' : '无线' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="PLUS会员">
          <el-tag :type="currentOrder.plus === 1 ? 'warning' : 'info'">
            {{ currentOrder.plus === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="同跨店">
          <el-tag :type="currentOrder.traceType === 2 ? 'success' : 'warning'">
            {{ currentOrder.traceType === 2 ? '同店' : '跨店' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="站长角色">
          <el-tag :type="getRoleType(currentOrder.unionRole)">
            {{ getRoleText(currentOrder.unionRole) }}
          </el-tag>
        </el-descriptions-item>
        
        <!-- 扩展信息 -->
        <el-descriptions-item label="扩展字段">{{ currentOrder.ext1 || '-' }}</el-descriptions-item>
        <el-descriptions-item label="礼金分摊金额">¥{{ currentOrder.giftCouponOcsAmount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="礼金批次ID">{{ currentOrder.giftCouponKey || '-' }}</el-descriptions-item>
        <el-descriptions-item label="计佣扩展信息">{{ currentOrder.balanceExt || '-' }}</el-descriptions-item>
        <el-descriptions-item label="价保赔付金额">¥{{ currentOrder.proPriceAmount || 0 }}</el-descriptions-item>
        
        <el-descriptions-item label="店铺ID">{{ (currentOrder.goodsInfo && currentOrder.goodsInfo.shopId) || '-' }}</el-descriptions-item>
        
        <!-- 类目信息 -->
        <el-descriptions-item label="类目信息" :span="2" v-if="currentOrder.categoryInfo">
          {{ currentOrder.categoryInfo.cid1Name }} > {{ currentOrder.categoryInfo.cid2Name }} > {{ currentOrder.categoryInfo.cid3Name }}
        </el-descriptions-item>
        
        <!-- 其他信息 -->
        <el-descriptions-item label="联盟商品ID">{{ currentOrder.itemId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="工具商联盟商品ID">{{ currentOrder.callerItemId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="渠道关系ID">{{ currentOrder.channelId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="团长渠道ID">{{ currentOrder.rid || '-' }}</el-descriptions-item>
        <el-descriptions-item label="招商团活动ID">{{ currentOrder.cpActId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="账户ID">{{ currentOrder.account || '-' }}</el-descriptions-item>
      </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderrows, getOrderrows, delOrderrows, addOrderrows, updateOrderrows, getValidCodeSelectData, backfillGoodsInfo } from "@/api/system/orderrows";
import { getAdminSelectData } from "@/api/system/superadmin";
import { mapGetters } from 'vuex'
import * as echarts from 'echarts'
import { debounce } from '@/utils'
import MobileSearchForm from '@/components/MobileSearchForm'
import MobileButtonGroup from '@/components/MobileButtonGroup'

/** 与后端分组顺序一致，便于阅读 */
const STATUS_STAT_ORDER = ['pending', 'paid', 'deposit', 'finished', 'cancel', 'invalid', 'illegal']

export default {
  name: "Orderrows",
  components: {
    MobileSearchForm,
    MobileButtonGroup
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      backfillLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 京粉订单表格数据
      orderrowsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unionId: null,
        orderId: null,
        skuName: null,
        skuId: null,
        validCode: null,
        statusGroup: null, // 新增
        orderBy: null, // 排序字段
        orderSort: null // 排序方向：asc/desc
      },
      // 管理员列表
      adminList: [],
      // 状态列表
      statusList: [], // 原始状态列表
      mergedStatusList: [], // 合并后下拉
      statusValueMap: {}, // 合并项到原始code数组
      // 查看详情对话框
      viewDialogVisible: false,
      // 当前查看的订单
      currentOrder: {},
      detailImageFailed: false,
      viewLoading: false,
      // 统计相关
      showStatistics: true,
      statistics: {
        totalOrders: 0,
        totalCosPrice: 0,
        totalEstimateFee: 0,
        estimatePaidPending: 0,
        totalActualFee: 0,
        statusStats: {}
      },
      statusPieInstance: null,
      _statusPieResizeHandler: null
    };
  },
  computed: {
    ...mapGetters(['device']),
    orderedStatusStatRows() {
      return STATUS_STAT_ORDER.filter(key => this.statistics.statusStats[key]).map(key => ({
        key,
        stat: this.statistics.statusStats[key]
      }))
    },
    isMobile() {
      if (this.device === 'mobile') {
        return true
      }
      if (typeof window !== 'undefined' && window.innerWidth < 768) {
        return true
      }
      return false
    },
    actionButtons() {
      return [
        { key: 'add', label: '新增', type: 'primary', icon: 'el-icon-plus', handler: () => this.handleAdd(), disabled: false },
        { key: 'update', label: '修改', type: 'success', icon: 'el-icon-edit', handler: () => this.handleUpdate(), disabled: this.single },
        { key: 'delete', label: '删除', type: 'danger', icon: 'el-icon-delete', handler: () => this.handleDelete(), disabled: this.multiple },
        { key: 'export', label: '导出', type: 'warning', icon: 'el-icon-download', handler: () => this.handleExport(), disabled: false },
        { key: 'backfill', label: '补全商品图', type: 'info', icon: 'el-icon-picture-outline', handler: () => this.handleBackfillGoodsInfo(), disabled: this.backfillLoading }
      ]
    },
    goodsDetailShopName() {
      const shopName = this.currentOrder.goodsInfo && this.currentOrder.goodsInfo.shopName
      return shopName || '-'
    },
    goodsDetailImageUrl() {
      const imageUrl = this.currentOrder.goodsInfo && this.currentOrder.goodsInfo.imageUrl
      if (imageUrl) {
        return imageUrl
      }
      if (this.currentOrder.skuId) {
        return 'https://img14.360buyimg.com/n5/s450x450_' + this.currentOrder.skuId + '.jpg'
      }
      return ''
    }
  },
  created() {
    this.getList();
    this.getAdminList();
    this.getStatusList();
  },
  beforeDestroy() {
    this.disposeStatusPieChart();
  },
  watch: {
    // 监听日期范围变化，自动调整分页条数
    dateRange: {
      handler(newVal) {
        if (newVal && newVal.length === 2) {
          // 选择了日期范围，设置分页条数为1000
          this.queryParams.pageSize = 1000;
          this.queryParams.pageNum = 1;
        } else {
          // 清空日期范围，恢复默认分页条数
          this.queryParams.pageSize = 10;
          this.queryParams.pageNum = 1;
        }
      },
      deep: true
    },
    statistics: {
      deep: true,
      handler() {
        this.$nextTick(() => this.renderStatusPieChart());
      }
    },
    showStatistics(val) {
      if (val) this.$nextTick(() => this.renderStatusPieChart());
    }
  },
  methods: {
    /** 查询京粉订单列表 */
    getList() {
      this.loading = true;
      listOrderrows(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.orderrowsList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 统计已合并到列表接口返回的 statistics，与列表同条件
        this.applyStatistics(response.statistics);
      }).catch(error => {
        console.error('获取订单列表失败:', error);
        this.loading = false;
        this.$message.error('获取订单列表失败');
      });
    },
    /** 使用列表接口返回的 statistics 填充统计（与列表同一次请求、同条件） */
    applyStatistics(data) {
      if (!data) {
        if (this.orderrowsList.length > 0) this.calculateStatistics();
        else this.statistics = { totalOrders: 0, totalCosPrice: 0, totalEstimateFee: 0, estimatePaidPending: 0, totalActualFee: 0, statusStats: {} };
        return;
      }
      const groupStats = data.groupStats || {};
      this.statistics = {
        totalOrders: data.totalOrders || 0,
        totalCosPrice: data.totalCosPrice != null ? data.totalCosPrice : 0,
        totalEstimateFee: data.totalCommission != null ? data.totalCommission : 0,
        estimatePaidPending: data.estimatePaidPending != null ? data.estimatePaidPending : 0,
        totalActualFee: data.totalActualFee != null ? data.totalActualFee : 0,
        statusStats: {
          cancel: this.convertGroupStat(groupStats.cancel),
          invalid: this.convertGroupStat(groupStats.invalid),
          pending: this.convertGroupStat(groupStats.pending),
          paid: this.convertGroupStat(groupStats.paid),
          finished: this.convertGroupStat(groupStats.finished),
          deposit: this.convertGroupStat(groupStats.deposit),
          illegal: this.convertGroupStat(groupStats.illegal)
        }
      };
    },
    /** 与 OrderRowsController.buildStatistics 一致：commission→预估口径，actualFee→实际口径 */
    convertGroupStat(groupStat) {
      if (!groupStat) return { label: '', count: 0, estimateAmount: 0, actualAmount: 0 };
      const est = groupStat.commission != null ? Number(groupStat.commission) : 0;
      const act = groupStat.actualFee != null ? Number(groupStat.actualFee) : 0;
      return {
        label: groupStat.label || '',
        count: groupStat.count || 0,
        estimateAmount: est,
        actualAmount: act
      };
    },
    disposeStatusPieChart() {
      if (this._statusPieResizeHandler) {
        window.removeEventListener('resize', this._statusPieResizeHandler);
        this._statusPieResizeHandler = null;
      }
      if (this.statusPieInstance) {
        this.statusPieInstance.dispose();
        this.statusPieInstance = null;
      }
    },
    renderStatusPieChart() {
      if (!this.showStatistics || !this.$refs.statusPieRef) return;
      const pieData = [];
      STATUS_STAT_ORDER.forEach(key => {
        const s = this.statistics.statusStats[key];
        if (s && s.count > 0) pieData.push({ name: s.label, value: s.count });
      });
      const el = this.$refs.statusPieRef;
      if (!this.statusPieInstance) {
        this.statusPieInstance = echarts.init(el);
        this._statusPieResizeHandler = debounce(() => {
          this.statusPieInstance && this.statusPieInstance.resize();
        }, 100);
        window.addEventListener('resize', this._statusPieResizeHandler);
      }
      if (!pieData.length) {
        this.statusPieInstance.setOption({
          tooltip: { show: false },
          graphic: [{
            type: 'text',
            left: 'center',
            top: 'middle',
            style: { text: '暂无分布数据', fill: '#909399', fontSize: 14 }
          }],
          series: []
        }, true);
        return;
      }
      this.statusPieInstance.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>{c} 单 ({d}%)'
        },
        graphic: [],
        series: [
          {
            name: '订单数',
            type: 'pie',
            radius: ['40%', '68%'],
            center: ['50%', '52%'],
            data: pieData,
            label: { formatter: '{b}\n{d}%' },
            emphasis: { itemStyle: { shadowBlur: 8, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.15)' } }
          }
        ],
        color: ['#e6a23c', '#409eff', '#909399', '#67c23a', '#f56c6c', '#c0c4cc', '#f78989']
      }, true);
    },
    /** 获取管理员列表 */
    getAdminList() {
      getAdminSelectData().then(response => {
        this.adminList = response.data || response;
      }).catch(error => {
        console.error('获取管理员列表失败:', error);
        this.$message.error('获取管理员列表失败');
      });
    },
    /** 获取状态列表 */
    getStatusList() {
      getValidCodeSelectData().then(response => {
        const raw = response.data || response;
        // 合并分组
        const groupMap = [
          { label: '取消', value: 'cancel', codes: ['3'] },
          { label: '无效', value: 'invalid', codes: ['2','4','5','6','7','8','9','10','11','14','19','20','21','22','23','29','30','31','32','33','34'] },
          { label: '待付款', value: 'pending', codes: ['15'] },
          { label: '已付款（待结算）', value: 'paid', codes: ['16'] },
          { label: '已完成', value: 'finished', codes: ['17'] },
          { label: '已付定金', value: 'deposit', codes: ['24'] },
          { label: '违规', value: 'illegal', codes: ['25','26','27','28'] }
        ];
        // 兼容后端返回的code为数字或字符串
        const allCodes = raw.map(i => String(i.value || i.code));
        // 处理无效分组codes
        groupMap[1].codes = ['2','4','5','6','7','8','9','11','14','19','20','21','22','23','29','30','31','33','34'];
        // 违规codes
        groupMap[6].codes = ['25','26','27','28'];
        // 生成下拉和映射
        this.mergedStatusList = groupMap.map(g => ({ label: g.label, value: g.value }));
        this.statusValueMap = {};
        groupMap.forEach(g => { this.statusValueMap[g.value] = g.codes; });
        this.statusList = raw;
      }).catch(error => {
        this.$message.error('获取状态列表失败');
      });
    },
    // 获取状态类型
    getStatusType(validCode) {
      const statusMap = {
        '-100': 'info',      // 无变化
        '-1': 'info',        // 未知
        '2': 'danger',        // 无效-拆单
        '3': 'danger',        // 无效-取消
        '4': 'danger',        // 无效-京东帮帮主订单
        '5': 'danger',        // 无效-账号异常
        '6': 'danger',        // 无效-赠品类目不返佣
        '7': 'danger',        // 无效-校园订单
        '8': 'danger',        // 无效-企业订单
        '9': 'danger',        // 无效-团购订单
        '11': 'danger',       // 无效-乡村推广员下单
        '13': 'danger',       // 违规订单-其他
        '14': 'danger',       // 无效-来源与备案网址不符
        '15': 'warning',      // 待付款
        '16': 'primary',      // 已付款
        '17': 'success',      // 已完成（购买用户确认收货）
        '19': 'danger',       // 无效-佣金比例为0
        '20': 'danger',       // 无效-此复购订单对应的首购订单无效
        '21': 'danger',       // 无效-云店订单
        '22': 'danger',       // 无效-PLUS会员佣金比例为0
        '23': 'danger',       // 无效-支付有礼
        '24': 'warning',      // 已付定金
        '25': 'danger',       // 违规订单-流量劫持
        '26': 'danger',       // 违规订单-流量异常
        '27': 'danger',       // 违规订单-违反京东平台规则
        '28': 'danger',       // 违规订单-多笔交易异常
        '29': 'danger',       // 无效-跨屏跨店
        '30': 'danger',       // 无效-累计件数超出类目上限
        '31': 'danger',       // 无效-黑名单sku
        '33': 'info',         // 超市卡充值订单
        '34': 'danger'        // 无效-推卡订单无效
      };
      return statusMap[validCode] || 'info';
    },
    // 获取状态文本
    getStatusText(validCode) {
      const statusMap = {
        '-100': '无变化',
        '-1': '未知',
        '2': '无效-拆单',
        '3': '无效-取消',
        '4': '无效-京东帮帮主订单',
        '5': '无效-账号异常',
        '6': '无效-赠品类目不返佣',
        '7': '无效-校园订单',
        '8': '无效-企业订单',
        '9': '无效-团购订单',
        '11': '无效-乡村推广员下单',
        '13': '违规订单-其他',
        '14': '无效-来源与备案网址不符',
        '15': '待付款',
        '16': '已付款',
        '17': '已完成',
        '19': '无效-佣金比例为0',
        '20': '无效-此复购订单对应的首购订单无效',
        '21': '无效-云店订单',
        '22': '无效-PLUS会员佣金比例为0',
        '23': '无效-支付有礼',
        '24': '已付定金',
        '25': '违规订单-流量劫持',
        '26': '违规订单-流量异常',
        '27': '违规订单-违反京东平台规则',
        '28': '违规订单-多笔交易异常',
        '29': '无效-跨屏跨店',
        '30': '无效-累计件数超出类目上限',
        '31': '无效-黑名单sku',
        '33': '超市卡充值订单',
        '34': '无效-推卡订单无效'
      };
      return statusMap[validCode] || '代码描述未定义';
    },
    // 获取站长角色类型
    getRoleType(unionRole) {
      const roleMap = {
        1: 'primary',   // 推客
        2: 'success',    // 团长
        3: 'warning'     // 内容服务商
      };
      return roleMap[unionRole] || 'info';
    },
    // 获取站长角色文本
    getRoleText(unionRole) {
      const roleMap = {
        1: '推客',
        2: '团长',
        3: '内容服务商'
      };
      return roleMap[unionRole] || '未知';
    },
    // 根据unionId获取管理员名称
    getAdminName(unionId) {
      if (!unionId) return '-';
      const admin = this.adminList.find(item => {
        const itemValue = item.value || item.id;
        return itemValue == unionId;
      });
      if (admin) {
        return admin.label || (admin.name + ' (' + admin.wxid + ')');
      }
      return unionId; // 如果找不到对应的管理员，返回原始unionId
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        skuName: null,
        price: null,
        validCode: "1"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.statusGroup) {
        const codes = this.statusValueMap[this.queryParams.statusGroup]
        this.queryParams.validCodes = codes && codes.length ? codes.map(code => Number(code)) : null
      } else {
        this.queryParams.validCodes = null
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.validCodes = null;
      // 重置时恢复默认分页条数
      this.queryParams.pageSize = 10;
      this.queryParams.pageNum = 1;
      // 重置排序
      this.queryParams.orderBy = null;
      this.queryParams.orderSort = null;
      this.getList();
    },
    /** 排序变化处理 */
    handleSortChange(column) {
      if (column.prop === 'estimateCosPrice') {
        if (column.order === 'ascending') {
          this.queryParams.orderBy = 'estimateCosPrice';
          this.queryParams.orderSort = 'asc';
        } else if (column.order === 'descending') {
          this.queryParams.orderBy = 'estimateCosPrice';
          this.queryParams.orderSort = 'desc';
        } else {
          // 取消排序
          this.queryParams.orderBy = null;
          this.queryParams.orderSort = null;
        }
        this.queryParams.pageNum = 1;
        this.getList();
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看订单详情 */
    handleView(row) {
      const id = row.id
      this.detailImageFailed = false
      if (!id) {
        this.currentOrder = row
        this.viewDialogVisible = true
        return
      }
      this.viewLoading = true
      getOrderrows(id).then(response => {
        this.currentOrder = response.data || row
        this.viewDialogVisible = true
      }).catch(() => {
        this.currentOrder = row
        this.viewDialogVisible = true
      }).finally(() => {
        this.viewLoading = false
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加京粉订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrderrows(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改京粉订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrderrows(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderrows(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除京粉订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrderrows(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/jarvis/orderrows/export', {
        ...this.queryParams
      }, `京粉订单数据_${new Date().getTime()}.xlsx`)
    },
    /** 一键补全商品图、店铺名 */
    handleBackfillGoodsInfo() {
      const orderId = this.queryParams.orderId && String(this.queryParams.orderId).trim()
      const tip = orderId
        ? `将为订单号 ${orderId} 从京东补全商品图和店铺名，是否继续？`
        : '将自动补全最近 100 条缺失商品图/店铺名的订单（可多次点击直到补完），是否继续？'
      this.$modal.confirm(tip).then(() => {
        this.backfillLoading = true
        const payload = orderId ? { orderIds: orderId } : { missing: true, limit: 100 }
        return backfillGoodsInfo(payload)
      }).then(res => {
        const data = (res && res.data) || {}
        const updated = data.updated != null ? data.updated : 0
        const skipped = data.skipped != null ? data.skipped : 0
        const failed = data.failed != null ? data.failed : 0
        if (failed > 0) {
          this.$modal.msgWarning(`补全完成：成功 ${updated}，跳过 ${skipped}，失败 ${failed}`)
        } else {
          this.$modal.msgSuccess(`补全完成：成功 ${updated}，跳过 ${skipped}`)
        }
        this.getList()
      }).catch(() => {}).finally(() => {
        this.backfillLoading = false
      })
    },
    formatLinkedModel(linked) {
      if (!linked) return '-'
      const model = linked.modelNumber || ''
      const shop = linked.modelShop || ''
      if (model && shop) return model + shop
      return model || shop || '-'
    },
    goToSlowOrder(row) {
      const linked = row && row.linkedJdOrder
      if (!linked) return
      const orderSearch = row.orderId != null ? String(row.orderId) : linked.orderId
      this.$router.push({
        path: '/sloworder/index',
        query: {
          orderSearch,
          allDates: '1'
        }
      })
    },
    /** 切换统计显示 */
    toggleStatistics() {
      this.showStatistics = !this.showStatistics;
    },
    /** 无后端 statistics 时按当前页推算（与 OrderRowsController.buildStatistics 口径一致） */
    calculateStatistics() {
      const stats = {
        totalOrders: this.orderrowsList.length,
        totalCosPrice: 0,
        totalEstimateFee: 0,
        estimatePaidPending: 0,
        totalActualFee: 0,
        statusStats: {}
      };

      const statusGroups = {
        cancel: { label: '取消', codes: ['3'] },
        invalid: { label: '无效', codes: ['2', '4', '5', '6', '7', '8', '9', '10', '11', '14', '19', '20', '21', '22', '23', '29', '30', '31', '32', '33', '34'] },
        pending: { label: '待付款', codes: ['15'] },
        paid: { label: '已付款（待结算）', codes: ['16'] },
        finished: { label: '已完成', codes: ['17'] },
        deposit: { label: '已付定金', codes: ['24'] },
        illegal: { label: '违规', codes: ['25', '26', '27', '28'] }
      };

      Object.keys(statusGroups).forEach(key => {
        stats.statusStats[key] = {
          label: statusGroups[key].label,
          count: 0,
          estimateAmount: 0,
          actualAmount: 0
        };
      });

      this.orderrowsList.forEach(order => {
        if (order.estimateCosPrice != null && order.estimateCosPrice !== '') {
          stats.totalCosPrice += parseFloat(order.estimateCosPrice) || 0;
        }

        const validCode = String(order.validCode);
        const isCancel = validCode === '3';
        const isIllegal = ['25', '26', '27', '28'].includes(validCode);
        const estCos = parseFloat(order.estimateCosPrice) || 0;
        const rate = parseFloat(order.commissionRate) || 0;
        const estFee = parseFloat(order.estimateFee) || 0;
        const actFee = parseFloat(order.actualFee) || 0;

        let commissionAmount = 0;
        let actualFeeAmount = 0;

        if (isIllegal) {
          if (estCos > 0 && rate > 0) {
            commissionAmount = estCos * rate / 100;
            actualFeeAmount = commissionAmount;
          } else if (estFee) {
            commissionAmount = estFee;
            actualFeeAmount = estFee;
          }
        } else if (isCancel) {
          if (actFee > 0) {
            actualFeeAmount = actFee;
            commissionAmount = estFee;
          } else if (estCos > 0 && rate > 0) {
            commissionAmount = estCos * rate / 100;
            actualFeeAmount = commissionAmount;
          } else {
            commissionAmount = estFee;
            actualFeeAmount = actFee;
          }
        } else {
          commissionAmount = estFee;
          actualFeeAmount = actFee;
        }

        // 与 OrderRowsController.buildStatistics：预估汇总排除取消；实际汇总仅已完成(17)
        if (validCode !== '3') {
          stats.totalEstimateFee += commissionAmount;
        }
        if (validCode === '16') {
          stats.estimatePaidPending += commissionAmount;
        }
        if (validCode === '17') {
          stats.totalActualFee += actualFeeAmount;
        }

        let statusKey = 'invalid';
        for (const [key, group] of Object.entries(statusGroups)) {
          if (group.codes.includes(validCode)) {
            statusKey = key;
            break;
          }
        }
        stats.statusStats[statusKey].count++;
        stats.statusStats[statusKey].estimateAmount += commissionAmount;
        stats.statusStats[statusKey].actualAmount += actualFeeAmount;
      });

      this.statistics = stats;
    },
    /** 根据状态键获取标签类型 */
    getStatusTypeByKey(key) {
      const typeMap = {
        'cancel': 'danger',
        'invalid': 'info',
        'pending': 'warning',
        'paid': 'primary',
        'finished': 'success',
        'deposit': 'warning',
        'illegal': 'danger'
      };
      return typeMap[key] || 'info';
    }
  }
};
</script>

<style scoped>
.detail-goods-img {
  max-width: 200px;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.order-id-text {
  vertical-align: middle;
}

.linked-jd-icon {
  margin-left: 4px;
  color: #67c23a;
  cursor: pointer;
  font-weight: bold;
  vertical-align: middle;
}

.linked-jd-popover .linked-jd-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.linked-jd-popover .linked-jd-row {
  margin-bottom: 6px;
  font-size: 13px;
  line-height: 1.5;
  word-break: break-all;
}

.linked-jd-popover .linked-jd-row span {
  display: inline-block;
  width: 56px;
  color: #909399;
}

.linked-jd-popover .linked-jd-actions {
  margin-top: 10px;
  text-align: right;
}

/* 主容器布局 */
.app-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 84px); /* 减去头部导航高度 */
  overflow: hidden;
}

/* 搜索区域 - 固定在顶部 */
.search-section {
  flex-shrink: 0;
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 表格区域 - 可滚动 */
.table-section {
  flex: 1;
  overflow: auto;
  padding: 0 20px;
  background: #fff;
}

/* 固定分页区域 */
.pagination-section {
  flex-shrink: 0;
  background: #fff;
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  bottom: 0;
  z-index: 10;
}

/* 统计卡片样式 */
.statistics-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.statistics-card .el-card__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

.statistics-card .el-card__header span {
  font-weight: 600;
  font-size: 16px;
}

.statistics-card .el-card__header .el-button {
  color: white;
  font-weight: 500;
}

.statistics-card .el-card__header .el-button:hover {
  color: #f0f0f0;
}

.statistics-content {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

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

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.status-chart-row {
  align-items: stretch;
}

.status-pie-wrap,
.status-stats-expanded {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  height: 100%;
  min-height: 280px;
}

.status-pie-wrap h4,
.status-stats-expanded h4 {
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #e9ecef;
  padding-bottom: 8px;
}

.status-pie-chart {
  width: 100%;
  height: 260px;
}

.status-list-expanded {
  max-height: 320px;
  overflow-y: auto;
}

.status-item-expanded {
  flex-wrap: wrap;
  gap: 8px 0;
}

.status-item-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
}

.status-item-amounts {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  justify-content: flex-end;
  width: 100%;
}

@media (min-width: 992px) {
  .status-item-expanded {
    flex-wrap: nowrap;
    align-items: center;
  }
  .status-item-amounts {
    width: auto;
    flex: 0 0 auto;
  }
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e9ecef;
}

.status-item:last-child {
  border-bottom: none;
}

.status-count {
  font-size: 12px;
  color: #666;
  background: #e9ecef;
  padding: 2px 8px;
  border-radius: 12px;
  min-width: 40px;
  text-align: center;
}

.status-amt-est {
  font-weight: 600;
  color: #409eff;
  font-size: 13px;
  white-space: nowrap;
}

.status-amt-act {
  font-weight: 600;
  color: #67c23a;
  font-size: 13px;
  white-space: nowrap;
}

/* 滚动条样式 */
.status-list-expanded::-webkit-scrollbar {
  width: 4px;
}

.status-list-expanded::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.status-list-expanded::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.status-list-expanded::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表格区域滚动条样式 */
.table-section::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.table-section::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.table-section::-webkit-scrollbar-thumb {
  background: #c0c0c0;
  border-radius: 3px;
}

.table-section::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    height: calc(100vh - 50px); /* 移动端调整高度 */
  }
  
  .search-section {
    padding: 15px;
  }
  
  .table-section {
    padding: 0 15px;
  }
  
  .pagination-section {
    padding: 10px 15px;
  }
  
  .statistics-content .el-col {
    margin-bottom: 15px;
  }
  
  .stat-item {
    padding: 10px;
  }
  
  .stat-value {
    font-size: 20px;
  }
}

/* 确保表格在容器内正确显示 */
.table-section .el-table {
  width: 100%;
}

/* 分页组件样式优化 */
.pagination-section .pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  border-radius: 4px;
  padding: 10px 0;
}

/* 操作按钮区域 */
.action-buttons-section {
  margin-top: 12px;
  margin-bottom: 12px;
}

/* 移动端和桌面端按钮组显示控制 */
@media (max-width: 768px) {
  .desktop-only {
    display: none !important;
  }
  
  .action-buttons-section.mobile-only {
    display: block;
  }
}

@media (min-width: 769px) {
  .mobile-only {
    display: none !important;
  }
  
  .desktop-only {
    display: block;
  }
}
</style>