<template>
  <view class="container">
    <u-sticky>
      <view class="head">
        <u-navbar title="我的订单" leftIcon=" " leftIconColor="#ffffff" titleStyle="color:#fff" :autoBack="false" placeholder></u-navbar>
        <view>
          <view class="searchBox">
            <view>
              <u--input placeholder="请输入商品名称" v-model="searchValue" placeholderClass="placeholderClass" border="none" clearable></u--input>
              <view class="searchBox_btn" @click="goSearch()">
                <text class="iconfont icon-sousuo"></text>
                搜索
              </view>
            </view>
          </view>
          <view class="tabs">
            <u-tabs :list="typeList" lineWidth="28" :current="typeindex" lineColor="#ffffff" activeStyle="color:#FFFFFF;font-size:28rpx;font-family: FZCuYuan-M03;" inactiveStyle="color:#FFFFFF;font-size:28rpx" :scrollable="false" @click="tabsClick"></u-tabs>
          </view>
        </view>
      </view>
    </u-sticky>
    <view class="list">
      <view class="item" v-for="(v,i) in list" v-if="params.queryStatus==40" :key="i" @click="goPath('/pages/order/orderDetails?refundOrderId='+v.refundOrderId)">
        <view class="item_t">
          <image :src="v.businessImage+'?x-oss-process=style/w_300'" mode="" />
          <view>{{v.businessName}}</view>
        </view>
        <view class="item_c">
          <view class="item_c_l">
            <image :src="(v.businessProductImage||v.businessImage)+'?x-oss-process=style/w_300'" mode="" />
          </view>
          <view class="item_c_r">
            <view class="item_c_r_title">{{v.businessProductName}}</view>
            <view class="item_c_r_text">{{v.productDataJosn.costIncluded}}</view>
            <view class="item_c_r_price">
              <view class="item_c_r_price_l" v-if="v.sellingPrice">￥
                <text>{{v.sellingPrice.split('.')[0]}}</text>.{{v.sellingPrice.split('.')[1]}}
              </view>
              <view class="item_c_r_price_r">X{{v.buyQuantity}}</view>
            </view>
          </view>
        </view>
        <view class="item_c1">
          <view class="item_c1_lab">合计：</view>
          <view class="item_c1_val" v-if="v.orderAmount">￥
            <text>{{v.orderAmount.split('.')[0]}}</text>.{{v.orderAmount.split('.')[1]}}
          </view>
        </view>
        <view class="item_btn" v-if="v.orderStatus==0">
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red1" @click.stop="cancelOrder(v)">取消订单</view>
          <view class="red1" @click.stop="payment(v)">去支付</view>
        </view>
        <view class="item_btn" v-if="v.orderStatus==10">
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red1" v-if="v.orderType==0" @click.stop="goPath('/pages/order/applicationDrawback?orderNumber=' +v.orderNumber)">申请退款</view>
          <!-- <view class="red1">去使用</view> -->
        </view>
        <view class="item_btn" v-if="v.orderStatus==20">
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red">详情</view>
        </view>
        <view class="item_btn" v-if="v.orderStatus==30||v.refundStatus==1||v.refundStatus==2">
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red1">详情</view>
        </view>
        <!-- <view class="item_tag item_tag_red" v-if="v.orderStatus==0">待支付</view> -->
        <view class="item_wait" v-if="v.orderStatus==0&&v.countdownTime&&v.countdownTime>0">
          <view class="item_wait_l">待支付</view>
          <view class="item_wait_r">14:50</view>
        </view>
        <view class="item_tag item_tag_green" v-if="v.orderStatus==10">待使用</view>
        <view class="item_tag item_tag_gary" v-if="v.orderStatus==20">已完成</view>
        <view class="item_tag item_tag_gary" v-if="v.orderStatus==30">已取消</view>
        <view class="item_tag item_tag_red" v-if="v.refundStatus==0">退款中</view>
        <view class="item_tag item_tag_gary" v-if="v.refundStatus==1">已退款</view>
        <view class="item_tag item_tag_gary" v-if="v.refundStatus==2">退款失败</view>
        <view class="item_tag item_tag_gary" v-if="v.refundStatus==3">拒绝退款</view>
        <view class="item_tag item_tag_gary" v-if="v.refundStatus==10">退款取消</view>
        <view class="item_tag1" v-if="v.orderType==1">猜拳奖励</view>
      </view>
      <view v-if="params.queryStatus!=40" class="item" v-for="(v,i) in list" :key="i" @click="goPath('/pages/order/orderDetails?orderNumber='+v.orderNumber)">
        <view class="item_t">
          <image :src="v.businessImage+'?x-oss-process=style/w_300'" mode="" />
          <view :class="{mr270:v.orderStatus==0&&v.countdownTime&&v.countdownTime>0}">{{v.businessName}}</view>
        </view>
        <view class="item_c">
          <view class="item_c_l">
            <image :src="(v.businessProductImage||v.businessImage)+'?x-oss-process=style/w_300'" mode="" />
          </view>
          <view class="item_c_r">
            <view class="item_c_r_title">{{v.businessProductName}}</view>
            <view class="item_c_r_text">{{v.productDataJosn.costIncluded}}</view>
            <view class="item_c_r_price">
              <view class="item_c_r_price_l" v-if="v.sellingPrice">￥
                <text>{{v.sellingPrice.split('.')[0]}}</text>.{{v.sellingPrice.split('.')[1]}}
              </view>
              <view class="item_c_r_price_r">X{{v.buyQuantity}}</view>
            </view>
          </view>
        </view>
        <view class="item_c1">
          <view class="item_c1_lab">合计：</view>
          <view class="item_c1_val" v-if="v.orderAmount">￥
            <text>{{v.orderAmount.split('.')[0]}}</text>.{{v.orderAmount.split('.')[1]}}
          </view>
        </view>
        <view class="item_btn" v-if="v.orderStatus==0">
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red1" @click.stop="cancelOrder(v)">取消订单</view>
          <view class="red1" @click.stop="payment(v)">去支付</view>
        </view>
        <view class="item_btn" v-if="v.orderStatus==10">
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red1" v-if="v.orderType==0" @click.stop="goPath('/pages/order/applicationDrawback?orderNumber=' +v.orderNumber)">申请退款</view>
          <view class="red1" @click.stop="goPath('/pages/order/orderDetails?orderNumber='+v.orderNumber+'&type=use')">去使用</view>
        </view>
        <view class="item_btn" v-if="v.orderStatus==20&&v.refundStatus!=1&&v.refundStatus!=2">
          <!-- v.gamesStatus==1&& -->
          <!-- <view class="red1" v-if="v.orderType==0" @click.stop="goPath(`/pages/game/index?orderNumber=${v.orderNumber}`)">参与免单</view> -->
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red1">详情</view>
        </view>
        <view class="item_btn" v-if="v.orderStatus==30||v.refundStatus==1||v.refundStatus==2">
          <view class="red" :class="{gary:v.gamesStatus == 2}" v-if="v.orderType==0" @click.stop="participate(v)">参与免单</view>
          <view class="red1">详情</view>
        </view>
        <!-- <view class="item_tag item_tag_red" v-if="v.orderStatus==0">待支付</view> -->
        <view class="item_wait" v-if="v.orderStatus==0&&v.countdownTime&&v.countdownTime>0">
          <view class="item_wait_l">待支付</view>
          <view class="item_wait_r">{{v.minutes}}:{{v.seconds}}</view>
        </view>
        <view class="item_tag item_tag_green" v-if="v.orderStatus==10">待使用</view>
        <view class="item_tag item_tag_gary" v-if="v.orderStatus==20">已完成</view>
        <view class="item_tag item_tag_gary" v-if="v.orderStatus==30">已取消</view>
        <view class="item_tag item_tag_gary" v-if="v.refundStatus==1||v.refundStatus==2">退款售后</view>
        <view class="item_tag1" v-if="v.orderType==1">猜拳奖励</view>
      </view>
      <empty marginTop="50" v-if="(!list||list.length<=0)&&status!='loading'" text="您目前还未下单，赶紧下单核销参与免单活动吧"></empty>
      <u-loadmore v-else :status="status" />
    </view>

    <reasonPop title="请选择取消原因" ref="reasonPopRef" @submit="affirm" />
    <tabBar currentPage="/pages/tabBar/order" />
  </view>
</template>

<script>
import {
  orderPage,
  orderPay,
  orderCancel,
  refundOrderPage
} from "@/api/home.js"
import tabBar from '@/components/tabBar/index.vue'
import reasonPop from "@/components/reasonPop/index.vue"
export default {
  components: {
    tabBar,
    reasonPop
  },
  data () {
    return {
      typeList: [{
        name: "全部",
        value: undefined
      }, {
        name: "待支付",
        value: 0
      }, {
        name: "待使用",
        value: 10
      }, {
        name: "已完成",
        value: 20
      }, {
        name: "已取消",
        value: 30
      }, {
        name: "退款售后",
        value: 40
      }],
      status: 'loadmore', //加载前值为loadmore，加载中为loading，没有数据为nomore，
      typeindex: 0,
      params: {
        pageSize: 10,
        pageNum: 1,
        queryStatus: undefined
      },
      list: [],
      searchValue: "",
      loading: false,
      cancelForm: {
        orderId: undefined,
        cancelNote: undefined
      }
    }
  },
  onPullDownRefresh () {
    this.params.pageNum = 1;
    this.getList()
  },
  onReachBottom () {
    if (this.status == "loadmore") {
      this.params.pageNum++;
      this.getList()
    }
  },
  onShow () {
    this.params.pageNum = 1;
    this.getList();
  },
  onUnload () {
    // 当页面关闭或卸载时清除定时器
    this.list.map(v => {
      if (v.intervalId) {
        clearInterval(row.intervalId);
      }
    })
  },
  onHide () {
    // 当页面关闭或卸载时清除定时器
    this.list.map(v => {
      if (v.intervalId) {
        clearInterval(row.intervalId);
      }
    })
  },
  methods: {
    tabsClick (e) {
      this.typeindex = e.index;
      this.params.queryStatus = e.value;
      this.params.pageNum = 1;
      this.getList()
    },
    goSearch () {
      this.params.businessProductName = this.searchValue;
      this.params.pageNum = 1;
      this.getList()
    },
    // 支付
    payment (item) {
      orderPay({
        orderNumber: item.orderNumber
      }).then(res => {
        uni.requestPayment({
          "provider": "wxpay",
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: (ret) => {
            this.params.pageNum = 1;
            this.getList()
          },
          fail (e) {
            // uni.redirectTo({
            //   url: '/pages/order/orderDetails?orderNumber=' + res.data.out_trade_no
            // });
          }
        })
      })
    },
    // 取消订单
    cancelOrder (row) {
      this.$refs.reasonPopRef.open();
      this.cancelForm.orderId = row.orderId;
      // uni.showModal({
      //   title: '提示',
      //   content: '确定取消订单？',
      //   success: (re) => {
      //     if (re.confirm) {
      //       orderCancel({
      //         orderId: row.orderId
      //       }).then(res => {
      //         uni.showToast({
      //           title: '取消成功！',
      //           duration: 2000
      //         });
      //         this.params.pageNum = 1;
      //         this.getList()
      //       })
      //     }
      //   }
      // });
    },
    // 计算订单取消订单的倒计时
    countDown (row) {
      // 获取当前时间
      let currentTime = new Date();
      // 订单取消时间  时间格式替换为ios支持的格式
      let cancelTime = new Date(row.payExpireTime.replace(/-/g, '/'));
      row.countdownTime = Math.floor((cancelTime - currentTime) / 1000);
      row.minutes = Math.floor(row.countdownTime / 60) < 10 ? '0' + Math.floor(row.countdownTime / 60) : Math.floor(row.countdownTime / 60);
      row.seconds = row.countdownTime % 60 < 10 ? '0' + row.countdownTime % 60 : row.countdownTime % 60;
      row.intervalId = setInterval(() => {
        row.minutes = Math.floor(row.countdownTime / 60) < 10 ? '0' + Math.floor(row.countdownTime / 60) : Math.floor(row.countdownTime / 60);
        row.seconds = row.countdownTime % 60 < 10 ? '0' + row.countdownTime % 60 : row.countdownTime % 60;
        if (row.countdownTime > 0) {
          row.countdownTime--;
        } else {
          row.orderStatus = 30;
          clearInterval(row.intervalId);
        }
      }, 1000)
    },
    affirm (e) {
      this.cancelForm.cancelNote = e;
      uni.showLoading({
        title: '执行中'
      });
      orderCancel(this.cancelForm).then(res => {
        uni.showToast({
          title: '取消成功！',
          duration: 2000
        });
        this.params.pageNum = 1;
        this.getList()
      }).finally(() => {
        uni.hideLoading();
      })
    },
    getList () {
      let token = uni.getStorageSync('apiToken');
      if (!token) return
      let apiFun = orderPage
      if (this.params.queryStatus == 40) {
        apiFun = refundOrderPage
      }
      apiFun(this.params).then(res => {
        res.rows.map(v => {
          v.productDataJosn = JSON.parse(v.productData);
          if (v.orderStatus == 0) {
            this.countDown(v)
          }
        })
        if (this.params.pageNum == 1) {
          this.list = res.rows
        } else {
          this.list.push(...res.rows);
        }
        if (this.list.length < res.total) {
          this.status = 'loadmore';
        } else {
          this.status = 'nomore';
        }
      }).finally(()=>{
		  uni.stopPullDownRefresh();
	  })
    },
    participate (row) {
      if (row.orderStatus == 0 || row.orderStatus == 10 || row.orderStatus == 30 || row.refundStatus == 1 || row.refundStatus == 2) {
        uni.$u.toast('支付订单并核销后可参与免单游戏');
        return
      } else if (row.gamesStatus != 1) {
        uni.$u.toast('您已参与过免单游戏');
        return
      } else {
        // uni.navigateTo({
        //   url: `/pages/game/index?orderNumber=${row.orderNumber}`
        // })
      }
    },
    goPath (path) {
      if (this.loading) return
      this.loading = true;
      uni.navigateTo({
        url: path,
        complete: () => {
          this.loading = false;
        }
      })
    },
  },
}
</script>

<style lang='scss' scoped>
::v-deep .u-navbar__content,
::v-deep .u-status-bar {
  background-color: transparent !important;
}
.container {
  padding-bottom: 160rpx;

  .head {
    background: linear-gradient(180deg, #c90700, #c90700 100%);
    padding: 20rpx 30rpx 30rpx;

    .searchBox {
      font-family: FZZhunYuan-M02S;

      > view {
        display: flex;
        background: #f5f5f5;
        height: 78rpx;
        border-radius: 40rpx;
        padding-left: 30rpx;
        border: 1px solid #e6e6e6;
      }

      .searchBox_btn {
        font-size: 28rpx;
        width: 136rpx;
        height: 66rpx;
        background: #fb0b03;
        border-radius: 33rpx;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 7rpx;

        .icon-sousuo {
          display: inline-block;
          margin-right: 8rpx;
          font-size: 32rpx;
        }
      }
    }

    .tabs {
      margin-top: 10rpx;
    }
  }
}

::v-deep .u-tabs__wrapper__nav__item {
  flex: auto !important;
  padding: 0 !important;
}

::v-deep .u-tabs__wrapper__nav__line {
  bottom: 8rpx !important;
}

.list {
  background: #f8f8f8;
  padding: 46rpx 30rpx;
  min-height: 65vh;

  .item {
    background: #ffffff;
    margin-bottom: 32rpx;
    border-radius: 30rpx;
    position: relative;

    .item_t {
      padding: 36rpx 24rpx 29rpx;
      border-bottom: 1rpx solid rgba(204, 204, 204, 0.6);
      display: flex;
      align-items: center;

      image {
        width: 68rpx;
        height: 68rpx;
        border-radius: 20rpx;
        margin-right: 15rpx;
        flex-shrink: 0;
      }

      view {
        font-size: 28rpx;
        color: #1a1a1a;
        font-family: FZCuYuan-M03;
        margin-right: 110rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }

    .item_c {
      display: flex;
      padding: 30rpx 0;
      margin: 0 24rpx;
      border-bottom: 1rpx solid rgba(204, 204, 204, 0.6);

      .item_c_l {
        margin-right: 12rpx;
        image {
          width: 172rpx;
          height: 172rpx;
          border-radius: 12rpx;
        }
      }

      .item_c_r {
        flex-grow: 1;

        .item_c_r_title {
          font-size: 26rpx;
          color: #242424;
          font-family: FZCuYuan-M03;
        }

        .item_c_r_text {
          font-size: 24rpx;
          color: #1a1a1a;
          margin: 15rpx 0 22rpx;
          height: 56rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

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

          .item_c_r_price_l {
            font-size: 22rpx;
            color: #ff0000;
            font-family: FZCuYuan-M03;

            text {
              font-size: 34rpx;
              font-family: FZCuYuan-M03;
            }
          }

          .item_c_r_price_r {
            font-size: 26rpx;
            color: #1a1a1a;
          }
        }
      }
    }

    .item_c1 {
      padding: 20rpx 0;
      margin: 0 24rpx;
      text-align: right;
      border-bottom: 1rpx solid rgba(204, 204, 204, 0.6);

      > view {
        display: inline-block;
      }

      .item_c1_lab {
        font-size: 26rpx;
        color: #1a1a1a;
      }

      .item_c1_val {
        font-size: 22rpx;
        color: #ff0000;
        font-family: FZCuYuan-M03;

        text {
          font-size: 42rpx;
          color: #ff0000;
          font-family: FZCuYuan-M03;
        }
      }
    }

    .item_btn {
      text-align: right;
      padding: 30rpx 24rpx 35rpx;

      > view {
        width: 200rpx;
        height: 70rpx;
        border-radius: 35rpx;
        text-align: center;
        color: #ffffff;
        line-height: 72rpx;
        display: inline-block;
        font-size: 26rpx;
        margin-left: 15rpx;
        &:first-child {
          margin-left: 0;
        }
      }

      .red {
        background: #fb0b03;
      }
      .red1 {
        border: 1rpx solid #fb0b03;
        color: #fb0b03;
      }
      .gary {
        background: #999999;
      }
    }
    .item_wait {
      width: 252rpx;
      height: 51rpx;
      background: #ffdbd9;
      border-radius: 26rpx;
      display: flex;
      position: absolute;
      top: 44rpx;
      right: 40rpx;
      > view {
        width: 50%;
        font-size: 24rpx;
        color: #ffffff;
        text-align: center;
        line-height: 51rpx;
      }
      .item_wait_l {
        background: #fb0b03;
        border-radius: 35rpx 0 35rpx 35rpx;
      }
      .item_wait_r {
        font-size: 30rpx;
        color: #fb0b03;
        letter-spacing: 1px;
        font-family: FZCuYuan-M03;
      }
    }
    .item_tag {
      width: 136rpx;
      height: 50rpx;
      border-radius: 0rpx 30rpx 0rpx 30rpx;
      font-size: 24rpx;
      color: #fb0b03;
      line-height: 50rpx;
      text-align: center;
      position: absolute;
      top: 0;
      right: 0;
    }
    .item_tag1 {
      height: 50rpx;
      background: #ffdbd9;
      font-size: 24rpx;
      color: #fb0b03;
      text-align: center;
      line-height: 50rpx;
      padding: 0 30rpx;
      border-radius: 8rpx;
      border: 1rpx solid #fa353b;
      position: absolute;
      bottom: 43rpx;
      left: 30rpx;
    }
    .item_tag_red {
      background: #ffdbd9;
      color: #fb0b03;
    }

    .item_tag_green {
      background: #e6ffec;
      color: #00bf02;
    }

    .item_tag_gary {
      background: #e6e6e6;
      color: #333333;
    }
  }
}
.mr270 {
  margin-right: 270rpx !important;
}
::v-deep .placeholderClass {
  font-family: FZZhunYuan-M02S;
  font-size: 28rpx;
}
</style>