<template>
  <div class="app-container">
    <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="indicatorName">
        <el-input
          v-model="queryParams.indicatorName"
          placeholder="请输入指标名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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:customerStatistics:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" width="180">
        <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>
      <el-table-column label="重要指标" align="center" prop="indicatorName" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="N组(投放)" align="center" prop="ntfGroup" width="100">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.ntfGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.ntfGroup,'ntfGroup')"
          />
          <span v-else>{{ scope.row.ntfGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="O组(公司孵化)" align="center" prop="ofhGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.ofhGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.ofhGroup,'ofhGroup')"
          />
          <span v-else>{{ scope.row.ofhGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="P组(商务)" align="center" prop="pswGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.pswGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.pswGroup,'pswGroup')"
          />
          <span v-else>{{ scope.row.pswGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="W组(A1组)" align="center" prop="wa1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.wa1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.wa1Group,'wa1Group')"
          />
          <span v-else>{{ scope.row.wa1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="X组(B1组)" align="center" prop="xb1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.xb1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.xb1Group,'xb1Group')"
          />
          <span v-else>{{ scope.row.xb1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Y组(C1组)" align="center" prop="yc1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.yc1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.yc1Group,'yc1Group')"
          />
          <span v-else>{{ scope.row.yc1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Z组(D1组)" align="center" prop="zd1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.zd1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.zd1Group,'zd1Group')"
          />
          <span v-else>{{ scope.row.zd1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AA组(E1组)" align="center" prop="aaGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.aaGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.aaGroup,'aaGroup')"
          />
          <span v-else>{{ scope.row.aaGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AC组(自然流)" align="center" prop="acGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.acGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.acGroup,'acGroup')"
          />
          <span v-else>{{ scope.row.acGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AD组(F1组)" align="center" prop="adGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.adGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.adGroup,'adGroup')"
          />
          <span v-else>{{ scope.row.adGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AE组(G1组)" align="center" prop="aeGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="canEditCost(scope.row)"
            v-model="scope.row.aeGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @keyup.enter.native="handleUpdateCost(scope.row,scope.row.aeGroup,'aeGroup')"
          />
          <span v-else>{{ scope.row.aeGroup }}</span>
        </template>
      </el-table-column>
    </el-table>

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

<script>
import { listCustomerStatistics, updateCustomerStatistics,exportCustomerStatistics } from "@/api/wecom/customerStatistics"

export default {
  name: "CustomerStatistics",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      dataList: [],
      weekDateRange: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dataType: undefined,
        year: undefined,
        week: undefined,
        yearMonth: undefined,
        startDate: undefined,
        endDate: undefined,
        indicatorName: undefined
      }
    }
  },
  watch: {
    'queryParams.week'(newVal) {
      this.updateWeekDateRange()
    },
    'queryParams.year'(newVal) {
      this.updateWeekDateRange()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    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
    },
    canEditCost(row) {
      const isCostIndicator = row.indicatorName === '总成本（当日）' || row.indicatorName === '单条成本（当日）'
      const isDayMode = this.queryParams.dataType === 'day' || !this.queryParams.dataType
      return isCostIndicator && isDayMode
    },
    getList() {
      this.loading = true
      console.log('=== 开始请求数据 ===')
      console.log('查询参数:', this.queryParams)

      listCustomerStatistics(this.queryParams).then(response => {
        console.log('=== API 返回数据 ===')
        console.log('完整响应:', response)
        console.log('rows 数据:', response.rows)
        console.log('total:', response.total)
        console.log('rows 长度:', response.rows ? response.rows.length : 0)

        if (response.rows && response.rows.length > 0) {
          console.log('第一条数据:', response.rows[0])
          console.log('第一条数据的 aaGroup:', response.rows[0].aaGroup)
          console.log('第一条数据的 nGroup:', response.rows[0].nGroup)
        } else {
          console.warn('rows 为空或不存在')
        }

        this.dataList = response.rows
        this.total = response.total
        this.loading = false

        console.log('=== 数据绑定完成 ===')
        console.log('dataList:', this.dataList)
        console.log('total:', this.total)
      }).catch(error => {
        console.error('=== API 请求失败 ===')
        console.error('错误信息:', error)
        this.loading = false
      })
    },
    handleDataTypeChange() {
      const dataType = this.queryParams.dataType

      if (dataType === 'day' || !dataType) {
        // 按天：设置默认日期为今天
        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 (dataType === 'week') {
        // 按周：计算当前周，清除天数参数
        const now = new Date()
        // 使用字符串格式与 el-date-picker 的 value-format 保持一致
        this.queryParams.year = String(now.getFullYear())
        // 计算当前是第几周
        const jan1 = new Date(now.getFullYear(), 0, 1)
        const jan1Weekday = jan1.getDay() // 0=周日，1=周一，...，6=周六

        // 计算第一周的结束日期（周日）
        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 diffTime = now - secondWeekStart
        const diffWeeks = Math.floor(diffTime / (7 * 24 * 60 * 60 * 1000))
        this.queryParams.week = diffWeeks + 2 // 第2周开始计数

        this.updateWeekDateRange()
        // 清除天数参数
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
        this.queryParams.yearMonth = undefined
      } else if (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 (dataType === 'all') {
        // 全部数据：清除所有日期参数
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
        this.queryParams.year = undefined
        this.queryParams.week = undefined
        this.queryParams.yearMonth = undefined
        this.weekDateRange = ''
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleDataTypeChange()
      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/customerStatistics/export', {
        ...this.queryParams
      }, `流量看板数据_${formattedDate}.xlsx`)
    },
    handleUpdateCost(row, cost, attr) {
      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;
      }

      const indicatorName = row.indicatorName;
      const type = indicatorName === '单条成本（当日）' ? 'single' : 'total';
      const costTypeName = indicatorName === '单条成本（当日）' ? '单条成本' : '总成本';
      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);
      }

      this.$modal.confirm(`确认修改${formattedDate}的${costTypeName}为 ${numCost}？`).then(() => {
        updateCustomerStatistics(formattedDate, numCost, attr, type).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        }).catch(() => {
          this.getList();
        });
      }).catch(() => {
        this.getList();
      });
    }
  }
}
</script>
