<template>
<view id="afterSales-center">
    <view class="navbar mx-1px-bottom">
        <block v-for="(item, index) in tabList" :key="index" >
            <view :id="index" class="navbar-item" :class="activeIndex == index ? 'activity' : ''" @tap="tabClick">
                <view class="navbar-title">{{item.title}}</view>
            </view>
        </block>
        <view class="navbar-slider" :style="'width: ' + width + 'px; transform: translateX(' + sliderOffset + 'px); -webkit-transform: translateX(' + sliderOffset + 'px);'"></view>
    </view>
    <view class="tab-panel">
        <view class="tab-content" :hidden="activeIndex != 0">
            <view class="order-box">
               <view v-for="(item, idx) in dataList[0]" :key="idx" >
                   <view class="order-item" v-if="order.can_refund" :data-no="order.order_no" v-for="(order, index) in dataList[0][idx]" :key="index">
                       <view class="item-top">
                           <view class="indent mx-1px-bottom">
                               <view class="order-num">
                                   订单编号：{{order.order_no}}
                               </view>
                               <view class="order-type">
                                   {{statusList[order.status]}}
                               </view>
                           </view>
                       </view>
                       <view class="item-middle">
                           <view class="middle-item mx-1px-bottom" v-if="!good.is_refunded" v-for="(good, index) in order.items" :key="index" >
                               <image :src="good.item_meta.image"></image>
                               <view class="text">
                                   <view class="names">
                                       {{good.item_name}}
                                   </view>
                                   <view class="model">
                                       {{good.item_meta.specs_text}}
                                   </view>
                               </view>
                               <view class="money-box">
                                   <view>
                                       {{good.quantity}}件
                                   </view>
                                   <view>
                                       <view class="button-box" @tap="viewRetreat" :data-id="good.id" :data-no="order.order_no" v-if="!good.is_refunded">
                                           申请售后
                                       </view>
                                   </view>
                               </view>
                           </view>
                       </view>
                       <view class="item-bottom">
                           <view class="all-money">
                               下单时间:{{order.submit_time}}
                           </view>
                       </view>
                   </view>
               </view>
                <view class="loadingbox" :hidden="!tabList[0].show">
                    {{showText}}
                </view>
            </view>
        </view>

        <view class="tab-content" :hidden="activeIndex != 1">
            <view class="order-box">
                <view v-for="(item, idx) in dataList[1]" :key="idx" >
                    <view class="order-item" :data-no="order.refund_no" :data-status="order.status" v-for="(order, index) in dataList[1][idx]" :key="index"  @tap="viewSales">
                        <view class="item-top">
                            <view class="indent mx-1px-bottom">
                                <view class="order-num">
                                    订单编号：{{order.order.order_no}}
                                </view>
                                <view class="order-type">
                                    {{typeList[order.status]}}

                                </view>
                            </view>
                        </view>
                        <view class="item-middle">
                            <view class="middle-item mx-1px-bottom">
                                <image :src="order.order_item.item_meta.image"></image>
                                <view class="text">
                                    <view class="names">
                                        {{order.order_item.item_name}}
                                    </view>
                                    <view class="model">
                                        {{order.order_item.item_meta.specs_text}}
                                    </view>
                                </view>
                                <view class="money-box">
                                    <view>
                                        {{order.order_item.quantity}}件
                                    </view>

                                </view>
                            </view>
                        </view>
                        <view class="item-bottom">
                            <view class="all-money">
                                申请时间:{{order.updated_at}}
                            </view>
                            <view class="button-box" v-if="order.status === 1">
                                立即退货
                            </view>
                            <view class="button-box" v-if="order.status === 0">
                                取消申请
                            </view>
                        </view>
                    </view>
                </view>
                <view class="loadingbox" :hidden="!tabList[1].show">
                    {{showText}}
                </view>
            </view>
        </view>
        <view class="tab-content" :hidden="activeIndex != 2">
            <view class="order-box">
                <view v-for="(item, idx) in dataList[2]" :key="idx">
                    <view class="order-item" :data-no="order.refund_no" :data-status="order.status" v-for="(order, index) in dataList[2][idx]" :key="index"  @tap="viewSales">
                        <view class="item-top">
                            <view class="indent mx-1px-bottom">
                                <view class="order-num">
                                    订单编号：{{order.order.order_no}}
                                </view>
                                <view class="order-type">
                                    {{typeList[order.status]}}
                                </view>
                            </view>
                        </view>
                        <view class="item-middle">
                            <view class="middle-item mx-1px-bottom">
                                <image :src="order.order_item.item_meta.image"></image>
                                <view class="text">
                                    <view class="names">
                                        {{order.order_item.item_name}}
                                    </view>
                                    <view class="model">
                                        {{order.order_item.item_meta.specs_text}}
                                    </view>
                                </view>
                                <view class="money-box">
                                    <view>
                                        {{order.order_item.quantity}}件
                                    </view>

                                </view>
                            </view>
                        </view>
                        <view class="item-bottom">
                            <view class="all-money">
                                申请时间:{{order.updated_at}}
                            </view>
                        </view>
                    </view>
                </view>
                <view class="loadingbox" :hidden="!tabList[1].show">
                    {{showText}}
                </view>
            </view>
        </view>
    </view>
</view>

</template>
<script>
// pages/order/index/index.js
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';

export default {
  data() {
    return {
      activeIndex: 0,
      sliderOffset: 0,
      sliderLeft: 0,
      width: 0,
      tabList: [{
        title: "可申请",
        init: false,
        page: 0,
        id: 0,
        name: "after",
        more: true,
        show: false
      }, {
        title: "申请中",
        init: false,
        page: 0,
        id: 1,
        name: "process",
        more: true,
        show: false
      }, {
        title: "已结束",
        init: false,
        page: 0,
        id: 2,
        name: "end",
        more: true,
        show: false
      }],
      dataList: {
        0: [],
        1: [],
        2: []
      },
      statusList: ['临时订单', '待付款', '付款成功', '已发货', '已完成', '已完成', '已取消', '已退款', '已作废', '已删除'],
      typeList: ['申请审核中', '申请已通过', '拒绝申请', '退款成功', '售后已关闭', '等待用户退货', '退货中', '等待商城发货'],
      showText: '正在加载下一页数据',
      token: ''
    };
  },

  onReachBottom(e) {
    var status = this.activeIndex;
    var page = this.tabList[status].page + 1;
    var tabList = `tabList[${status}]`;

    if (this.tabList[status].more) {
      this.setData({
        [`${tabList}.show`]: true
      });

      if (status == 0) {
        [];
        this.operabale(0, page);
      } else {
        this.orderList(0, status, page);
      }
    } else {
      wx.showToast({
        title: '再拉也没有啦'
      });
    }
  },

  onShow(e) {
    wx.showLoading({
      title: "加载中",
      mask: true
    });
    wx.getSystemInfo({
      success: res => {
        this.setData({
          width: res.windowWidth / this.tabList.length,
          sliderOffset: res.windowWidth / this.tabList.length * this.activeIndex
        });
      }
    });
    pageLogin(getUrl(), () => {
      this.operabale(0, 1);
    }); // let app =getApp();
    // app.isBirthday().then(()=>{
    //     if(this.$cookieStorage.get("birthday_gift")){
    //         var giftData=this.$cookieStorage.get("birthday_gift").data;
    //         new app.ToastPannel().__page.showText(giftData);
    //     }
    // });
    // this.orderList(0, this.activeIndex);
  },

  components: {},
  props: {},
  methods: {
    // jump(e) {
    //     wx.navigateTo({
    //         url: '/pages/afterSales/apply/apply?no=' + e.currentTarget.dataset.no
    //     })
    // },
    tabClick(e) {
      var status = e.currentTarget.id;
      this.setData({
        sliderOffset: e.currentTarget.offsetLeft,
        activeIndex: status
      });

     wx.showLoading({
       title: "加载中",
       mask: true
     });
     
     if (status == 0) {
       this.operabale(0, 1);
     } else {
       this.orderList(0, status);
     }
    },

    viewRetreat(e) {
      wx.navigateTo({
        url: '/pages/afterSales/apply/apply?no=' + e.currentTarget.dataset.no + '&id=' + e.currentTarget.dataset.id
      });
    },

    viewSales(e) {
      var refund_no = e.currentTarget.dataset.no;
      var refund_status = e.currentTarget.dataset.status;
      var type = e.currentTarget.dataset.type;

      if (refund_no == null) {
        return;
      } else {
        wx.navigateTo({
          url: '/pages/afterSales/detail/detail?no=' + refund_no
        });
      }
    },

    operabale(status = 0, pages = 1, type = [0, 1, 2]) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.get({
        api: 'api/order/refund/list',
        header: {
          Authorization: token
        },
        data: {
          pages,
          type
        }
      }).then(res => {
        res = res.data;
        var page = res.meta.pagination;
        var total_pages = page.total_pages;
        // this.setData({
        //   [`dataList.${status}[${pages - 1}]`]: res.data,
        //   [`${tabList}.init`]: true,
        //   [`${tabList}.page`]: pages,
        //   [`${tabList}.more`]: pages < total_pages
        // });
		
	
	    this.$set(this.dataList[status], pages-1, res.data);
		this.tabList[status].init=true;
		this.tabList[status].page=pages;
		this.tabList[status].more=pages < total_pages;
		
        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
      });
    },

    // 获取订单列表
    orderList(offline = 0, status = 1, pages = 1, type = 0) {
      var token = this.$cookieStorage.get('user_token');

      var state = this.tabList[status].name;
      var params = status ? {
        status
      } : {};
      params.page = pages;
      params.status = state; // params.offline = offline;

      this.$http.get({
        api: 'api/refund/list',
        header: {
          Authorization: token
        },
        data: params
      }).then(res => {
        res = res.data;
        var page = res.meta.pagination;
        var current_page = page.current_page;
        var total_pages = page.total_pages;
        var tabList = `tabList[${status}]`;
        // this.setData({
        //   [`dataList.${status}[${pages - 1}]`]: res.data,
        //   [`${tabList}.init`]: true,
        //   [`${tabList}.page`]: current_page,
        //   [`${tabList}.more`]: current_page < total_pages
        // });
		
	
	    this.$set(this.dataList[status], pages-1, res.data);
		this.tabList[status].init=true;
		this.tabList[status].page=pages;
		this.tabList[status].more=pages < total_pages;
		
        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
      });
    },

    // 确认收货
    receiveOrder(orderNo) {
      var token = this.token;
      this.$http.post({
        api: 'api/shopping/order/received',
        header: {
          Authorization: token
        },
        data: {
          order_no: orderNo
        }
      }).then(res => {
        res = res.data;
        wx.showModal({
          title: '',
          content: res.message,
          showCancel: false,
          success: res => {
            if (res.confirm) {
              this.orderList(0, this.activeIndex);
            }
          }
        });
      }).catch(rej => {
        if (rej.statusCode == 404) {
          wx.showModal({
            title: '',
            content: '接口不存在',
            showCancel: false
          });
        } else {
          wx.showModal({
            title: '',
            content: '取消订单失败, 请检查您的网络状态',
            showCancel: false
          });
        }
      });
    },

    // 删除订单
    deleteOrder(orderNo) {
      var token = this.token;
      this.$http.post({
        api: 'api/shopping/order/delete',
        header: {
          Authorization: token
        },
        data: {
          'order_no': orderNo
        }
      }).then(res => {
        wx.showToast({
          title: res.data.message
        });
        this.orderList(0, this.activeIndex);
      }).catch(rej => {
        wx.showModal({
          title: '',
          content: '删除订单失败, 请检查您的网络状态',
          showCancel: false
        });
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "index";
</style>
