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

    <view class="list-container">
      <view class="item" v-for="(item, index) in dataList" :key="index" @tap="toDetail(item)">
        <view class="top">
          <view class="left">
            <image :src="item.sellUrl" mode="aspectFill"></image>
            <view class="info">
              <view class="name">{{item.sellName}}</view>
              <view class="text">{{item.sellTime | timeFilter}}发布</view>
            </view>
          </view>
          <view class="right">
            <view class="status" v-if="item.payStatus == 'PAID' && item.status == 'CANCEL'">已售后</view>
            <view class="status" v-else>
              {{{SAVE: '待付款', WAIT: '待确认', PAID: '待发货', SEND: '待收货', OVER: '已收货', TIME_OUT: '已超时', CANCEL: '已取消', WAIT_REFUND: '售后中'}[item.status]}}
            </view>

            <view class="tag">
              <u-tag :text="{1: '线上销售', 2: '线下销售'}[item.saleType]" plain plainFill size="mini"></u-tag>
              <u-tag :text="{WECHAT: '在线支付', CASH: '到店支付'}[item.payType]" plain plainFill size="mini"></u-tag>
            </view>
          </view>
        </view>
        <view class="goods">
          <image :src="item.goodsUrl" mode="aspectFill"></image>
          <view class="right">
            <view class="name">{{item.esGoodsName}}</view>
            <view class="text">{{item.goodsNote}}</view>
            <view class="info">
              <view class="price">{{item.goodsPrice | priceFilter2}}</view>
              <view class="num">x{{item.num}}</view>
            </view>
          </view>
        </view>
        <view class="total">订单总金额<text>{{item.totalAmount | priceFilter2}}</text></view>
        <view class="bottom">
          <view class="left"></view>
          <view class="right" @tap.stop>
            <block v-if="item.status == 'SAVE'">
              <u-button text="取消订单" size="small" shape="circle" @click="cancelOrder(item)"></u-button>
              <u-button text="去支付" size="small" shape="circle" type="primary" plain v-if="item.payType == 'WECHAT'" @click="payOrder(item)"></u-button>
            </block>
            <block v-else-if="item.status == 'PAID'">
              <u-button text="联系卖家" size="small" shape="circle" type="primary" plain @click="$callPhone(item.sellMobile)"></u-button>
            </block>
            <block v-else-if="item.status == 'SEND'">
              <u-button text="查看物流" size="small" shape="circle" @click="toLogistics(item)"></u-button>
              <u-button text="确认收货" size="small" shape="circle" type="primary" plain @click="confirmOrder(item)"></u-button>
            </block>
            <block v-else-if="item.status == 'OVER'">
              <u-button text="申请售后" size="small" shape="circle" type="primary" plain @click="toRefundForm(item)"></u-button>
            </block>
            <block v-else>
              <!-- <u-button text="售后详情" size="small" shape="circle" @click="toRefundDetail(item)"></u-button> -->
              <u-button text="查看详情" size="small" shape="circle" @click="toDetail(item)"></u-button>
            </block>
          </view>
        </view>
      </view>
    </view>

    <Loading :type="1" :loadStatus="loadStatus" :dataList="dataList" />

  </zj-page-layout>
</template>

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

  export default {
    data() {
      return {
        dataList: [],
        pageNum: 1,
        loadStatus: 0,
        refresherTriggered: false,
        tabList: [
          {name: '全部', value: ''},
          {name: '待付款', value: 'SAVE'},
          {name: '待发货', value: 'PAID'},
          {name: '待收货', value: 'SEND'},
          {name: '已收货', value: 'OVER'},
          {name: '售后', value: 'REFUND'},
          {name: '已取消', value: 'CANCEL'},
        ],
        tabCurrent: 0,
        status: '',
      }
    },

    onLoad({tab = ''}) {
      this.status = tab;
      this.tabCurrent = this.tabList.map(o => o.value).indexOf(tab);

      this.getList();

      this.crossPage.$on('refreshRecycleOrderList', data => {
        this.refreshList();
      })
    },

    onUnload() {
      this.crossPage.$off('refreshRecycleOrderList');
    },

    methods: {
      getList() {
      	this.loadStatus = 1;
      	this.$api.post('/es/orderPay/list', {
          pageNum: this.pageNum,
          pageSize: 10,
          status: this.status,
          // userId: this.$store.state.user.userId,
      	}).then(res => {
      		this.loadStatus = 0;
      		let list = res.data.records;
      		if (list.length < 10) {
      		  this.loadStatus = 2;
      		}
      		this.dataList = this.dataList.concat(list);
      	}).catch(() => {
      		this.loadStatus = 2;
      	}).finally(res => {
      		this.refresherTriggered = false;
      	})
      },

      changeTab(e) {
      	this.tabCurrent = e.index;
      	this.status = e.value;
        this.refreshList();
      },

      refreshList() {
      	this.dataList = [];
      	this.pageNum = 1;
      	this.getList();
      },

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

      // 去订单详情
      toDetail(item) {
        this.$navToPage({
          url: `/packageHome/pages/recycle/order/detail?id=${item.esOrderId}`
        })
      },

      // 查看物流
      toLogistics(item) {
        this.$navToPage({
          url: `/packageHome/pages/recycle/order/logistics?id=${item.esOrderId}`
        })
      },

      // 去申请售后
      toRefundForm(item) {
        this.$navToPage({
          url: `/packageHome/pages/recycle/order/refundForm?id=${item.esOrderId}`
        })
      },

      // 去售后详情
      toRefundDetail(item) {
        this.$navToPage({
          url: `/packageHome/pages/recycle/order/refundDetail?id=${item.esOrderId}`
        })
      },

      // 确认收货
      confirmOrder(item) {
        this.$modal({
          content: `确定要确认收货吗？`
        }).then(() => {
          this.$api.post('/es/orderPay/okSend', {
            esOrderId: item.esOrderId,
          }).then(res => {
            this.$successToast();
            this.refreshList();
          })
        }).catch(() => {})
      },

      // 取消订单
      cancelOrder(item) {
        this.$modal({
          content: `确定要取消订单吗？`
        }).then(() => {
          this.$api.post('/es/orderPay/wait/notPay', {
            orderId: item.esOrderId,
          }).then(res => {
            this.$successToast();
            this.refreshList();
          })
        }).catch(() => {})
      },

      // 支付订单
      payOrder(item) {
        let that = this;
        mini_env((bool) => {
          this.$api.post('/es/orderPay/wait/pay', {
            esOrderId: item.esOrderId,
            ...(() => {
              if (bool) {
                return {
                  miniPay: true,
                  openId: this.$store.state.user.miniOpenId
                }
              }
              return {}
            })()
          }).then(res => {
            if (res.code === 1100) {
              return that.$tips(res.message);
            }
            // 不需要支付
            if (res.data.isPay === false) {
              that.$successToast('购买成功');
              that.refreshList();
            }
            // 需要支付
            else {
              // 小程序环境
              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("&")}`
                })
              }
              // h5环境
              else {
                weixinPay(res.data, function (res) {
                  that.$successToast('购买成功');
                  that.refreshList();
                })
              }
            }
          })
        })
      },

    },
  }
</script>

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

.list-container {
  padding: 0 20rpx;
  box-sizing: border-box;
  .item {
    @include zj-card;
    padding: 20rpx;
    margin-top: 20rpx;
    .top {
      display: flex;
      justify-content: space-between;
      .left {
        display: flex;
        align-items: center;
        image {
          width: 88rpx;
          height: 88rpx;
          border-radius: 50%;
        }
        .info {
          margin-left: 20rpx;
          .name {
            font-size: 28rpx;
          }
          .text {
            font-size: 24rpx;
            color: $sec-font;
            margin-top: 12rpx;
          }
        }
      }
      .right {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        .status {
          color: $minor-color;
          font-size: 28rpx;
        }
        .tag {
          margin-top: 10rpx;
          display: flex;
          ::v-deep .u-tag {
            margin-left: 12rpx;
          }
        }
      }
    }
    .goods {
      display: flex;
      padding: 20rpx 0;
      image {
        width: 120rpx;
        height: 120rpx;
        margin-right: 20rpx;
      }
      .right {
        flex: 1;
        .name {
          font-size: 28rpx;
        }
        .text {
          font-size: 24rpx;
          color: $sec-font;
          margin-top: 8rpx;
        }
        .info {
          display: flex;
          margin-top: 12rpx;
          .price {
            font-size: 28rpx;
            color: $minor-color;
            font-weight: 600;
          }
          .num {
            font-size: 28rpx;
            margin-left: 12rpx;
          }
        }
      }
    }
    .total {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      border-top: 1px solid #eaeaea;
      padding: 20rpx 0;
      font-size: 28rpx;
      text {
        font-size: 32rpx;
        color: $minor-color;
        font-weight: 600;
        margin-left: 8rpx;
      }
    }
    .bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid #eaeaea;
      padding: 20rpx 0;
      &:last-child {
        padding-bottom: 0;
      }
      .left {
        font-size: 28rpx;
      }
      .right {
        display: flex;
        ::v-deep .u-button {
          margin-left: 20rpx;
        }
      }
    }
  }
}
</style>
