<template>
  <view>
    <Loading :type="3" :loadStatus="loadStatus" :showText="errorText" />
    <zj-page-layout :hasFooter="true" v-if="detail">
      <view style="padding: 1rpx 30rpx">
        <view class="materials-container card mt30">
          <view class="title">
            <view class="t1">支付金额</view>
            <view class="t2"
              >¥<text>{{ detail.totalAmount | priceFilter }}</text></view
            >
          </view>
          <view class="id"><text>订单号：</text>{{ detail.orderId }}</view>
          <view class="product">
            <view
              class="it"
              v-for="(item, index) in wbId ? detail.rpMaterialOrderItems : detail.workerOrderItems"
              :key="index"
            >
              <view class="name"
                >{{ item.goodsName }}<text>×{{ item.num }}{{ item.unit }}</text></view
              >
              <view class="price">¥{{ item.totalAmount | priceFilter }}</view>
            </view>
            <view class="total">
              <view class="text">合计：</view>
              <view class="price">¥{{ detail.totalAmount | priceFilter }}</view>
            </view>
          </view>
          <view class="row"><text>备注：</text>{{ detail.remark }}</view>
          <view class="row"><text>操作人：</text>{{ detail.workerName }}</view>
        </view>

        <!-- <view class="pay-container card mt30">
          <view class="top">请选择客户支付方式</view>
          <view class="item" @tap="payType = 1">
            <view class="left">
              <text class="iconfont icon-weixinzhifu" style="color: #43c93e"></text>
              <text class="text">微信支付</text>
            </view>
            <view class="right">
              <text class="iconfont" :class="payType === 1 ? 'icon-danxuan2 active' : 'icon-danxuan'"></text>
            </view>
          </view>
          <view class="item" @tap="payType = 2">
            <view class="left">
              <text class="iconfont icon-xianxiazhifu" style="color: #0379ff"></text>
              <text class="text">线下支付</text>
            </view>
            <view class="right">
              <text class="iconfont" :class="payType === 2 ? 'icon-danxuan2 active' : 'icon-danxuan'"></text>
            </view>
          </view>
        </view> -->
      </view>

      <template slot="footer">
        <view class="footer-btn-group">
          <u-button text="取消订单" @click="cancelOrder"></u-button>
          <u-button text="扫码支付" type="primary" @click="scanCode"></u-button>
          <!-- <u-button text="扫码支付" type="primary" @click="scanCode" v-if="payType === 1"></u-button> -->
          <!-- <u-button text="确定支付" type="primary" @click="confirmPay" v-else></u-button> -->
        </view>
      </template>
    </zj-page-layout>
  </view>
</template>

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

export default {
  data() {
    return {
      orderId: null,
      wbId: null,
      refresherTriggered: false,
      loadStatus: 0,
      errorText: '',
      detail: null,
      canScanCode: 0,
      timeout: null,
      timeoutNum: 0,

      payType: 1
    }
  },

  onLoad({ handleOrderId, wbId }) {
    this.orderId = handleOrderId
    this.wbId = wbId
    this.getDetail()

    this.crossPage.$on('reScanCode', () => {
      this.scanCode()
    })
  },

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

  methods: {
    getDetail() {
      let url = '',
        params = {}
      if (this.wbId) {
        url = '/engin/material/detail'
        params.id = this.orderId
      } else {
        url = '/pay/getOrder'
        params.orderId = this.orderId
      }
      this.$api
        .post(url, params)
        .then(res => {
          this.detail = res.data
          this.loadStatus = 0
        })
        .catch(res => {
          this.errorText = res.message
          this.loadStatus = 2
        })
        .finally(res => {
          this.refresherTriggered = false
        })
    },

    // 取消订单
    cancelOrder() {
      this.$modal({
        content: '确认取消订单吗？'
      })
        .then(() => {
          this.$api
            .post('/pay/cancel', {
              orderId: this.orderId
            })
            .then(res => {
              this.$successToast()
              this.$navToPage(
                {
                  delta: 1
                },
                'navigateBack'
              )
            })
        })
        .catch(() => {})
    },

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

    // 下单
    submitData(code) {
      let url = ''
      if (this.wbId) {
        url = '/engin/material/paid'
      } else {
        url = '/pay/paid'
      }

      this.$api
        .post(url, {
          authCode: code,
          orderId: this.orderId,
          payType: 'WECHAT'
        })
        .then(res => {
          // 返回true，则支付成功
          if (res.data) {
            this.timeoutNum = 0
            clearTimeout(this.timeout)

            this.$navToPage({
              url: `/packageMaterial/pages/sale/result?handleOrderId=${this.orderId}&result=1&wbId=${this.wbId || ''}`
            })
          }
          // 返回false，轮询3次
          else {
            if (this.timeoutNum < 4) {
              this.timeoutNum = this.timeoutNum + 1
              this.timeout = setTimeout(() => {
                this.submitData(code)
              }, 1000)
            } else {
              this.timeoutNum = 0
              clearTimeout(this.timeout)
              this.$navToPage({
                url: `/packageMaterial/pages/sale/result?handleOrderId=${this.orderId}&result=0&wbId=${this.wbId || ''}`
              })
            }
          }
        })
        .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)
        })
    },

    confirmPay() {
      let url = ''
      if (this.wbId) {
        url = '/engin/material/paid'
      } else {
        url = '/pay/paid'
      }

      this.$api
        .post(url, {
          authCode: '',
          orderId: this.orderId,
          payType: 'LINE'
        })
        .then(res => {
          if (res.data) {
            this.$navToPage({
              url: `/packageMaterial/pages/sale/result?handleOrderId=${this.orderId}&result=1&wbId=${this.wbId || ''}`
            })
          } else {
            this.$navToPage({
              url: `/packageMaterial/pages/sale/result?handleOrderId=${this.orderId}&result=0&wbId=${this.wbId || ''}`
            })
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.card {
  @include zj-card;
}

.materials-container {
  padding: 30rpx;

  .title {
    text-align: center;
    margin-top: 30rpx;

    .t1 {
      font-size: 32rpx;
      font-weight: 500;
    }

    .t2 {
      font-size: 40rpx;
      color: $minor-color;
      margin-top: 20rpx;

      text {
        font-size: 56rpx;
        font-weight: 500;
      }
    }
  }

  .id {
    margin-top: 50rpx;

    text {
      color: $sec-font;
    }
  }

  .product {
    background: #f5f5f5;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-top: 20rpx;
    .it {
      display: flex;
      align-items: flex-end;
      margin-bottom: 20rpx;
      .name {
        flex: 1;
        font-size: 28rpx;
        font-weight: 500;
        text {
          color: $sec-font;
          margin-left: 12rpx;
          font-weight: normal;
        }
      }
      .price {
        margin-left: 30rpx;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
    .total {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 30rpx;
      .text {
        font-size: 28rpx;
        color: $sec-font;
      }
      .price {
        font-size: 28rpx;
        color: $minor-color;
        font-weight: 500;
      }
    }
  }

  .row {
    margin-top: 20rpx;
    line-height: 40rpx;
    display: flex;
    font-size: 28rpx;

    text {
      color: $sec-font;
      flex-shrink: 0;
      line-height: 40rpx;
    }
  }
}

.pay-container {
  padding: 30rpx;

  .top {
    margin-bottom: 40rpx;
  }

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 30rpx 0;

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

      .iconfont {
        font-size: 44rpx;
        color: #43c93e;
      }

      .text {
        margin-left: 18rpx;
        font-size: 32rpx;
      }
    }

    .right {
      .iconfont {
        font-size: 40rpx;
        color: $sec-font;

        &.active {
          color: $theme-color;
        }
      }
    }
  }
}
</style>
