<template>
  <view class="dt-page">
    <view class="scroll-tab-wrap">
      <DtScrollTab :config="configTab" :dataList="tabList" :current.sync="curTab" @change="onTabChange" />
    </view>
    <swiper :style="calcHeight" duration="300" :current="curTab" @change="onSwiperChange">
      <swiper-item v-for="(tItem, tIdx) in tabList" :key="tIdx">
        <scroll-view @scrolltolower="onReachLower" scroll-y="true" class="scoll-h">
          <block v-if="curTab==tIdx">
            <view v-if="emptyType==0" class="content-wrap">
              <view v-for="(item,idx) in dataList" :key="idx" class="order-item-wrap">
                <DtOrderItem :dataDetail="item" @timer="onTimer(idx)" @tapbtn="onTapBtn($event,idx)" @order="onOrderTap" />
              </view>
              <DtNoMore v-if="isNoMore" />
            </view>
			<DtEmpty :type="emptyType"/>
			<!-- <DtEmpty :type="emptyType" :wrapHeight="50+'%'" :loadingPaddingTop="20+'%'"/> -->
			<view v-if="recomendList.length>0" clsss="recommend">
			  <DtRecommendWrap title="新邻推荐" />
			  <DtRecommendGoodsList :dataList="recomendList" />
			</view>
          </block>
        </scroll-view>
      </swiper-item>
    </swiper>

    <!-- 微信客服 -->
    <DtService />
  </view>
</template>
<script>
import DtScrollTab from '../comps/dt_scroll_tab.vue'
import DtOrderItem from '../comps/dt_order_item.vue'
import DtEmpty from '../comps/dt_empty.vue'
import DtNoMore from '../comps/dt_no_more.vue'
import DtService from '../comps/dt_service.vue'
import DtRecommendWrap from '../comps/dt_recommend_wrap.vue'
import DtRecommendGoodsList from '../comps/dt_recommend_goods_list.vue'
export default {
  components: {
    DtScrollTab,
    DtOrderItem,
    DtEmpty,
    DtNoMore,
    DtService,
	DtRecommendWrap,
	DtRecommendGoodsList
  },
  data() {
    return {
      configTab: {
        width: '20vw',
        isActiveLine: true
      },
      curTab: 0,
      tabList: ['全部', '待付款', '待发货', '待收货', '已取消', '待评价','已完成','退款/售后'],
      winHeight: "", //窗口高度,
      dataList: [],
      memberId: '',
	  isOne: true,
	  recomendList:[]
    }
  },
  computed: {
    calcHeight() {
      return "height:" + this.winHeight + "px;";
    },
    tabValues() {
      return [
        this.orderState.all,
        this.orderState.waitForPay,
        this.orderState.waitForDelive,
        this.orderState.waitForReceive,
        this.orderState.cancel,
        this.orderState.waitForAppraise,
        this.orderState.finished,
        this.orderState.afterSale
      ]
    },
    orderState() {
      return this.$global.orderState
    },
    saledStatus(){
      return this.$global.saledStatus
    },
    saledStatusName(){
      return this.$global.saledStatusName
    },
    refundState() {
      return [
        this.orderState.refunded,     // 已退款
        this.orderState.failRefund,   // 退款失败
        this.orderState.refunding,    // 退款中
      ]
    },
  },
  methods: {
	// 推荐商品列表
	async queryRecomendList() {
	  let params = [
	    {
	      t: 3,
	      v: -1,
	      k: "hits"
	    },
	    {
	      t: 1,
	      v: this.$global.server.storeId,
	      k: "storeId"
	    }
	  ]
	  let resp = await this.$api.searchProduct({
	    memberId: this.memberId,
	    pageNo: this.pageIndex,
	    pageSize: 10,
	    params: params
	  })
	  let list = this.getDataList(resp);
	  this.recomendList = this.recomendList.concat(list)
	},
    onSwiperChange(e) {
      console.log(113, e)
      this.curTab = e.detail.current
      this.isNoMore = false
      this.emptyType = -1
      this.pageIndex = 0;
      this.dataList.length = 0
      this.queryDataList(this.tabValues[this.curTab])
    },
    onTabChange(idx) {
      console.log(23, this.tabValues[idx])
    },
    onOrderTap(item) {
      let isAfterSales = this.curTab === this.tabList.length-1
      if(isAfterSales){
        uni.navigateTo({
          url: '/pagesM/pages/order_sale_detail?orderSns='+ item.sn +'&adfterSaleId=' + item.id +'&isAfterSales='+1
        })
      }else{
        uni.navigateTo({
          url: '/pagesM/pages/order_detail?orderSns=' + item.sn
        })
      }
      
    },
    // 过期
    onTimer(idx) {
      let dataList = this.dataList.slice(0)
      let curItem = dataList[idx]
      let state = this.orderState.cancel
      curItem.status = state
      curItem.statusTxt = this.$global.orderStateName[state]
      dataList[idx] = curItem
      this.dataList = dataList
    },
    onTapBtn({flag, item},idx) {
      console.log(118, flag, item, idx)
      switch (flag) {
        case 'cancel':
          this.cancelOrder(item)
          break;
        case 'pay':
          this.payOrder(item)
          break;
        case 'refund':
          this.refund(item)
          break;
        case 'cancelRefund':
          this.cancelRefund(item)
          break;
		case 'refund_choose':
			this.refund_choose(item)
		break;
        case 'receive':
          this.$dialog.confirm({
            content: '确认收货吗？',
            success: async (res) => {
              if (res.confirm) {
                this.receiveOrder(item)
              }
            }
          })
          break;
        case 'appraise':
          uni.navigateTo({
            url: '/pagesM/pages/order_appraise?idx=' + idx
          })
          break;
        case 'delete':
          this.$dialog.confirm({
            content: '确认删除该订单吗？',
            success: async (res) => {
              if (res.confirm) {
                this.delOrder(item)
              }
            }
          })
          break;
        default: break;
      }
    },
	async refund_choose(item) {
	  uni.navigateTo({
	    url:'/pagesM/pages/after_sale_choose?orderId='+item.id
	  })
	},
    async cancelOrder(item) {
      this.$dialog.confirm({
        content:'确认取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            todoCancelOrder()
          }
        }
      })
      let ctx = this
      async function todoCancelOrder(){
        let resp = await ctx.$api.cancelOrder({
          sn: item.sn,
          detail:'订单取消',
          remark:'B2C微信小程序用户取消订单',
        })
        ctx.$dialog.success('取消成功',()=>{
          ctx.$util.refreshPage(['pages/mine'])
          ctx.onPullDownRefreshPage()
        })
      }
      // let resp = await this.$api.cancelOrder({
      //   sn: item.sn,
      //   detail: '订单取消',
      //   remark: 'B2C微信小程序用户取消订单',
      // })
      // this.$util.refreshPage(['pages/mine'])
      // this.isPull = true
      // this.queryDataList(this.tabValues[this.curTab])
    },
    async payOrder(item) {
      let sns = [item.sn]
      uni.navigateTo({ url: "/pagesM/pages/order_pay?orderSns=" + JSON.stringify(sns) + "&payFlag=" + this.$global.payFlag.order });
    },
    async refund(item) {
      uni.navigateTo({
        // url:'/pages/after_sale_choose?orderId='+item.id
        url:'/pagesM/pages/after_sale_submit?orderId='+item.id
      })
    },
    async cancelRefund(item) {
      this.$dialog.confirm({
        content: '确定取消售后吗？',
        success: async (res) => {
          if (res.confirm) {
            todoCancelRefund()
          }
        }
      })
      let ctx = this
      async function todoCancelRefund(){
        let resp = await ctx.$api.cancelAftersales({
          _isShowLoading:true,
          id:item.id
        })
        ctx.$dialog.success('取消成功',()=>{
          ctx.$util.refreshPage(['pages/mine'])
          ctx.onPullDownRefreshPage()
        })
      }
    },
    async receiveOrder(item) {
      let resp = await this.$api.orderChange({
        memberId: this.memberId,
        orderId: item.id,
        execType: 2
      })
      this.$dialog.success('确认收货',()=>{
        this.$util.refreshPage(['pages/mine'])
        this.onPullDownRefreshPage()
      })
    },
    async delOrder(item) {
      let resp = await this.$api.delOrder({
        orderId: item.id
      })
      // this.$dialog.success('删除成功')
      this.$util.refreshPage(['pages/mine'])
      this.onPullDownRefreshPage()
    },
    // tapToDetail(item){
    //   uni.navigateTo({
    //     url:'/pages/order_detail'
    //   })
    // },
    onReachLower(ev) {
      console.log(108, ev)
      this.onReachBottomPage();
    },
    // 查询数据
    async queryDataList(status) {
      if (this.isPull) {
        this.emptyType = -1
        this.isNoMore = false
        this.pageIndex = 0
        this.dataList.length = 0
      }
      let resp = null, list = []
      if(this.curTab==7){
        resp = await this.$api.getAftersaless({
          _isShowLoading:true,
          _isPull: this.isPull,
          memberId:this.memberId,
          pageNo:this.pageIndex,
          pageSize:this.pageSize
        })
      }else{
        resp = await this.$api.getMyOrders({
          _isShowLoading: true,
          _isPull: this.isPull,
          status: status || this.$global.orderState.all,
          memberId: this.memberId,
          pageNo: this.pageIndex,
          pageSize: this.pageSize
        })
      }
      list = this.getDataList(resp);
	
      if(this.curTab==7){
        list.map((item) => {
          item.sn = item.orderSN
          item.amount = 0
          item.products = item.aftersalesItems.slice(0)
          item.products.map((itm) => {
            itm.specificationsDesc = itm.specifications.join('　')
            item.amount += itm.quantity * itm.price
            return itm
          })
          let status = item.status
          item.status = this.saledStatus[status]
          item.statusTxt = this.saledStatusName[status]
          return item
        })
      }else{
        list.map((item) => {
          item.products.map((itm) => {
            itm.specificationsDesc = itm.specifications.join('　')
            return itm
          })
          return item
        })
      }
      this.dataList = this.dataList.concat(list)
    },

    onLoadPage(options) {
	  wx.hideShareMenu();
      if (this.isLoad) {
        this.curTab = parseInt(options.state) || 0
        this.memberId = this.$auth.getMemberId()
        if (options.state == 0) {
          this.queryDataList()
        }
        // 初始化高度
        let res = uni.getSystemInfoSync();
        let clientHeight = res.windowHeight;
        let clientWidth = res.windowWidth;
        let upxR = 750 / clientWidth;
        let calc = clientHeight * upxR - 110;
        let height = uni.upx2px(calc);
        this.winHeight = height;
      }
      if (this.isReach || this.isPull) {
        console.log(331, 'isReach',this.isReach,this.isPull)
		this.queryDataList(this.tabValues[this.curTab]);
      }
    },
  },
  onShow(){
    this.onShowPage()
	// if(this.isOne){
	// 	this.isOne = false;
	// 	return;
	// }
	let e = {detail:{current:this.curTab}};
	//发起售后返回后会刷新执行，所以加个判断
	if (!this.isReach&&!this.isPull) {
		this.onSwiperChange(e);
	}
	
  },
  onPullDownRefresh(){
    this.onPullDownRefreshPage()
  },
}
</script>

<style lang="scss" scoped>
.dt-page {
  min-height: 100vh;
  background-color: #f2f2f2;
  .scroll-tab-wrap {
    margin-bottom: 20upx;
  }
  .scoll-h {
    height: 100%;
    // .conttent-wrap {
    // }
  }

  .content-wrap {
    .order-item-wrap {
      margin-bottom: 20upx;
    }
  }
}
</style>