<template>
  <div class="app-container statistics-container">
    <!-- 搜索筛选 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-form">
      <el-form-item label="站点" prop="siteId">
        <el-select
          v-model="queryParams.siteId"
          placeholder="请选择站点"
          clearable
          size="small"
          filterable
        >
          <el-option
            v-for="item in siteList"
            :key="item.id"
            :label="item.siteName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="广告商" prop="advertiserId">
        <el-select
          v-model="queryParams.advertiserId"
          placeholder="请选择广告商"
          clearable
          size="small"
          filterable
        >
          <el-option
            v-for="item in advertiserList"
            :key="item.id"
            :label="item.advertiserName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          size="small"
          style="width: 280px"
        />
      </el-form-item>
      <el-form-item>
        <div class="date-quick-buttons">
          <el-button type="primary" plain size="small" @click="setDateRange('today')">今日</el-button>
          <el-button type="primary" plain size="small" @click="setDateRange('yesterday')">昨日</el-button>
          <el-button type="primary" plain size="small" @click="setDateRange('week')">本周</el-button>
          <el-button type="primary" plain size="small" @click="setDateRange('month')">本月</el-button>
          <el-button type="primary" plain size="small" @click="setDateRange('30days')">30天</el-button>
        </div>
      </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
          plain
          type="success"
          icon="el-icon-refresh"
          size="mini"
          @click="getList"
        >刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table border v-loading="loading" :data="statisticsList" class="stats-table">
      <el-table-column label="站点ID" align="center" prop="siteId" width="80" />
      <el-table-column label="站点名称" align="center" prop="siteName" min-width="150" show-overflow-tooltip />
      
      <!-- 流量数据 -->
      <el-table-column label="流量数据" align="center">
        <el-table-column label="PV" align="center" prop="pv" width="100">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.pv || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="UV" align="center" prop="uv" width="100">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.uv || 0 }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 广告数据 -->
      <el-table-column label="广告数据" align="center">
        <el-table-column label="展示数" align="center" prop="impressionCount" width="100">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.impressionCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击数" align="center" prop="clickCount" width="100">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.clickCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击率(%)" align="center" prop="clickRate" width="100">
          <template slot-scope="scope">
            <span class="rate-text">{{ scope.row.clickRate || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="平均点击单价" align="center" prop="avgClickPrice" width="120">
          <template slot-scope="scope">
            <span class="money-text">¥{{ scope.row.avgClickPrice || 0 }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 成本数据 -->
      <el-table-column label="成本数据" align="center">
        <el-table-column label="账面花费" align="center" prop="accountCost" width="120">
          <template slot-scope="scope">
            <span class="money-text">¥{{ scope.row.accountCost || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际花费" align="center" prop="actualCost" width="120">
          <template slot-scope="scope">
            <span class="money-text primary">¥{{ scope.row.actualCost || 0 }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 转化数据 -->
      <el-table-column label="转化数据" align="center">
        <el-table-column label="名片数" align="center" prop="cardCount" width="100">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.cardCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="名片获取率(%)" align="center" prop="cardAcquireRate" width="120">
          <template slot-scope="scope">
            <span class="rate-text">{{ scope.row.cardAcquireRate || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="名片获取成本" align="center" prop="cardAcquireCost" width="120">
          <template slot-scope="scope">
            <span class="money-text">¥{{ scope.row.cardAcquireCost || 0 }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 企微数据 -->
      <el-table-column label="企微数据" align="center">
        <el-table-column label="企微添加人数" align="center" prop="wechatAddCount" width="120">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.wechatAddCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="企微添加率(%)" align="center" prop="wechatAddRate" width="120">
          <template slot-scope="scope">
            <span class="rate-text">{{ scope.row.wechatAddRate || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="企微添加成本" align="center" prop="wechatAddCost" width="120">
          <template slot-scope="scope">
            <span class="money-text">¥{{ scope.row.wechatAddCost || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="企微加群人数" align="center" prop="wechatGroupCount" width="120">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.wechatGroupCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="企微加群率(%)" align="center" prop="wechatGroupRate" width="120">
          <template slot-scope="scope">
            <span class="rate-text">{{ scope.row.wechatGroupRate || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="企微删除人数" align="center" prop="wechatDeleteCount" width="120">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.wechatDeleteCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="企微删除率" align="center" prop="wechatDeleteCountRate" width="120">
          <template slot-scope="scope">
            <span class="rate-text">{{ scope.row.wechatDeleteCountRate || 0 }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 小程序数据 -->
      <el-table-column label="小程序数据" align="center">
        <el-table-column label="发起进入小程序人数" align="center" prop="miniLaunchIndexCount" width="140">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.miniLaunchIndexCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="进入小程序落地页" align="center" prop="miniAuthIndexCount" width="140">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.miniAuthIndexCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="小程序授权人数" align="center" prop="miniAuthCount" width="140">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.miniAuthCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="进入出码页人数" align="center" prop="miniQrCodeIndexCount" width="140">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.miniQrCodeIndexCount || 0 }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 下次转化数据 -->
      <el-table-column label="下次转化数据" align="center">
        <el-table-column label="报名成功人数" align="center" prop="registerSuccessCount" width="120">
          <template slot-scope="scope">
            <span class="number-text">{{ scope.row.registerSuccessCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报名成功加微率(%)" align="center" prop="registerWechatRate" width="140">
          <template slot-scope="scope">
            <span class="rate-text">{{ scope.row.registerWechatRate || 0 }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180" fixed="right">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 详情对话框 -->
    <el-dialog title="统计详情" :visible.sync="detailOpen" width="900px" append-to-body class="detail-dialog">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="站点ID">{{ detail.siteId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="站点名称">{{ detail.siteName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="PV">{{ detail.pv || 0 }}</el-descriptions-item>
        <el-descriptions-item label="UV">{{ detail.uv || 0 }}</el-descriptions-item>
        <el-descriptions-item label="展示数">{{ detail.impressionCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="点击数">{{ detail.clickCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="点击率">{{ detail.clickRate || 0 }}</el-descriptions-item>
        <el-descriptions-item label="平均点击单价">¥{{ detail.avgClickPrice || 0 }}</el-descriptions-item>
        <el-descriptions-item label="账面花费">¥{{ detail.accountCost || 0 }}</el-descriptions-item>
        <el-descriptions-item label="实际花费">¥{{ detail.actualCost || 0 }}</el-descriptions-item>
        <el-descriptions-item label="名片数">{{ detail.cardCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="名片获取率">{{ detail.cardAcquireRate || 0 }}</el-descriptions-item>
        <el-descriptions-item label="名片获取成本">¥{{ detail.cardAcquireCost || 0 }}</el-descriptions-item>
        <el-descriptions-item label="企微添加人数">{{ detail.wechatAddCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="企微添加率">{{ detail.wechatAddRate || 0 }}</el-descriptions-item>
        <el-descriptions-item label="企微添加成本">¥{{ detail.wechatAddCost || 0 }}</el-descriptions-item>
        <el-descriptions-item label="企微加群人数">{{ detail.wechatGroupCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="企微加群率">{{ detail.wechatGroupRate || 0 }}</el-descriptions-item>
        <el-descriptions-item label="报名成功人数">{{ detail.registerSuccessCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="报名成功加微率">{{ detail.registerWechatRate || 0 }}</el-descriptions-item>
        <el-descriptions-item label="企微删除率">{{ detail.wechatDeleteCountRate || 0 }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detail.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageSiteStatistics, getSiteStatistics } from "@/api/adv/siteStatistics";
import { listSite } from "@/api/adv/site";
import { pageAdvertiser } from "@/api/adv/advertiser";

export default {
  name: "SiteStatistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计列表
      statisticsList: [],
      // 站点列表
      siteList: [],
      // 详情对话框
      detailOpen: false,
      // 详情数据
      detail: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        siteId: undefined,
        advertiserId: undefined,
        startDate: undefined,
        endDate: undefined,
        dateRange: []
      },
      // 广告商列表
      advertiserList: []
    };
  },
  created() {
    // 从 URL参数获取站点ID
    const siteId = this.$route.query.siteId;
    if (siteId) {
      this.queryParams.siteId = parseInt(siteId);
    }
    // 默认设置今天的日期范围
    const today = new Date();
    const dateStr = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0');
    this.queryParams.startDate = dateStr;
    this.queryParams.endDate = dateStr;
    this.queryParams.dateRange = [dateStr, dateStr];
    this.getSiteList();
    this.getAdvertiserList();
    this.getList();
  },
  methods: {
    /** 查询站点列表 */
    getSiteList() {
      listSite().then(response => {
        this.siteList = response.data || [];
      });
    },
    /** 查询广告商列表 */
    getAdvertiserList() {
      pageAdvertiser({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.advertiserList = response.data.records || [];
      }).catch(error => {
        console.error('查询广告商列表失败:', error);
        this.advertiserList = [];
      });
    },
    /** 设置日期范围 */
    setDateRange(rangeType) {
      const today = new Date();
      let startDate, endDate;
      
      if (rangeType === 'today') {
        startDate = new Date(today);
        endDate = new Date(today);
      } else if (rangeType === 'yesterday') {
        startDate = new Date(today.getTime() - 24 * 60 * 60 * 1000);
        endDate = new Date(today.getTime() - 24 * 60 * 60 * 1000);
      } else if (rangeType === 'week') {
        const dayOfWeek = today.getDay();
        const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
        startDate = new Date(today.getFullYear(), today.getMonth(), diff);
        endDate = new Date(today);
      } else if (rangeType === 'month') {
        startDate = new Date(today.getFullYear(), today.getMonth(), 1);
        endDate = new Date(today);
      } else if (rangeType === '30days') {
        startDate = new Date(today.getTime() - 29 * 24 * 60 * 60 * 1000);
        endDate = new Date(today);
      }
      
      const formatDate = (date) => {
        return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
      };
      
      this.queryParams.startDate = formatDate(startDate);
      this.queryParams.endDate = formatDate(endDate);
      this.queryParams.dateRange = [this.queryParams.startDate, this.queryParams.endDate];
    },
    /** 查询统计列表 */
    getList() {
      this.loading = true;
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        siteId: this.queryParams.siteId,
        advertiserId: this.queryParams.advertiserId,
        startDate: this.queryParams.startDate,
        endDate: this.queryParams.endDate
      };
      pageSiteStatistics(params).then(response => {
        this.statisticsList = response.data.records || [];
        this.total = response.data.total || 0;
        this.loading = false;
      }).catch((error) => {
        console.error('查询统计列表失败:', error);
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 不会会改版面pageNum,维持已有的pageNum
      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        this.queryParams.startDate = this.queryParams.dateRange[0];
        this.queryParams.endDate = this.queryParams.dateRange[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重新设置为today是不是更好？这里应该是按照简易逻辑重新设置日期
      const today = new Date();
      const dateStr = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0');
      this.queryParams.startDate = dateStr;
      this.queryParams.endDate = dateStr;
      this.queryParams.dateRange = [dateStr, dateStr];
      this.handleQuery();
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      getSiteStatistics(row.id).then(response => {
        this.detail = response.data;
        this.detailOpen = true;
      });
    },
    /** 获取ROI标签类型 */
    getRoiType(roi) {
      const value = parseFloat(roi || 0);
      if (value >= 3) return 'success';
      if (value >= 2) return 'warning';
      if (value >= 1) return 'info';
      return 'danger';
    }
  }
};
</script>

<style lang="scss" scoped>
.statistics-container {
  padding: 20px;
}

// 搜索表单样式
.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

// 表格样式
.stats-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  
  .number-text {
    color: #409eff;
    font-weight: 500;
  }
  
  .rate-text {
    color: #e6a23c;
    font-weight: 500;
  }
  
  .money-text {
    color: #f56c6c;
    font-weight: 500;
    
    &.primary {
      color: #409eff;
    }
    
    &.success {
      color: #67c23a;
    }
  }
  
  ::v-deep .el-table__header {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
      font-size: 13px;
    }
  }
  
  ::v-deep .el-table__row {
    transition: all 0.3s ease;
    
    &:hover {
      background-color: rgba(102, 126, 234, 0.05);
    }
  }
}

// 工具栏样式
.mb8 {
  margin-bottom: 15px;
  
  .el-button {
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
    
    &.el-button--success {
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
      }
    }
  }
}

// 日期快速设置按钮样式
.date-quick-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  
  .el-button {
    padding: 8px 18px;
    font-size: 13px;
    font-weight: 500;
    border-radius: 6px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
    
    &:active {
      transform: translateY(0);
    }
  }
}

// 详情对话框样式
::v-deep .detail-dialog {
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
    margin: 0;
    border-radius: 4px 4px 0 0;
    
    .el-dialog__title {
      color: #fff;
      font-size: 18px;
      font-weight: 500;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
      font-size: 20px;
      
      &:hover {
        color: #f0f0f0;
      }
    }
  }
  
  .el-dialog__body {
    padding: 25px 30px;
  }
  
  .el-descriptions {
    ::v-deep .el-descriptions-item__label {
      font-weight: 600;
      color: #606266;
      background-color: #fafafa;
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    padding: 10px 24px;
    border-radius: 6px;
    font-weight: 500;
  }
}
</style>
