import {
  OrderStatus
} from '../config';
import {
  fetchOrders,
  fetchOrdersCount,
} from '../../../services/order/orderList';
import {
  getOrderList
} from '~/services/order/getOrderList';
import {
  cosThumb
} from '../../../utils/util';

Page({
  page: {
    size: 10,
    num: 1,
  },

  data: {
    tabs: [{
        key: -1,
        text: '全部'
      },
      {
        key: OrderStatus.PENDING_PAYMENT,
        text: '待付款',
        info: ''
      },
      {
        key: OrderStatus.PENDING_DELIVERY,
        text: '待发货',
        info: ''
      },
      {
        key: OrderStatus.PENDING_RECEIPT,
        text: '待收货',
        info: ''
      },
      {
        key: OrderStatus.COMPLETE,
        text: '已完成',
        info: ''
      },
    ],
    curTab: -1,
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    backRefresh: false,
    status: -1,
  },

  onLoad(query) {
    let status = parseInt(query.status);
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : -1;
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  onReachBottom() {
    if (this.data.listLoading === 0) {
      this.onGetOrderList(this.data.curTab);
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    this.setData({
      pullDownRefreshing: true
    });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({
          pullDownRefreshing: false
        });
      })
      .catch((err) => {
        this.setData({
          pullDownRefreshing: false
        });
        Promise.reject(err);
      });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    this.refreshList(status);
  },

  changeOrderStatus(deliveryStatus, payStatus, orderStatus, receiptStatus) {

  },

  onGetOrderList(statusCode, reset = false) {
    let _status = -1;
    switch (statusCode) {
      case -1:
        _status = 0
        break;
      case 1:
        _status = 1
        break;
      case 2:
        _status = 2
        break;
      case 3:
        _status = 3
        break;
      case 4:
        _status = 4
        break;
      default:
        _status = 0
    }
    const params = {
      PageNum: this.page.num,
      pageSize: this.page.size,
      status: _status
    };
    // if (statusCode !== -1) params.parameter.orderStatus = statusCode;
    this.setData({
      listLoading: 1
    });
    return getOrderList(params)
      .then((res) => {
        // console.log(res);
        this.page.num++;
        let orderList = [];
        if (res && res.data && res.data.result) {
          orderList = (res.data.result || []).map((order) => {
            return {
              id: order.orderId,
              Guid: order.orderGuid,
              orderNo: order.orderNo,
              // parentOrderNo: order.parentOrderNo,
              // storeId: order.storeId,
              // storeName: order.storeName,
              status: order.status,
              statusDesc: order.statusName,
              amount: order.payPrice,
              totalAmount: order.orderAmount,
              // logisticsNo: order.logisticsVO.logisticsNo,
              // createTime: order.createTime,
              goodsList: (order.goodsList || []).map((goods) => ({
                id: goods.goodsGuId,
                thumb: goods.thumb,
                title: goods.title,
                skuId: goods.skuId,
                // spuId: goods.spuId,
                specs: (goods.specifications || []).map(
                  (spec) => spec.specValue,
                ),
                price: goods.price,
                num: goods.buyQuantity,
                titlePrefixTags: goods.tagText ? [{
                  text: goods.tagText
                }] : [],
              })),
              buttons: order.buttonVOs || [],
              // groupInfoVo: order.groupInfoVo,
              freightFee: order.expressPrice,
            };
          });
          // console.log(orderList);
        }
        return new Promise((resolve) => {
          if (reset) {
            this.setData({
              orderList: []
            }, () => resolve());
          } else resolve();
        }).then(() => {
          this.setData({
            orderList: this.data.orderList.concat(orderList),
            listLoading: orderList.length > 0 ? 0 : 2,
          });
          // console.log(orderList);
        });
      })
      .catch((err) => {
        this.setData({
          listLoading: 3
        });
        return Promise.reject(err);
      });
  },

  onReTryLoad() {
    this.onGetOrderList(this.data.curTab);
  },

  onTabChange(e) {
    // console.log(e);
    const {
      value
    } = e.detail;
    this.setData({
      status: value,
    });
    // console.log(value);
    this.refreshList(value);
  },

  getOrdersCount() {
    return fetchOrdersCount().then((res) => {
      const tabsCount = res.data || [];
      const {
        tabs
      } = this.data;
      tabs.forEach((tab) => {
        const tabCount = tabsCount.find((c) => c.tabType === tab.key);
        if (tabCount) {
          tab.info = tabCount.orderNum;
        }
      });
      this.setData({
        tabs
      });
    });
  },

  refreshList(status = -1) {
    this.page = {
      size: this.page.size,
      num: 1,
    };
    this.setData({
      curTab: status,
      orderList: []
    });

    return Promise.all([
      this.onGetOrderList(status, true),
      this.getOrdersCount(),
    ]);
  },

  onRefresh() {
    this.refreshList(this.data.curTab);
  },

  onOrderCardTap(e) {
    const {
      order
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/order-detail/index?orderGuid=${order.Guid}`,
    });
  },
});