<template>
  <div class="app-container">
    <div class="head-container">
      <span style="margin-right:10px;">时间筛选 : </span>
      <el-date-picker
        v-model="date"
        :picker-options="pickerOptions"
        class="filter-item"
        end-placeholder="结束日期"
        range-separator="至"
        size="small"
        start-placeholder="开始日期"
        style="padding-right: 10px"
        type="daterange"
        value-format="yyyy-MM-dd"
        @blur="datePickerBlur"
        @change="datePickerChange"
      />
      <!-- icon="el-icon-search" -->
      <el-button
        class="filter-item"
        size="mini"
        style="margin-left: 10px"
        type="primary"
        @click="toQuery()"
      >查询
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        @click="download"
      >导出
      </el-button>
    </div>
    <!-- 头部信息 -->
    <div class="table-container">
      <span>总交易单数: {{ topData.orders }} 单</span>
      <span>订单总金额(元): {{ (topData.totalPrices / 100).toFixed(2) }}</span>
      <span>手续费总金额(元): {{ (topData.totalFees / 100).toFixed(2) }}</span>
      <span>实收总金额(元): {{ (topData.payTotals / 100).toFixed(2) }}</span>
      <span>申请退款总金额(元):
        {{ (topData.applyRefundAmounts / 100).toFixed(2) }}</span>
      <span>退款总金额(元): {{ (topData.refundAmounts / 100).toFixed(2) }}</span>
    </div>
    <!--表格渲染-->
    <el-table
      v-loading="loading"
      :data="data"
      border
      size="small"
      style="width: 100%"
    >
      <el-table-column align="center" fixed="left" label="序号" type="index" />
      <el-table-column align="center" label="交易时间" prop="days" width="90" />
      <el-table-column
        :show-overflow-tooltip="true"
        align="center"
        label="总交易单数"
        prop="orders"
      />
      <el-table-column align="center" label="订单总金额(元)" prop="totalPrices">
        <template slot-scope="scope">
          <span>{{ (scope.row.totalPrices / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手续费总金额(元)" prop="totalFees">
        <template slot-scope="scope">
          <span>{{ (scope.row.totalFees / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="实收总金额(元)" prop="payTotals">
        <template slot-scope="scope">
          <span>{{ (scope.row.payTotals / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="申请退款总金额(元)"
        prop="applyRefundAmounts"
      >
        <template slot-scope="scope">
          <span>{{ (scope.row.applyRefundAmounts / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="退款总金额(元)"
        prop="refundAmounts"
      >
        <template slot-scope="scope">
          <span>{{ (scope.row.refundAmounts / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :current-page="page"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { parseTime } from "@/utils/index";
import keyBy from "lodash/keyBy";
import { queryOrderSummary } from "@/api/order";
import dayjs from "dayjs";
// import { DAY_TYPE } from '@/utils/options'

// 前后需要的月数
const space = 6;
// 所选的第一个日期
let _minDate = "";

export default {
  // name: "观点列表",
  name: "",
  components: {},
  data() {
    return {
      // 选中时间段(默认是近一周)
      pickerOptions: {
        // 设置禁用状态
        disabledDate: time => {
          // 当选中第一个时间时
          if (_minDate) {
            // 最小时间
            const min = dayjs(_minDate).subtract(space, "month");
            // 最大时间
            const max = dayjs(_minDate).add(space, "month");
            return (
              // 控制可以选择的时间范围
              dayjs(time).isBefore(min) || dayjs(max).isBefore(time)
            );
          } else {
            return false;
          }
        },
        // 选中日期后会执行的回调
        onPick({ minDate }) {
          _minDate = minDate;
        }
      },
      total: 1,
      page: 1,
      size: 10,
      loading: false,
      date: [],
      topData: {
        orders: 0,
        totalPrices: 0,
        totalFees: 0,
        payTotals: 0,
        applyRefundAmounts: 0,
        refundAmounts: 0
      },
      downloadLoading: false,
      data: [],
      deriveData: [],
      delLoading: false
    };
  },
  computed: {
    ...mapGetters(["user"])
  },
  mounted() {
    this.getOrderList();
  },

  methods: {
    parseTime,
    getSubString(value) {
      return value.length > 15 ? value.substring(0, 15) + "..." : value;
    },
    // 查询订单
    async getOrderList() {
      this.loading = true;
      const params = {};
      params.current = this.page;
      params.size = this.size;
      params.type = 1;
      if (this.date.length > 0) {
        params.startTime = this.date[0];
        params.endTime = this.date[1];
      } else {
        params.startTime = dayjs()
          .subtract(1, "month")
          .format("YYYY-MM-DD");
        params.endTime = dayjs().format("YYYY-MM-DD");
      }
      const data = await queryOrderSummary(params);
      if (data.code === 0) {
        this.loading = false;
        this.data = data.data.list;
        this.total = data.data.total;
        this.getTop();
      } else {
        this.loading = false;
        this.$message.error(data.message);
      }
      // console.log(params)
    },
    // 查询订单头部
    async getTop() {
      const params = {};
      params.current = 1;
      params.size = 1;
      params.type = 2;
      if (this.date.length > 0) {
        params.startTime = this.date[0];
        params.endTime = this.date[1];
      } else {
        params.startTime = dayjs()
          .subtract(1, "month")
          .format("YYYY-MM-DD");
        params.endTime = dayjs().format("YYYY-MM-DD");
      }
      const data = await queryOrderSummary(params);
      if (data.code === 0) {
        if (data.data.list.length > 0) {
          this.topData = data.data.list[0];
        } else {
          this.topData = {
            orders: 0,
            totalPrices: 0,
            totalFees: 0,
            payTotals: 0,
            applyRefundAmounts: 0,
            refundAmounts: 0
          };
        }
      } else {
        this.$message.error(data.message);
      }
      // console.log(this.topData)
    },
    // 时间处理
    getTime(date) {
      const y = date.substring(0, 4);
      const m = date.substring(4, 6);
      const d = date.substring(6);
      return y + "-" + m + "-" + d;
    },
    async toQuery() {
      this.page = 1;
      if (this.date === null) {
        this.date = [];
      }
      this.getOrderList();
    },
    // 分页
    sizeChange(e) {
      this.page = 1;
      this.size = e;
      this.getOrderList();
    },
    pageChange(e) {
      this.page = e;
      this.getOrderList();
    },
    // 审核退款
    getProductType(status) {
      const statusObj = keyBy(this.productTypeList, "key")[status];
      return statusObj ? statusObj.value : "";
    },
    getRefundStatus(row) {
      switch (row) {
        case 180:
          return "申请退款";
        case 200:
          return "退款审核通过";
        case 210:
          return "退款失败";
        case 220:
          return "已退款";
        default:
          break;
      }
    },
    isNumber(val) {
      // 非负浮点数
      var regPos = /^\d+(\.\d+)?$/;
      // 负浮点数
      var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/;
      if (regPos.test(val) || regNeg.test(val)) {
        return true;
      } else {
        return false;
      }
    },
    // 导出
    async download() {
      if (this.date === null) {
        this.date = [];
      }
      const params = {};
      params.current = 1;
      params.size = 1000000;
      params.type = 1;
      if (this.date.length > 0) {
        params.startTime = this.date[0];
        params.endTime = this.date[1];
      } else {
        params.startTime = dayjs()
          .subtract(1, "month")
          .format("YYYY-MM-DD");
        params.endTime = dayjs().format("YYYY-MM-DD");
      }
      const data = await queryOrderSummary(params);
      if (data.code === 0) {
        this.deriveData = data.data.list;
      }
      // return
      this.downloadLoading = true;
      console.log(this.deriveData);
      import("@/utils/export2Excel").then(excel => {
        const tHeader = [
          "交易时间",
          "总交易单数",
          "订单总金额(元)",
          "手续费总金额(元)",
          "实收总金额(元)",
          "申请退款总金额(元)",
          "退款总金额(元)"
        ];
        const filterVal = [
          "days",
          "orders",
          "totalPrices",
          "totalFees",
          "payTotals",
          "applyRefundAmounts",
          "refundAmounts"
        ];
        const data = this.formatJson(filterVal, this.deriveData);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "订单汇总"
        });
        this.downloadLoading = false;
      });
    },
    // 数据转换
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (
            j === "totalPrices" ||
            j === "totalFees" ||
            j === "payTotals" ||
            j === "applyRefundAmounts" ||
            j === "refundAmounts"
          ) {
            return (v[j] / 100).toFixed(2);
          } else {
            return v[j];
          }
        })
      );
    },
    // 风险等级
    getRisk(riskLevel) {
      switch (riskLevel) {
        case 0:
          return "低风险";
        case 1:
          return "低风险";
        case 2:
          return "中低风险";
        case 3:
          return "中风险";
        case 4:
          return "中高风险";
        case 5:
          return "高风险";
      }
    },
    // 时间 发生改变时
    datePickerChange() {
      // 判断时间段为null时 至空所选的第一个日期(目的是避免类型错误的报错)
      if (!this.date) {
        _minDate = "";
        return;
      }
    },
    // 时间 失去焦点时
    datePickerBlur() {
      // 判断时间段不为null并且数组长度为0时 至空所选的第一个日期(目的是避免类型错误的报错)
      if (this.date && this.date.length === 0) {
        _minDate = "";
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  min-width: 1000px;
}
.head-container {
  display: flex;
  align-items: baseline;
}
.compress {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.table-container {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

::v-deep .el-input__suffix {
  margin-right: 3px;
}
</style>
