<template>
  <zj-page-layout
    :hasFooter="true"
    :isScroll="true"
    :refresherTriggered="refresherTriggered"
    @refresherrefresh="refresherrefresh"
  >
    <template slot="header">
      <view class="tab-container">
        <u-tabs
          :scrollable="true"
          :list="tabList"
          :current="curTab"
          @click="changeTab"
          lineColor="#3D8FFD"
          :activeStyle="{
            color: '#3D8FFD'
          }"
          :inactiveStyle="{
            color: '#666666'
          }"
          itemStyle="height: 88rpx;"
        >
        </u-tabs>
      </view>
    </template>

    <view class="list-container">
      <view class="mode" @click.prevent="toOrderDetail(item.id)" v-for="(item, index) in orderList" :key="index">
        <view class="flex_asb order">
          <view class="title"
            >制单时间: <text class="text">{{ item.createTime }}</text></view
          >
          <view :class="item.payStatus">{{ statusFilter(item.payStatus) }}</view>
        </view>
        <view class="flex_asb order" v-if="item.payStatus == 'PAID' || item.payStatus == 'EXPIRE'">
          <view class="title"
            >延保期限: <text class="text">{{ item.serviceEndTime.substring(0, 10) }}</text></view
          >
          <view class="status">延保</view>
        </view>
        <view class="flex">
          <view class="hui">申请单号: </view>
          <view class="text"> {{ item.id }}</view>
        </view>
        <view class="flex">
          <view class="hui">产品品牌: </view>
          <view class="text"> {{ item.brandName }}</view>
        </view>
        <view class="flex">
          <view class="hui">产品大类: </view>
          <view class="text"> {{ item.mainName }}</view>
        </view>
        <view class="flex">
          <view class="hui">延保年限: </view>
          <view class="text"> {{ item.limitNum }}</view>
        </view>
        <view class="flex">
          <view class="hui">延保金额: </view>
          <view class="text"> {{ item.amount }}</view>
        </view>
        <view class="flex_end">
          <view
            v-if="item.payStatus == 'WAIT'"
            @click.stop="cancelOrder(item.id)"
            style="width: 160rpx; height: 60rpx; margin-left: 20rpx"
          >
            <u-button :plain="true" type="primary" text="取消订单"></u-button>
          </view>
          <view
            v-if="item.payStatus == 'PAID'"
            @click.stop="navToPage('/packageWorkorder/pages/userWorkorderList?pgIncreOrderId=' + item.id)"
            style="width: 160rpx; height: 60rpx; margin-left: 20rpx"
          >
            <u-button :plain="true" type="primary" text="使用记录"></u-button>
          </view>

          <view
            v-if="item.payStatus == 'PAID' && item.orderTaxId"
            @click.stop="toInvoiceDetail(item.orderTaxId)"
            style="width: 160rpx; height: 60rpx; margin-left: 20rpx"
          >
            <u-button :plain="true" type="primary" text="查看发票"></u-button>
          </view>
          <view
            v-if="item.payStatus == 'PAID' && !item.orderTaxId"
            @click.stop="toInvoiceForm(item.id)"
            style="width: 160rpx; height: 60rpx; margin-left: 20rpx"
          >
            <u-button :plain="true" type="primary" text="开发票"></u-button>
          </view>

          <view
            v-if="item.payStatus == 'PAID'"
            @click.stop="navToPage('/packageHome/pages/addvalue/serviceUse?id=' + item.id)"
            style="width: 160rpx; height: 60rpx; margin-left: 20rpx"
          >
            <u-button :plain="true" type="primary" text="去使用"></u-button>
          </view>
          <view
            v-if="item.payStatus == 'WAIT'"
            @click.stop="toPay(item)"
            style="width: 160rpx; height: 60rpx; margin-left: 20rpx"
          >
            <u-button :plain="true" type="primary" text="去支付"></u-button>
          </view>
        </view>
      </view>
    </view>

    <Loading :loadStatus="loadStatus" :dataList="orderList" />

    <u-popup :show="isShowPay" mode="bottom">
      <view class="pay">
        <image class="close" @click="closePay()" src="/static/icon/close.png" mode="aspectFill"></image>
        <view class="title">请支付</view>
        <view class="item"> 服务类型: <text class="text">延保</text> </view>
        <view class="item"> 使用类型: <text class="text">按使用年限</text> </view>
        <view class="item">
          产品品牌: <text class="text">{{ detail.brandName }}</text>
        </view>
        <view class="item">
          产品大类: <text class="text">{{ detail.minName }}</text>
        </view>
        <view class="item">
          服务内容: <text class="text">{{ detail.increContent }}</text>
        </view>
        <view class="item">
          使用限制: <text class="text">{{ detail.limitNum }}</text>
        </view>
        <view class="item">
          服务金额: <text class="text">{{ detail.amount }}</text>
        </view>
        <view class="title" style="text-align: left">选择支付方式</view>
        <view class="payType">
          <view style="margin-bottom: 20rpx">
            <u-button type="primary" @click="scanCode" text="扫码支付 (推荐)"></u-button>
          </view>
          <u-button type="primary" @click="workerPay" :plain="true" text="代客支付"></u-button>
        </view>
      </view>
    </u-popup>
  </zj-page-layout>
</template>

<script>
import { weixinPay, mini_env, wxScanCode } from '@/common/utils/util.js'

export default {
  data() {
    return {
      tabList: [
        { key: '', name: '全部(0)' },
        { key: 'WAIT', name: '待支付(0)' },
        { key: 'PAID', name: '已支付(0)' },
        { key: 'EXPIRE,CANCEL', name: '过期/取消(0)' },
        { key: 'REFUND', name: '已退款(0)' }
      ],
      tabCurrent: '', // 当前tab状态
      orderList: [], // 订单列表
      loadStatus: 0,
      refresherTriggered: false, // 下拉刷新状态
      pageNum: 1,
      isShowPay: false,
      detail: {},
      canScanCode: 0,
      timeout: null,
      timeoutNum: 0
    }
  },

  computed: {
    curTab() {
      return this.tabList.map(item => item.key).indexOf(this.tabCurrent) || 0
    },
    statusFilter() {
      return function (val) {
        const statusMap = {
          WAIT: '待支付',
          PAID: '已支付',
          EXPIRE: '已过期',
          CANCEL: '已取消',
          REFUND: '已退款'
        }
        return statusMap[val]
      }
    },
    deadline() {
      return function (time, num) {
        let date = new Date(time)
        date.setFullYear(date.getFullYear() + num)
        let y = date.getFullYear(),
          m = date.getMonth() + 1,
          d = date.getDate()
        return `${y}-${m > 9 ? m : '0' + m}-${d > 9 ? d : '0' + d}`
      }
    }
  },

  onLoad() {
    this.getOrderList()
  },

  onUnload() {
    clearTimeout(this.timeout)
  },

  methods: {
    getOrderList() {
      this.getCount()
      this.loadStatus = 1
      let url = ''
      this.$api
        .post('/increConfig/listIncre', {
          pageNum: this.pageNum,
          pageSize: 10,
          payStatus: this.tabCurrent
          // userId: this.$store.state.user.userId
        })
        .then(res => {
          this.loadStatus = 0
          let list = res.data.records
          if (list.length < 10) {
            this.loadStatus = 2
          }
          this.orderList = this.orderList.concat(list)
        })
        .catch(() => {
          this.loadStatus = 2
        })
        .finally(res => {
          this.refresherTriggered = false
        })
    },

    // 滚动到底部
    scrolltolower(e) {
      if (this.loadStatus === 0) {
        this.pageNum++
        this.getOrderList()
      }
    },

    // 触发下拉刷新
    async refresherrefresh(e) {
      this.refresherTriggered = true
      this.refreshList()
    },

    refreshList() {
      this.orderList = []
      this.pageNum = 1
      this.getOrderList()
    },

    getCount() {
      this.$api.post('/increConfig/listIncreCount').then(res => {
        this.tabList[0].name = '全部' //'全部(' + res.data.qb + ')'
        this.tabList[1].name = '待支付(' + res.data.dzf + ')'
        this.tabList[2].name = '已支付' //'已支付(' + res.data.yzf + ')'
        this.tabList[3].name = '过期/取消(' + res.data.gqqx + ')'
        this.tabList[4].name = '已退款(' + res.data.tk + ')'
      })
    },

    // 切换类型
    changeTab(item) {
      this.tabCurrent = item.key
      this.refreshList()
    },

    // 去订单详情
    toOrderDetail(id) {
      this.$navToPage({
        url: '/packageHome/pages/addvalue/orderDetail?id=' + id
      })
    },

    // 取消订单
    cancelOrder(id) {
      this.$modal({
        content: '确定要取消订单吗？'
      })
        .then(() => {
          this.$api
            .post('/increConfig/cancel', {
              id
            })
            .then(res => {
              this.refreshList()
              this.$successToast()
            })
        })
        .catch(() => {})
    },

    navToPage(url) {
      this.$navToPage({
        url
      })
    },

    toPay(item) {
      this.detail = item
      this.isShowPay = true
    },

    // 扫码
    async scanCode() {
      if (this.canScanCode > 0) return this.$toast(`请等待${this.canScanCode}秒后重试`)
      var codeVal = await wxScanCode(['qrCode'])
      this.userPay(codeVal)
    },

    // 用户支付
    userPay(code) {
      this.$api
        .post('/increConfig/paid', {
          authCode: code,
          id: this.detail.id
        })
        .then(res => {
          // 返回true，则支付成功
          if (res.data) {
            this.timeoutNum = 0
            clearTimeout(this.timeout)
            this.getOrderList()
          }
          // 返回false，轮询3次
          else {
            if (this.timeoutNum < 4) {
              this.timeoutNum = this.timeoutNum + 1
              this.timeout = setTimeout(() => {
                this.userPay(code)
              }, 1000)
            } else {
              this.timeoutNum = 0
              clearTimeout(this.timeout)
              this.getOrderList()
            }
          }
        })
        .catch(res => {
          this.timeoutNum = 0
          clearTimeout(this.timeout)
          this.$tips(res.message)
        })
        .finally(() => {
          this.canScanCode = 15
          let time = setInterval(() => {
            if (this.canScanCode > 0) {
              this.canScanCode = this.canScanCode - 1
            } else {
              clearInterval(time)
            }
          }, 1000)
        })
    },

    //代客支付
    workerPay() {
      mini_env(bool => {
        const that = this
        this.$api
          .post('/increConfig/pay', {
            id: this.detail.id,
            ...(() => {
              if (bool) {
                return {
                  miniPay: true,
                  openId: this.$store.state.user.miniOpenId
                }
              }
              return {}
            })()
          })
          .then(res => {
            if (!res.data) return false
            if (bool) {
              uniWebview.navigateTo({
                url: `/pages/pay/pay?${Object.entries({
                  ...res.data,
                  payPackage: res.data.payPackage.split('=')[0] || '',
                  payPackageVal: res.data.payPackage.split('=')[1] || ''
                })
                  .map(item => item.join('='))
                  .join('&')}`
              })
            } else {
              weixinPay(res.data, function (res) {
                that.$successToast('支付成功')
                that.getOrderList()
              })
            }
          })
      })
    },

    closePay() {
      this.isShowPay = false
    },

    // 开发票
    toInvoiceForm(orderId = '') {
      this.navToPage('/packageMine/pages/invoice/form?orderType=INCRE&orderId=' + orderId)
    },

    // 发票详情
    toInvoiceDetail(orderTaxId = '') {
      this.navToPage('/packageMine/pages/invoice/detail?orderTaxId=' + orderTaxId)
    }
  }
}
</script>

<style lang="scss">
.tab-container {
  background: #ffffff;
}

.flex {
  display: flex;
  align-items: center;
}

.flex_asb {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex_end {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 30rpx;
}

.flex1 {
  flex: 1;
}

.list-container {
  padding: 1rpx 20rpx 0;

  .mode {
    @include zj-card;
    padding: 30rpx 20rpx;
    margin-top: 30rpx;
    border-radius: 20rpx;
    box-sizing: border-box;
    background-color: #ffffff;

    .order {
      margin-bottom: 20rpx;
    }

    .title {
      font-weight: bold;
      font-size: 28rpx;
    }

    .text,
    .hui {
      font-size: 28rpx;
      margin-top: 16rpx;
    }

    .text {
      margin-left: 20rpx;
    }

    .hui {
      color: #999999;
    }

    .status {
      font-size: 28rpx;
      color: #0379ff;
    }

    .PAID {
      color: #4bba75;
    }

    .WAIT {
      color: #fda624;
    }

    .CANCEL,
    .EXPIRE {
      color: #999999;
    }

    .zhihui {
      .text,
      .hui,
      .title,
      .status {
        color: #999999 !important;
      }
    }

    .img {
      width: 100rpx;
      height: 100rpx;
      margin-right: 30rpx;
    }
  }
}

.pay {
  padding: 30rpx;
  padding-bottom: 0;
  box-sizing: border-box;
  position: relative;

  .title {
    font-size: 34rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 50rpx;
  }

  .item {
    color: #666666;
    margin-bottom: 20rpx;

    .text {
      margin-left: 30rpx;
      color: #000000;
    }
  }

  .payType {
    margin: 40rpx 0;
  }

  .close {
    width: 30rpx;
    height: 30rpx;
    position: absolute;
    top: 30rpx;
    right: 30rpx;
  }
}
</style>
