/*我的积分*/
<template>
  <div class="integral">
    <div class="header">
      <span>积分明细</span>
      <span>剩余积分：{{ point }}</span>
    </div>
    <div class="content-list">
      <div v-if="paginationConfig.total == 0" class="tips">暂无数据</div>
      <div v-for="(item, index) in listData" :key="index" class="list">
        <div class="desc">
          <p>{{ item.desc }}</p>
          <span>{{ formatTime(item.createTime) }}</span>
        </div>
        <span class="price"
          >{{ item.direction == '-' ? '-' : '+' }}{{ item.point }}</span
        >
      </div>
    </div>

    <div class="pagination">
      <Pagination
        :pagination-config="paginationConfig"
        @putPagination="getPagination"
      ></Pagination>
      <!-- <el-button
        type="danger"
        size="mini"
        plain
        round
        @click.native.prevent="charge"
        >去充值</el-button
      > -->
    </div>

    <Charge :charge-config="chargeConfig" @putCharge="getCharge" />
    <Pay :pay-config="payConfig" @putPay="getPay" />
    <Result :result-config="resultConfig" @putResult="getResult" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import Charge from './components/Charge'
import Pay from './components/Pay'
import Result from './components/Result'
import wechat from '@/assets/img/wechat.png'
import alipay from '@/assets/img/alipay.png'
import { request } from '@/utils/request'
import { parseTime } from '@/utils/index'
export default {
  name: 'Integral',
  components: { Pagination, Charge, Pay, Result },
  data() {
    return {
      paginationConfig: {
        hideSinglePage: false,
        page: 1,
        size: 15,
        sizeList: [10, 15, 30, 50],
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
      },
      chargeConfig: {
        isShow: false,
        account: '',
        payType: 'WeChat', // WeChat：微信；Alipay：支付宝
        intergal: '',
        amount: '',
        ruleList: [],
        selectGoodsCode: '',
        defineGoodsCode: '',
        description: '',
      },
      payConfig: {
        isShow: false,
        Payee: '',
        qrcode: '',
        payType: '',
        amount: '',
        payUrl: '',
      },
      resultConfig: {
        isShow: false,
        result: '3', // 0：下单失败；2：支付失败;3：支付成功；7：订单关闭；8：支付超时;
      },
      timeOut: null, // 计时器
      maxCheckTimes: 200, // 最大校验次数
      loading: false, // 是显示加载
      listData: [], // 数据列表
      point: '', // 剩余积分
    }
  },
  created() {
    this.getData() // 获取积分列表
    this.getPoint() // 获取剩余积分
  },
  methods: {
    // 获取剩余积分
    getPoint() {
      const params = {
        transCode: 'C00001',
      }
      request(params)
        .then((res) => {
          this.point = res.point
        })
        .catch((err) => {})
    },
    // 获取积分列表
    getData() {
      clearTimeout(this.timeOut)
      this.timeOut = null
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        const params = {
          transCode: 'C00011',
          type: '0', //类型（0-积分 1-积分充值 2-积分消费_新增子账户上限 3-积分赠送，不传是所有）
          page: this.paginationConfig.page,
          count: this.paginationConfig.size,
        }
        request(params)
          .then((res) => {
            loading.close()
            this.listData = res.rows
            this.paginationConfig.total = res.total
          })
          .catch((err) => {
            loading.close()
          })
      }, 1500)
    },
    // 充值
    charge() {
      //获取商品列表
      const params = {
        transCode: 'C00022',
        type: '1', // 类型（1-充值，2-增加子账户上限 4-购买资源）
        saleUnit: '', // 出售方式(0-整卖 1-零卖)
      }
      request(params)
        .then((res) => {
          this.chargeConfig = {
            isShow: true,
            account: this.$store.getters.name,
            payType: 'WeChat', // WeChat：微信；Alipay：支付宝
            intergal: res.rows.filter((tmp) => tmp.saleUnit == 0)[0]
              .returnGoods,
            amount: res.rows.filter((tmp) => tmp.saleUnit == 0)[0].salePrice,
            ruleList: res.rows.filter((tmp) => tmp.saleUnit == 0),
            selectGoodsCode: res.rows.filter((tmp) => tmp.saleUnit == 0)[0]
              .goodsCode,
            defineGoodsCode: res.rows.filter((tmp) => tmp.saleUnit == 1)[0]
              .goodsCode,
            description: res.rows.filter((tmp) => tmp.saleUnit == 1)[0]
              .description,
          }
        })
        .catch((err) => {})
    },
    // 获取分页操作
    getPagination(data) {
      this.paginationConfig = data
      this.getData()
    },
    // 获取charge操作
    getCharge(data) {
      this.chargeConfig.isShow = false
      if (data) {
        const loading = this.$loading({
          lock: true,
          text: '正在生成订单，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        // 充值积分
        const params = {
          transCode: 'C00012',
          count: data.intergal,
          goodsCode: data.selectGoodsCode,
        }
        request(params)
          .then((res) => {
            this.getOrder(res.orderId, res.payAmount, data.payType, loading) // 支付下单
          })
          .catch((err) => {
            loading.close()
          })
      }
    },
    // 支付下单
    getOrder(orderId, payAmount, payType, loading) {
      const params = {
        transCode: 'IEF001',
        orderId: orderId,
        payType: payType == 'WeChat' ? '0' : '2', // 类型（0-微信，2-支付宝）
        payDesc: '充值积分', // 支付说明
      }
      request(params)
        .then((res) => {
          loading.close()
          if (res.qrUrl) {
            this.payConfig = {
              isShow: true,
              Payee: '',
              qrcode: payType == 'WeChat' ? wechat : alipay,
              payType: payType,
              amount: payAmount,
              payUrl: res.qrUrl,
            }
            setTimeout(() => {
              this.maxCheckTimes = 200 // 最大校验次数
              this.checkPay(res.orderNo) // 校验支付状态
            }, 5000)
          } else {
            this.getPay(true)
            this.resultConfig = {
              isShow: true,
              result: '0',
            }
          }
        })
        .catch((err) => {})
    },
    // 校验支付状态
    checkPay(orderNo) {
      console.log(this.payConfig.isShow)
      if (!this.payConfig.isShow) return false
      this.maxCheckTimes--
      const params = {
        transCode: 'IEF002',
        orderNo: orderNo,
      }
      request(params)
        .then((res) => {
          if (this.maxCheckTimes > 0) {
            if (
              res.status == 2 ||
              res.status == 3 ||
              res.status == 7 ||
              res.status == 8
            ) {
              this.getPay(true)
              this.resultConfig = {
                isShow: true,
                result: res.status,
              }
            } else {
              this.timeOut = setTimeout(() => {
                this.checkPay(orderNo) // 校验支付状态
              }, 3000)
              this.$once('hook:beforeDestory', () => {
                clearTimeout(this.timeOut)
                this.timeOut = null
              })
            }
          } else {
            this.getPay(true)
            this.resultConfig = {
              isShow: true,
              result: '8',
            }
          }
        })
        .catch((err) => {
          this.checkPay(orderNo) // 校验支付状态
        })
    },
    // 获取Pay操作
    getPay(data) {
      this.payConfig.isShow = false
      clearTimeout(this.timeOut)
      this.timeOut = null
    },
    // 获取Result操作
    getResult(data) {
      this.resultConfig.isShow = false
      clearTimeout(this.timeOut)
      this.timeOut = null
      if (data) {
        this.charge()
      } else {
        this.getData()
        this.getPoint()
      }
    },
    formatTime(time) {
      return parseTime(time)
    },
  },
  beforeDestroy() {
    clearInterval(this.timeOut)
    this.timeOut = null
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixin.scss';
.integral {
  @include w_h(100%, 100%);
  font-size: 12px;
  background: $color_f;
  .header {
    @include flex();
    @include w_h(100%, 40px);
    padding: 0 30px;
    color: $color_f;
    background: #004498;
  }
  .content-list {
    @include w_h(100%, 80%);
    padding: 5px 30px;
    border-bottom: 1px solid #ebeef5;
    overflow-y: auto;
    .tips {
      @include w_h(100%, 100%);
      line-height: 400px;
      font-size: 12px;
      text-align: center;
      color: #909399;
    }
    .list {
      @include flex();
      padding: 8px 0;
      line-height: 16px;
      border-bottom: 1px solid $color_f5;
      .desc {
        span {
          color: $color_9;
        }
      }
    }
  }

  .pagination {
    @include flex();
    padding: 20px;
    font-size: 12px;
    color: $color_9;
  }
}
</style>

