<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 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>

      <template slot="footer">
        <view class="footer-btn-group">
          <u-button v-if="detail.ifCancel" text="取消订单" @click="cancelOrder"></u-button>
          <!-- <u-button text="扫码支付" type="primary" @click="scanCode"></u-button> -->
          <u-button text="线下支付" type="primary" @click="scanCodeXX"></u-button>
        </view>
      </template>
    </zj-page-layout>
    <zhifutanchuan
      v-if="state > 0"
      :detail="detail"
      :orderId="orderId"
      :state="state"
      @scan="scan"
      @back="back"
      @offTiming="offTiming"
    />
  </view>
</template>

<script>
import { wxScanCode } from '@/common/utils/util.js'
import zhifutanchuan from '@/components/zhifutanchuan.vue'
export default {
  components: {
    zhifutanchuan
  },
  data() {
    return {
      orderId: null,
      refresherTriggered: false,
      loadStatus: 0,
      errorText: '',
      detail: null,
      canScanCode: 0,
      timeout: null,
      timeoutNum: 0,
      payType: 1,
      state: 0
    }
  },

  onLoad({ handleOrderId }) {
    this.orderId = handleOrderId
    this.getDetail()
    this.crossPage.$on('reScanCode', () => {
      this.scanCode()
    })
  },

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

  methods: {
    scan() {
      this.state = 0
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.scanCode()
    },

    back() {
      this.state = 0
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.$navToPage(
        {
          url: `/packageMaterial/pages/index?type=M`
        },
        'reLaunch'
      )
    },

    getDetail(cb) {
      let url = '/pay/getOrder'
      let params = {
        orderId: this.orderId
      }
      this.$api
        .post(url, params)
        .then(res => {
          this.detail = res.data
          this.loadStatus = 0
          cb?.()
        })
        .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(['qrCode'])
      this.submitData(codeVal)
    },

    // 下单
    submitData(code) {
      this.$api
        .post('/pay/paid', {
          authCode: code,
          orderId: this.orderId,
          payType: 'WECHAT'
        })
        .then(res => {
          this.orderId = res.data.orderId
          if (res.data.payStatus == 'PAID') {
            // 支付成功
            this.getDetail(() => {
              this.state = 2
            })
          } else {
            // 支付失败
            this.getDetail(() => {
              this.state = 4
            })
          }
        })
        .catch(res => {
          // 等待支付
          var [USERPAYING, orderId] = res.message.split('|')
          if (~USERPAYING.indexOf('USERPAYING') && !!orderId) {
            this.orderId = orderId
            if (this.state == 0) {
              this.state = 1
            }
            this.getDetail__()
          } else {
            this.$tips(res.message)
          }
        })
    },

    scanCodeXX() {
      this.$api
        .post('/pay/paid', {
          orderId: this.orderId,
          payType: 'LINE'
        })
        .then(res => {
          this.orderId = res.data.orderId
          if (res.data.payStatus == 'PAID') {
            // 支付成功
            this.state = 2
          } else {
            // 支付失败
            this.state = 4
          }
        })
        .catch(res => {})
    },

    offTiming() {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
    },

    getDetail__(cb) {
      this.$api
        .post('/pay/getOrder', {
          orderId: this.orderId
        })
        .then(res => {
          this.detail = res.data
          if (res.data.payStatus == 'PAID') {
            this.state = 2
          } else {
            this.timeout = setTimeout(() => {
              this.getDetail__(cb)
            }, 1000)
          }
          cb?.()
        })
        .catch(res => {})
        .finally(res => {})
    },

    confirmPay() {
      this.$api
        .post('/pay/paid', {
          authCode: '',
          orderId: this.orderId,
          payType: 'LINE'
        })
        .then(res => {
          if (res.data) {
            this.$navToPage({
              url: `/packageMaterial/pages/sale/result?handleOrderId=${this.orderId}&result=1`
            })
          } else {
            this.$navToPage({
              url: `/packageMaterial/pages/sale/result?handleOrderId=${this.orderId}&result=0`
            })
          }
        })
    }
  }
}
</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>
