<template>
  <div class="app-container">
    <el-container>
      <el-aside width="250px" class="tree-aside">
        <div class="tree-header">
          <span>组/标签筛选</span>
          <el-button type="text" size="mini" @click="resetTreeFilter">重置</el-button>
        </div>
        <el-tree
          ref="filterTree"
          :data="treeFilterData"
          :props="treeProps"
          node-key="id"
          :default-expand-all="true"
          :highlight-current="true"
          @node-click="handleTreeNodeClick"
          class="filter-tree"
        >
          <template slot-scope="{ node, data }">
            <span class="tree-node">
              <span :class="{'group-node': data.type === 'group', 'tag-node': data.type === 'tag'}">
                {{ node.label }}
              </span>
              <span class="node-count" v-if="data.count !== undefined">({{ data.count }})</span>
            </span>
          </template>
        </el-tree>
      </el-aside>

      <el-main>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="数据类型" prop="dataType">
            <el-select
              v-model="queryParams.dataType"
              placeholder="请选择数据类型"
              clearable
              @change="handleDataTypeChange"
            >
              <el-option label="按天查询" value="day" />
              <el-option label="自然周叠加数据" value="week" />
              <el-option label="自然月叠加数据" value="month" />
              <el-option label="所有数据" value="all" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="queryParams.dataType === 'week'" label="年份" prop="year">
            <el-date-picker
              v-model="queryParams.year"
              type="year"
              placeholder="选择年份"
              value-format="yyyy"
              style="width: 120px"
            />
          </el-form-item>

          <el-form-item v-if="queryParams.dataType === 'week'" label="周数" prop="week">
            <el-select
              v-model="queryParams.week"
              placeholder="选择周数"
              clearable
              style="width: 120px"
            >
              <el-option v-for="i in 53" :key="i" :label="'第' + i + '周'" :value="i" />
            </el-select>
            <span v-if="weekDateRange" style="margin-left: 10px; color: #909399; font-size: 12px;">{{ weekDateRange }}</span>
          </el-form-item>

          <el-form-item v-if="queryParams.dataType === 'month'" label="年月" prop="yearMonth">
            <el-date-picker
              v-model="queryParams.yearMonth"
              type="month"
              placeholder="选择年月"
              value-format="yyyy-MM"
            />
          </el-form-item>

          <el-form-item v-if="queryParams.dataType === 'day' || !queryParams.dataType" label="开始日期" prop="startDate">
            <el-date-picker
              v-model="queryParams.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="yyyy-MM-dd"
              clearable
            />
          </el-form-item>
          <el-form-item v-if="queryParams.dataType === 'day' || !queryParams.dataType" label="结束日期" prop="endDate">
            <el-date-picker
              v-model="queryParams.endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="yyyy-MM-dd"
              clearable
            />
          </el-form-item>
          <el-form-item label="组" prop="groupName">
            <el-input
              v-model="queryParams.groupName"
              placeholder="请输入组名"
              clearable
              size="small"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="标签" prop="tagName">
            <el-input
              v-model="queryParams.tagName"
              placeholder="请输入标签名"
              clearable
              size="small"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="数据级别" prop="dataLevel">
            <el-checkbox v-model="queryParams.onlyGroup" @change="handleOnlyGroupChange">只看分组</el-checkbox>
            <el-checkbox v-model="queryParams.onlyTag" @change="handleOnlyTagChange">只看标签</el-checkbox>
          </el-form-item>
          <el-form-item>
            <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>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['wecom:customerStatisticsV2:export']"
            >导出</el-button>
          </el-col>
          <!-- 重新计算按钮已隐藏
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="handleRecalculate"
              v-hasPermi="['wecom:customerStatisticsV2:recalculate']"
            >重新计算</el-button>
          </el-col>
          -->
          <el-col :span="1.5">
            <el-popover
              placement="bottom"
              width="400"
              trigger="click"
            >
              <div class="column-config">
                <div class="config-header">
                  <span>选择要显示的列</span>
                  <el-button type="text" size="mini" @click="selectAllColumns">全选</el-button>
                  <el-button type="text" size="mini" @click="unselectAllColumns">全不选</el-button>
                  <el-button type="text" size="mini" @click="resetColumns">重置</el-button>
                </div>
                <el-divider></el-divider>
                <div class="config-body">
                  <div v-for="group in columnGroups" :key="group.label" class="config-group">
                    <div class="group-title">{{ group.label }}</div>
                    <el-checkbox-group v-model="selectedColumns" class="checkbox-group">
                      <el-checkbox
                        v-for="col in group.columns"
                        :key="col.prop"
                        :label="col.prop"
                        class="checkbox-item"
                      >{{ col.label }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
              <el-button
                slot="reference"
                type="info"
                plain
                icon="el-icon-setting"
                size="mini"
              >列配置</el-button>
            </el-popover>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="dataList"
          row-key="id"
          border
          style="width: 100%"
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column label="组" align="left" prop="groupName" width="120" fixed>
            <template slot-scope="scope">
              <span :style="{fontWeight: scope.row.dataLevel === 1 ? 'bold' : 'normal', color: '#409EFF'}">
                {{ scope.row.groupName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="标签" align="left" prop="tagName" width="180" fixed>
            <template slot-scope="scope">
              <span v-if="scope.row.tagName" style="color: #606266; padding-left: 10px;">
                {{ scope.row.tagName }}
              </span>
              <span v-else style="color: #909399; font-style: italic;">-</span>
            </template>
          </el-table-column>
          <el-table-column label="日期" align="center" width="140" fixed>
            <template slot-scope="scope">
              <div v-if="queryParams.dataType === 'week'">
                <div>{{ scope.row.yearWeek }}</div>
                <div style="color: #909399; font-size: 12px;">{{ scope.row.dateRange }}</div>
              </div>
              <div v-else-if="queryParams.dataType === 'month'">
                <div>{{ scope.row.yearMonth }}</div>
                <div style="color: #909399; font-size: 12px;">{{ scope.row.dateRange }}</div>
              </div>
              <div v-else-if="queryParams.dataType === 'all'">
                <span>全部数据</span>
              </div>
              <span v-else>{{ parseTime(scope.row.curDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>

          <template v-for="col in allColumns">
            <el-table-column
              v-if="selectedColumns.includes(col.prop)"
              :key="col.prop"
              :label="col.label"
              :align="col.align || 'center'"
              :prop="col.prop"
              :width="col.width"
            >
              <template slot-scope="scope">
                <template v-if="col.editable && canEditCost(scope.row)">
                  <el-input-number
                    v-model="scope.row[col.prop]"
                    size="mini"
                    :controls="false"
                    :precision="col.precision || 2"
                    style="width: 100%"
                    @keyup.enter.native="handleInputCost(scope.row, scope.row[col.prop], col.costType || 'total')"
                  />
                </template>
                <span v-else-if="col.isPercent">{{ formatPercent(scope.row[col.prop]) }}</span>
                <span v-else>{{ scope.row[col.prop] }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { listCustomerStatisticsV2, treeCustomerStatisticsV2, exportCustomerStatisticsV2, inputCost, recalculateStatisticsRange } from "@/api/wecom/customerStatisticsV2"

const STORAGE_KEY = 'customerStatisticsV2_columns'

const DEFAULT_COLUMNS = [
  'totalCost', 'singleCost', 'orderCost', 'orderCount', 'customerCount', 'conversionRate',
  'timelyRate', 'parentRate', 'studentRate', 'teacherRate'
]

export default {
  name: "CustomerStatisticsV2",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      dataList: [],
      treeData: [], // 树状筛选数据（从/tree接口获取）
      weekDateRange: '', // 周日期范围显示

      queryParams: {
        pageNum: 1,
        pageSize: 20,
        dataType: 'day', // 默认按天
        startDate: undefined,
        endDate: undefined,
        year: new Date().getFullYear(),
        week: undefined,
        yearMonth: undefined,
        groupName: undefined,
        tagName: undefined,
        onlyGroup: false,
        onlyTag: false
      },
      selectedColumns: [],
      treeProps: {
        children: 'children',
        label: 'label'
      },
      columnGroups: [
        {
          label: '成本指标',
          columns: [
            { prop: 'totalCost', label: '总成本', width: 120, editable: true, costType: 'total' },
            { prop: 'singleCost', label: '单条成本', width: 100, editable: true, costType: 'single' },
            { prop: 'orderCost', label: '成单成本', width: 100 }
          ]
        },
        {
          label: '核心指标',
          columns: [
            { prop: 'orderCount', label: '成单数', width: 80 },
            { prop: 'customerCount', label: '进粉数', width: 80 },
            { prop: 'conversionRate', label: '转化率', width: 80, isPercent: true }
          ]
        },
        {
          label: '及时单指标',
          columns: [
            { prop: 'timelyRate', label: '及时单占比', width: 100, isPercent: true },
            { prop: 'nonTimelyRate', label: '非及时单占比', width: 110, isPercent: true }
          ]
        },
        {
          label: '客户属性',
          columns: [
            { prop: 'customerAttrCount', label: '客户属性数量', width: 110 },
            { prop: 'parentRate', label: '家长占比', width: 80 },
            { prop: 'studentRate', label: '学生占比', width: 80 },
            { prop: 'teacherRate', label: '老师占比', width: 80 },
            { prop: 'unknownRate', label: '未知占比', width: 80 }
          ]
        },
        {
          label: '意向度',
          columns: [
            { prop: 'intentionCount', label: '意向度数量', width: 100 },
            { prop: 'activeQuoteRate', label: '主动报价占比', width: 110 },
            { prop: 'passiveQuoteRate', label: '被动报价占比', width: 110 },
            { prop: 'noQuoteRate', label: '未开口报价占比', width: 120 },
            { prop: 'deletedQuoteRate', label: '已删除报价占比', width: 120 }
          ]
        },
        {
          label: '年级统计',
          columns: [
            { prop: 'gradeCount', label: '年级数量', width: 80 },
            { prop: 'primaryRate', label: '小学占比', width: 80 },
            { prop: 'middleRate', label: '初中占比', width: 80 },
            { prop: 'highRate', label: '高中占比', width: 80 }
          ]
        },
        {
          label: '出单率',
          columns: [
            { prop: 'parentOrderRate', label: '家长出单率', width: 100, isPercent: true },
            { prop: 'studentOrderRate', label: '学生出单率', width: 100, isPercent: true },
            { prop: 'teacherOrderRate', label: '老师出单率', width: 100, isPercent: true },
            { prop: 'unknownOrderRate', label: '未知出单率', width: 100, isPercent: true }
          ]
        }
      ]
    }
  },
  computed: {
    allColumns() {
      const cols = []
      this.columnGroups.forEach(group => {
        group.columns.forEach(col => {
          cols.push(col)
        })
      })
      return cols
    },
    treeFilterData() {
      // 直接使用/tree接口返回的数据
      return this.treeData
    },
    // 计算合计行数据
    summaryData() {
      if (!this.dataList || this.dataList.length === 0) {
        return []
      }
      const summary = {
        groupName: '合计',
        tagName: '',
        curDate: ''
      }
      // 只计算非百分比列的合计
      this.allColumns.forEach(col => {
        if (!col.isPercent) {
          let sum = 0
          let hasValue = false
          this.dataList.forEach(row => {
            const val = parseFloat(row[col.prop])
            if (!isNaN(val)) {
              sum += val
              hasValue = true
            }
          })
          summary[col.prop] = hasValue ? sum.toFixed(2) : '-'
        }
      })
      return [summary]
    }
  },
  created() {
    this.loadColumnConfig()
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    this.queryParams.startDate = `${year}-${month}-${day}`
    this.queryParams.endDate = `${year}-${month}-${day}`
    // 确保数据更新后再调用
    this.$nextTick(() => {
      this.getTreeData() // 加载树状数据
      this.getList() // 加载列表数据
    })
  },
  watch: {
    // 当日期变化时，重新加载树状数据
    'queryParams.startDate': function(newVal, oldVal) {
      if (newVal !== oldVal && (this.queryParams.dataType === 'day' || !this.queryParams.dataType)) {
        this.getTreeData()
      }
    },
    'queryParams.endDate': function(newVal, oldVal) {
      if (newVal !== oldVal && (this.queryParams.dataType === 'day' || !this.queryParams.dataType)) {
        this.getTreeData()
      }
    },
    // 监听周相关参数变化
    'queryParams.year': function(newVal, oldVal) {
      if (newVal !== oldVal && this.queryParams.dataType === 'week') {
        this.updateWeekDateRange()
        this.getTreeData()
      }
    },
    'queryParams.week': function(newVal, oldVal) {
      if (newVal !== oldVal && this.queryParams.dataType === 'week') {
        this.updateWeekDateRange()
        this.getTreeData()
      }
    },
    // 监听月参数变化
    'queryParams.yearMonth': function(newVal, oldVal) {
      if (newVal !== oldVal && this.queryParams.dataType === 'month') {
        this.getTreeData()
      }
    },
    // 监听列配置变化
    selectedColumns: {
      handler() {
        this.saveColumnConfig()
      },
      deep: true
    }
  },
  methods: {
    // 合计行计算方法
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index === 1 || index === 2) {
          sums[index] = ''
          return
        }

        // 检查是否是百分比列
        const col = this.allColumns.find(c => c.prop === column.property)
        if (col && col.isPercent) {
          sums[index] = ''
          return
        }

        // 计算非百分比列的合计
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + value
            } else {
              return prev
            }
          }, 0)
          sums[index] = sum.toFixed(2)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 格式化百分比显示
    formatPercent(value) {
      if (value === null || value === undefined || value === '') {
        return '-'
      }
      const num = parseFloat(value)
      if (isNaN(num)) {
        return '-'
      }
      return num.toFixed(2) + '%'
    },
    // 更新周日期范围显示（修复跨年周问题）
    updateWeekDateRange() {
      if (this.queryParams.year && this.queryParams.week) {
        const year = parseInt(this.queryParams.year)
        const week = this.queryParams.week
        const weekRange = this.calculateWeekRangeFixed(year, week)
        this.weekDateRange = weekRange.startDate + ' 至 ' + weekRange.endDate
      } else {
        this.weekDateRange = ''
      }
    },
    // 计算周范围（修复跨年问题）
    // 规则：
    // 1. 周的第一天是周一（不是周日）
    // 2. 第一周：从1月1日开始，到1月1日所在周的周日结束
    //    - 如果1月1日是周日，第一周只有1天（1月1日当天）
    // 3. 最后一周：从最后一周的周一（12月31日往前推）开始，到12月31日结束
    //    - 如果12月31日是周一，最后一周只有1天（12月31日当天）
    // 4. 不显示跨年的日期范围
    calculateWeekRangeFixed(year, week) {
      const jan1 = new Date(year, 0, 1)
      const jan1Weekday = jan1.getDay() // 0=周日，1=周一，...，6=周六
      const dec31 = new Date(year, 11, 31)
      const dec31Weekday = dec31.getDay() // 0=周日，1=周一，...，6=周六

      // 第一周：从1月1日开始
      if (week === 1) {
        const startDate = this.formatDate(jan1)
        // 计算第一周的结束日期（周日）
        // 如果1月1日是周日(0)，则第一周只有1天（当天）
        // 否则，计算到本周日
        let daysToSunday
        if (jan1Weekday === 0) {
          // 1月1日是周日，第一周只有1天
          daysToSunday = 0
        } else {
          // 1月1日不是周日，计算到本周日
          daysToSunday = 7 - jan1Weekday
        }
        const firstWeekEnd = new Date(jan1)
        firstWeekEnd.setDate(jan1.getDate() + daysToSunday)
        const endDate = this.formatDate(firstWeekEnd)
        return { startDate, endDate }
      }

      // 计算第一周的结束日期（周日）
      let firstWeekDays
      if (jan1Weekday === 0) {
        firstWeekDays = 0 // 1月1日是周日，第一周只有1天
      } else {
        firstWeekDays = 7 - jan1Weekday // 到本周日
      }
      const firstWeekEnd = new Date(jan1)
      firstWeekEnd.setDate(jan1.getDate() + firstWeekDays)

      // 计算第二周开始日期（第一周结束后的周一）
      const secondWeekStart = new Date(firstWeekEnd)
      secondWeekStart.setDate(firstWeekEnd.getDate() + 1)

      // 计算目标周的开始和结束
      // 从第二周开始，每周都是周一到周日
      const targetWeekStart = new Date(secondWeekStart)
      targetWeekStart.setDate(secondWeekStart.getDate() + (week - 2) * 7)

      const targetWeekEnd = new Date(targetWeekStart)
      targetWeekEnd.setDate(targetWeekStart.getDate() + 6)

      // 如果目标周的结束超过了12月31日，则调整到12月31日
      let endDate = this.formatDate(targetWeekEnd)
      if (targetWeekEnd > dec31) {
        endDate = this.formatDate(dec31)
      }

      // 如果开始日期已经跨年了（大于12月31日），则返回空
      if (targetWeekStart > dec31) {
        return { startDate: '', endDate: '' }
      }

      return {
        startDate: this.formatDate(targetWeekStart),
        endDate: endDate
      }
    },
    // 获取指定周的开始日期（周一）- 旧方法，保留用于兼容
    getWeekStartDate(year, week) {
      const date = new Date(year, 0, 1)
      const dayOfWeek = date.getDay()
      const daysToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek
      date.setDate(date.getDate() + daysToMonday)
      date.setDate(date.getDate() + (week - 1) * 7)
      return date
    },
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return year + '-' + month + '-' + day
    },
    loadColumnConfig() {
      const saved = localStorage.getItem(STORAGE_KEY)
      if (saved) {
        try {
          this.selectedColumns = JSON.parse(saved)
        } catch (e) {
          this.selectedColumns = [...DEFAULT_COLUMNS]
        }
      } else {
        this.selectedColumns = [...DEFAULT_COLUMNS]
      }
    },
    saveColumnConfig() {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(this.selectedColumns))
    },
    selectAllColumns() {
      this.selectedColumns = this.allColumns.map(col => col.prop)
      this.saveColumnConfig()
    },
    unselectAllColumns() {
      this.selectedColumns = []
      this.saveColumnConfig()
    },
    resetColumns() {
      this.selectedColumns = [...DEFAULT_COLUMNS]
      this.saveColumnConfig()
    },
    // 只看分组变化
    handleOnlyGroupChange(val) {
      if (val) {
        this.queryParams.onlyTag = false
      }
      this.handleQuery()
    },
    // 只看标签变化
    handleOnlyTagChange(val) {
      if (val) {
        this.queryParams.onlyGroup = false
      }
      this.handleQuery()
    },
    handleTreeNodeClick(data) {
      // 自动填入筛选条件
      if (data.type === 'group') {
        this.queryParams.groupName = data.groupName
        this.queryParams.tagName = undefined
      } else if (data.type === 'tag') {
        this.queryParams.groupName = data.groupName
        this.queryParams.tagName = data.tagName
      }
      // 触发查询
      this.handleQuery()
    },
    resetTreeFilter() {
      this.queryParams.groupName = undefined
      this.queryParams.tagName = undefined
      this.$refs.filterTree.setCurrentKey(null)
      this.handleQuery()
    },
    canEditCost(row) {
      // 只有按天查询时才允许编辑成本
      if (this.queryParams.dataType !== 'day') {
        return false
      }
      return row.dataLevel === 1 || row.dataLevel === 2
    },
    // 获取树状筛选数据（从/tree接口）
    getTreeData() {
      let params = {}
      if (this.queryParams.dataType === 'day' || !this.queryParams.dataType) {
        // 按天查询，使用开始日期和结束日期
        params = {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate
        }
      } else if (this.queryParams.dataType === 'week') {
        // 计算周的开始和结束日期
        const weekRange = this.calculateWeekRange(this.queryParams.year, this.queryParams.week)
        params = {
          startDate: weekRange.startDate,
          endDate: weekRange.endDate
        }
      } else if (this.queryParams.dataType === 'month') {
        // 计算月的开始和结束日期
        const monthRange = this.calculateMonthRange(this.queryParams.yearMonth)
        params = {
          startDate: monthRange.startDate,
          endDate: monthRange.endDate
        }
      } else if (this.queryParams.dataType === 'all') {
        // 全部数据，不传递日期参数
        params = {}
      }
      console.log('getTreeData called with params:', params, 'dataType:', this.queryParams.dataType)
      treeCustomerStatisticsV2(params).then(response => {
        console.log('getTreeData response:', response)
        this.treeData = response.data || []
      }).catch(error => {
        console.error('getTreeData error:', error)
      })
    },
    // 计算周的开始和结束日期
    calculateWeekRange(year, week) {
      const start = new Date(year, 0, 1)
      const diff = (week - 1) * 7 * 24 * 60 * 60 * 1000
      const startDate = new Date(start.getTime() + diff - ((start.getDay() + 6) % 7) * 24 * 60 * 60 * 1000)
      const endDate = new Date(startDate.getTime() + 6 * 24 * 60 * 60 * 1000)
      return {
        startDate: this.parseTime(startDate, '{y}-{m}-{d}'),
        endDate: this.parseTime(endDate, '{y}-{m}-{d}')
      }
    },
    // 计算月的开始和结束日期
    calculateMonthRange(yearMonth) {
      if (!yearMonth) {
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        yearMonth = `${year}-${month}`
      }
      const [year, month] = yearMonth.split('-')
      const startDate = new Date(year, month - 1, 1)
      const endDate = new Date(year, month, 0)
      return {
        startDate: this.parseTime(startDate, '{y}-{m}-{d}'),
        endDate: this.parseTime(endDate, '{y}-{m}-{d}')
      }
    },
    // 获取列表数据（从/list接口）
    getList() {
      this.loading = true
      listCustomerStatisticsV2(this.queryParams).then(response => {
        this.dataList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleDataTypeChange() {
      // 切换数据维度时，重置相关参数
      if (this.queryParams.dataType === 'day') {
        // 按天：设置默认日期为今天
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        this.queryParams.startDate = `${year}-${month}-${day}`
        this.queryParams.endDate = `${year}-${month}-${day}`
        // 清除其他类型的参数
        this.queryParams.year = undefined
        this.queryParams.week = undefined
        this.queryParams.yearMonth = undefined
        this.weekDateRange = ''
      } else if (this.queryParams.dataType === 'week') {
        // 按周：计算当前周，清除天数参数
        const now = new Date()
        // 使用字符串格式与 el-date-picker 的 value-format 保持一致
        this.queryParams.year = String(now.getFullYear())
        const start = new Date(now.getFullYear(), 0, 1)
        const diff = now - start + ((start.getDay() + 6) % 7) * 86400000
        this.queryParams.week = Math.floor(diff / 604800000) + 1
        this.updateWeekDateRange()
        // 清除天数参数
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
        this.queryParams.yearMonth = undefined
      } else if (this.queryParams.dataType === 'month') {
        // 按月：设置当前年月，清除天数参数
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        this.queryParams.yearMonth = `${year}-${month}`
        // 清除天数参数
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
        this.queryParams.year = undefined
        this.queryParams.week = undefined
        this.weekDateRange = ''
      } else if (this.queryParams.dataType === 'all') {
        // 全部数据：清除所有日期参数
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
        this.queryParams.year = undefined
        this.queryParams.week = undefined
        this.queryParams.yearMonth = undefined
        this.weekDateRange = ''
      }
      // 重新加载树状数据
      this.getTreeData()
      this.handleQuery()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.dataType = 'day'
      this.queryParams.groupName = undefined
      this.queryParams.tagName = undefined
      this.queryParams.onlyGroup = false
      this.queryParams.onlyTag = false
      // 使用字符串格式与 el-date-picker 的 value-format 保持一致
      this.queryParams.year = String(new Date().getFullYear())
      this.queryParams.week = undefined
      this.queryParams.yearMonth = undefined
      this.weekDateRange = ''
      // 重置日期为今天
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      this.queryParams.startDate = `${year}-${month}-${day}`
      this.queryParams.endDate = `${year}-${month}-${day}`
      this.$refs.filterTree.setCurrentKey(null)
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleExport() {
      const formattedDate = this.parseTime(new Date(), '{y}-{m}-{d}')
      this.download('/wecom/customerStatisticsV2/export', {
        ...this.queryParams
      }, `流量看板V2数据_${formattedDate}.xlsx`)
    },
    handleInputCost(row, cost, inputType) {
      if (cost === '' || cost === null || cost === undefined) {
        this.$modal.msgWarning("请输入成本金额")
        return
      }

      const numCost = Number(cost)
      if (isNaN(numCost)) {
        this.$modal.msgWarning("成本金额必须为数字")
        return
      }

      if (numCost < 0) {
        this.$modal.msgWarning("成本金额不能为负数")
        return
      }

      let formattedDate = row.curDate
      if (row.curDate instanceof Date) {
        formattedDate = this.parseTime(row.curDate, '{y}-{m}-{d}')
      } else if (typeof row.curDate === 'string' && row.curDate.length > 10) {
        formattedDate = row.curDate.substring(0, 10)
      }

      const costTypeName = inputType === 'single' ? '单条成本' : '总成本'
      const displayName = row.tagName || row.groupName

      this.$modal.confirm(`确认修改 ${formattedDate} ${displayName} 的${costTypeName}为 ${numCost}？`).then(() => {
        inputCost({
          date: formattedDate,
          groupName: row.groupName,
          tagName: row.tagName || null,
          costValue: numCost,
          inputType: inputType
        }).then(() => {
          this.$modal.msgSuccess("修改成功")
          this.getList()
        }).catch(() => {
          this.getList()
        })
      }).catch(() => {
        this.getList()
      })
    },
    handleRecalculate() {
      if (!this.queryParams.startDate || !this.queryParams.endDate) {
        this.$modal.msgWarning("请选择日期范围")
        return
      }

      this.$modal.confirm(`确认重新计算 ${this.queryParams.startDate} 至 ${this.queryParams.endDate} 的统计数据？`).then(() => {
        recalculateStatisticsRange(this.queryParams.startDate, this.queryParams.endDate).then(() => {
          this.$modal.msgSuccess("重新计算成功")
          this.getList()
        })
      })
    }
  }
}
</script>

<style scoped>
.el-container {
  min-height: calc(100vh - 180px);
}

.tree-aside {
  background: #fff;
  border-right: 1px solid #e6e6e6;
  padding: 10px;
  overflow-y: auto;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 5px;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 10px;
}

.tree-header span {
  font-weight: bold;
  font-size: 14px;
  color: #333;
}

.filter-tree {
  background: transparent;
}

.tree-node {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.group-node {
  font-weight: bold;
  color: #409EFF;
}

.tag-node {
  color: #606266;
  padding-left: 5px;
}

.node-count {
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
}

.el-table .el-input-number {
  width: 100%;
}

.column-config {
  max-height: 500px;
  overflow-y: auto;
}

.config-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 10px;
}

.config-header span {
  font-weight: bold;
  font-size: 14px;
}

.config-body {
  padding: 10px 0;
}

.config-group {
  margin-bottom: 15px;
}

.group-title {
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
  padding-left: 5px;
  border-left: 3px solid #409EFF;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
}

.checkbox-item {
  margin-right: 15px;
  margin-bottom: 8px;
  width: 120px;
}

/* 合计表格样式 */
.summary-table {
  margin-bottom: 0;
}

.summary-table.el-table {
  background-color: #f5f7fa;
}

.summary-table.el-table td.el-table__cell {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #606266;
}

.summary-table.el-table--border {
  border-bottom: none;
}

/* 隐藏合计表格的滚动条 */
.summary-table .el-table__body-wrapper {
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
}

.summary-table .el-table__body-wrapper::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}
</style>
