<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="日期" prop="createTime">
        <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        @change="xdChange"></el-date-picker>
      </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"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['course:courseRedPacketLog:exportMoneyList']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="projectRedPacketList" v-hasPermi="['course:courseRedPacketLog:moneyList']">
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="红包消耗金额(元)" align="center" prop="money">
        <template slot-scope="{ row }">
          {{ row.money ? row.money.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
    </el-table>
    <div class="total-summary" v-hasPermi="['course:courseRedPacketLog:moneyList']">
      <span class="total-title">总计：</span>
      <span class="total-item">红包消耗金额: {{ calculatedTotalData.money.toFixed(2) }} 元</span>
    </div>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" v-hasPermi="['course:courseRedPacketLog:moneyList']" />
  </div>
</template>

<script>
import {exportProjectRedPacketMoney, getProjectRedPacketMoney} from "@/api/course/courseRedPacketLog";
import rightToolbar from "@/components/RightToolbar";
import Pagination from "@/components/Pagination";

export default {
  name: "ProjectRedPacketReport",
  components: {
    rightToolbar,
    Pagination
  },
  data() {
    return {
      calculatedTotalData: {
        money: 0
      },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 总条数
      total: 0,
      createTime: [],
      // 项目红包消耗列表数据
      projectRedPacketList: [],
      // 显示搜索条件
      showSearch: true,
      startTime: null,
      endTime: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: null, // 修改为startTime
        endTime: null     // 修改为endTime
      },
    };
  },
  created() {
    this.createTime = this.getDefaultDateRange();
    this.queryParams.startTime = this.createTime[0];
    this.queryParams.endTime = this.createTime[1];
    this.getList()
  },
  methods: {
    // 获取前一天日期范围
    getDefaultDateRange() {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);

      const year = yesterday.getFullYear();
      const month = String(yesterday.getMonth() + 1).padStart(2, '0');
      const day = String(yesterday.getDate()).padStart(2, '0');

      const yesterdayStr = `${year}-${month}-${day}`;
      return [yesterdayStr, yesterdayStr]; // 前一天开始和结束是同一天
    },
    calculateTotals() {
      // 重置总计数据
      this.calculatedTotalData = {
        money: 0
      };
      // 遍历当前页数据计算总和
      this.projectRedPacketList.forEach(item => {
        this.calculatedTotalData.money += Number(item.money) || 0;
      });
    },
    /** 查询项目红包消耗列表 */
    getList() {
      this.loading = true;
      getProjectRedPacketMoney(this.queryParams).then(response => {
        this.projectRedPacketList = response.rows;
        this.total = response.total;
        this.calculateTotals();
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      // 清空所有时间相关变量
      this.createTime = null;
      this.startTime = null;
      this.endTime = null;
      this.queryParams.startTime = null; // 重置时间参数
      this.queryParams.endTime = null;   // 重置时间参数
    },
    handleExport() {
      this.$confirm('是否确认导出项目红包消耗数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        // 调用导出API，传入查询参数
        exportProjectRedPacketMoney(this.queryParams)
          .then(response => {
            this.download(response.msg);
            this.msgSuccess('导出成功');
          })
          .catch(error => {
            console.error('导出失败:', error);
            this.msgError('导出失败');
          })
          .finally(() => {
            this.exportLoading = false;
          });
      }).catch(() => {
        // 用户取消导出，不执行任何操作
      });
    },
    xdChange() {
      if (this.createTime != null && this.createTime.length === 2) {
        this.queryParams.startTime = this.createTime[0];
        this.queryParams.endTime = this.createTime[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
    }
  }
};
</script>

<style scoped>
.total-summary {
  margin-top: 15px;
  padding: 15px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.total-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  margin-right: 20px;
}

.total-item {
  margin-right: 20px;
  font-size: 14px;
  color: #606266;
}
</style>
