<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="handleDateRangeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="门店" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择门店" clearable>
          <el-option
            v-for="store in storeOptions"
            :key="store.id"
            :label="store.name"
            :value="store.id">
          </el-option>
        </el-select>
      </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">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="statisticsList" border>
      <!-- 基本信息 -->
      <el-table-column label="统计日期" align="center" prop="day" width="100">
        <template slot-scope="scope">
          {{ parseDay(scope.row.day) }}
        </template>
      </el-table-column>

<!--      <el-table-column label="统计门店" align="center" prop="day" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.storeName }}-->
<!--        </template>-->
<!--      </el-table-column>-->

      <!-- 总计统计 -->
      <el-table-column label="总计" align="center">
        <el-table-column label="订单总数" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.clothOrderCount + scope.row.goodsOrderCount }}
          </template>
        </el-table-column>
        <el-table-column label="订单总额" align="center" width="120">
          <template slot-scope="scope">
            {{ (scope.row.clothOrderAmount + scope.row.goodsOrderAmount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="总支付金额" align="center" width="120">
          <template slot-scope="scope">
            {{ calculateTotalPayAmount(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="总退款金额" align="center" width="120">
          <template slot-scope="scope">
            {{ calculateTotalRefundAmount(scope.row) }}
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 洗衣订单统计 -->
      <el-table-column label="洗衣订单" align="center">
        <el-table-column label="订单数" align="center" prop="clothOrderCount" width="90" />
        <el-table-column label="衣物件数" align="center" prop="clothCount" width="90" />
        <el-table-column label="订单总额" align="center" prop="clothOrderAmount" width="100" />
        <el-table-column label="支付金额" align="center">
          <el-table-column label="微信支付" align="center" prop="clothWechatAmount" width="100" />
          <el-table-column label="支付宝" align="center" prop="clothAlipayAmount" width="100" />
          <el-table-column label="现金" align="center" prop="clothCashAmount" width="100" />
          <el-table-column label="会员卡" align="center" prop="clothMemberAmount" width="100" />
        </el-table-column>
        <el-table-column label="退款金额" align="center">
          <el-table-column label="微信退款" align="center" prop="clothWechatRefundAmount" width="100" />
          <el-table-column label="支付宝退款" align="center" prop="clothAlipayRefundAmount" width="100" />
          <el-table-column label="现金退款" align="center" prop="clothCashRefundAmount" width="100" />
          <el-table-column label="会员卡退款" align="center" prop="clothMemberRefundAmount" width="100" />
        </el-table-column>
      </el-table-column>

      <!-- 商品订单统计 -->
      <el-table-column label="商品订单" align="center">
        <el-table-column label="订单数" align="center" prop="goodsOrderCount" width="90" />
        <el-table-column label="订单总额" align="center" prop="goodsOrderAmount" width="100" />
        <el-table-column label="支付金额" align="center">
          <el-table-column label="微信支付" align="center" prop="goodsWechatAmount" width="100" />
          <el-table-column label="支付宝" align="center" prop="goodsAlipayAmount" width="100" />
          <el-table-column label="现金" align="center" prop="goodsCashAmount" width="100" />
          <el-table-column label="会员卡" align="center" prop="goodsMemberAmount" width="100" />
        </el-table-column>
        <el-table-column label="退款金额" align="center">
          <el-table-column label="微信退款" align="center" prop="goodsWechatRefundAmount" width="100" />
          <el-table-column label="支付宝退款" align="center" prop="goodsAlipayRefundAmount" width="100" />
          <el-table-column label="现金退款" align="center" prop="goodsCashRefundAmount" width="100" />
          <el-table-column label="会员卡退款" align="center" prop="goodsMemberRefundAmount" width="100" />
        </el-table-column>
      </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 { listStatisticsByDate, getTotalStatistics, listplatformStatisticsByDay } from '@/api/settlement/statistics'
import { listStore } from "@/api/system/store";
import CountTo from 'vue-count-to'

export default {
  name: "PlatformStatisticsByDate",
  components: {
    CountTo
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计列表
      statisticsList: [],
      // 总统计数据
      totalStatistics: {},
      // 门店选项
      storeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startDate: null,
        endDate: null,
        storeId: null
      },
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近半个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    };
  },
  created() {
    // 设置默认日期范围为最近半个月
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
    this.dateRange = [this.formatDate(start), this.formatDate(end)];
    this.queryParams.startDate = this.dateRange[0];
    this.queryParams.endDate = this.dateRange[1];

    this.getList();
    this.getStoreOptions();
  },
  methods: {
    /** 格式化日期为 yyyy-MM-dd */
    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}`;
    },
    /** 日期范围变化处理 */
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.startDate = val[0];
        this.queryParams.endDate = val[1];
      } else {
        this.queryParams.startDate = null;
        this.queryParams.endDate = null;
      }
    },
    // 解析日期显示
    parseDay(day) {
      if (!day) return '';
      const str = day.toString();
      return `${str.substring(0, 4)}-${str.substring(4, 6)}-${str.substring(6, 8)}`;
    },
    // 计算总支付金额
    calculateTotalPayAmount(row) {
      const clothPay = (row.clothWechatAmount || 0) +
        (row.clothAlipayAmount || 0) +
        (row.clothCashAmount || 0) +
        (row.clothMemberAmount || 0);
      const goodsPay = (row.goodsWechatAmount || 0) +
        (row.goodsAlipayAmount || 0) +
        (row.goodsCashAmount || 0) +
        (row.goodsMemberAmount || 0);
      return (clothPay + goodsPay).toFixed(2);
    },
    // 计算总退款金额
    calculateTotalRefundAmount(row) {
      const clothRefund = (row.clothWechatRefundAmount || 0) +
        (row.clothAlipayRefundAmount || 0) +
        (row.clothCashRefundAmount || 0) +
        (row.clothMemberRefundAmount || 0);
      const goodsRefund = (row.goodsWechatRefundAmount || 0) +
        (row.goodsAlipayRefundAmount || 0) +
        (row.goodsCashRefundAmount || 0) +
        (row.goodsMemberRefundAmount || 0);
      return (clothRefund + goodsRefund).toFixed(2);
    },
    /** 查询统计列表 */
    getList() {
      this.loading = true;
      listplatformStatisticsByDay(this.queryParams).then(response => {
        this.statisticsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      // 获取总统计数据
      // getTotalStatistics(this.queryParams).then(response => {
      //   this.totalStatistics = response.data;
      // });
    },
    /** 获取门店选项 */
    getStoreOptions() {
      listStore().then(response => {
        this.storeOptions = response.rows;
      });

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置日期范围为最近半个月
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
      this.dateRange = [this.formatDate(start), this.formatDate(end)];
      this.queryParams.startDate = this.dateRange[0];
      this.queryParams.endDate = this.dateRange[1];
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有日期统计数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.download('/mapi/platform/statistics/order/byday/export', {
          ...this.queryParams
        }, `工厂日期报表统计_${new Date().getTime()}.xlsx`);
      });
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
.card-body {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  color: #409EFF;
}
</style>
