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) {
    const {
      callback
    } = e.detail;
    this.setData({
      pullDownRefreshing: true
    });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({
          pullDownRefreshing: false
        });
        callback && callback();
      })
      .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 5:
        _status = 1
        break;
      case 10:
        _status = 2
        break;
      case 40:
        _status = 3
        break;
      case 50:
        _status = 4
        break;
    }
    const params = {
      pageIndex: 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);
        const res = {
          "code": 200,
          "msg": "SUCCESS",
          "data": {
            "pageSize": 10,
            "pageIndex": 1,
            "totalNum": 9,
            "totalPage": 1,
            "result": [{
                "orderId": 17,
                "orderGuid": "1714904293930307584",
                "orderNo": "Q2310191520196710002",
                "goodsList": [{
                  "goodsGuId": "1672964367177617408",
                  "thumb": "http://shop.back.aerwen.net/prod-api//Uploads/Goods/20231010/BD3521D2710CF9CD.jpg",
                  "title": "韩哚馨（HANDUOXIN）韩哚馨 感学院风短袖茶歇法式连衣裙子碎花长裙2023新款",
                  "skuId": 232,
                  "specifications": [{
                    "specTitle": "规格",
                    "specValue": "常规款加绒"
                  }],
                  "price": 160.00,
                  "buyQuantity": 1
                }],
                "goodsTotalAmoun": 160.00,
                "orderAmount": 155.00,
                "payPrice": 0.01,
                "expressPrice": 0.00,
                "payStatus": 2,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 2,
                "isComment": 1,
                "status": 0,
                "statusName": null
              },
              {
                "orderId": 16,
                "orderGuid": "1714900618189082624",
                "orderNo": "Q2310191505433070002",
                "goodsList": [{
                  "goodsGuId": "1672964367177617408",
                  "thumb": "http://shop.back.aerwen.net/prod-api//Uploads/Goods/20231010/BD3521D2710CF9CD.jpg",
                  "title": "韩哚馨（HANDUOXIN）韩哚馨 感学院风短袖茶歇法式连衣裙子碎花长裙2023新款",
                  "skuId": 232,
                  "specifications": [{
                    "specTitle": "规格",
                    "specValue": "常规款加绒"
                  }],
                  "price": 160.00,
                  "buyQuantity": 3
                }],
                "goodsTotalAmoun": 480.00,
                "orderAmount": 475.00,
                "payPrice": 0.01,
                "expressPrice": 0.00,
                "payStatus": 2,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 2,
                "statusName": "待发货"
              },
              {
                "orderId": 15,
                "orderGuid": "1714899117605523456",
                "orderNo": "Q2310191459455300002",
                "goodsList": [{
                  "goodsGuId": "1672961736711475200",
                  "thumb": "http://shop.back.aerwen.net/prod-api/Uploads/Goods/20231009/2E9F7284DE854663.jpg",
                  "title": "2024新款裙子夏季女法式桔梗碎花公主裙吊带连衣裙仙气仙森系 连衣裙 均码",
                  "skuId": 220,
                  "specifications": [{
                      "specTitle": "颜色分类",
                      "specValue": "碎花【收藏优先发货】"
                    },
                    {
                      "specTitle": "尺码 ",
                      "specValue": "S【建议70-95斤】"
                    }
                  ],
                  "price": 65.30,
                  "buyQuantity": 1
                }],
                "goodsTotalAmoun": 65.30,
                "orderAmount": 60.30,
                "payPrice": 0.01,
                "expressPrice": 0.00,
                "payStatus": 2,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 2,
                "statusName": "待发货"
              },
              {
                "orderId": 13,
                "orderGuid": "1714355378755604480",
                "orderNo": "Q2310180259081130005",
                "goodsList": [{
                  "goodsGuId": "1680467517816049664",
                  "thumb": "http://shop.back.aerwen.net/prod-api/Uploads/Goods/20231014/FFCD5093C92A62B1.jpg",
                  "title": "三只松鼠肉松饼1000g 黄金肉松饼早餐代餐休闲零食办公室点心面包量贩箱装",
                  "skuId": 0,
                  "specifications": null,
                  "price": 9.90,
                  "buyQuantity": 2
                }],
                "goodsTotalAmoun": 19.80,
                "orderAmount": 3001.80,
                "payPrice": 19.80,
                "expressPrice": 13.00,
                "payStatus": 2,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 2,
                "statusName": "待发货"
              },
              {
                "orderId": 14,
                "orderGuid": "1714355379099537408",
                "orderNo": "Q2310180259081130006",
                "goodsList": [{
                  "goodsGuId": "1673671239077597184",
                  "thumb": "http://shop.back.aerwen.net/prod-api/Uploads/Goods/20231014/666229CAA9F1B6AE.jpg",
                  "title": "三星 Galaxy S21 5G（SM-G9910）双模5G 骁龙888 超高清专业摄像 120Hz护目屏 游戏手机 8G+128G",
                  "skuId": 235,
                  "specifications": [{
                    "specTitle": "颜色",
                    "specValue": "梵梦紫"
                  }],
                  "price": 2969.00,
                  "buyQuantity": 1
                }],
                "goodsTotalAmoun": 2969.00,
                "orderAmount": 3001.80,
                "payPrice": 2969.00,
                "expressPrice": 13.00,
                "payStatus": 2,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 2,
                "statusName": "待发货"
              },
              {
                "orderId": 9,
                "orderGuid": "1713568156318044160",
                "orderNo": "Q2310152250589130002",
                "goodsList": [{
                  "goodsGuId": "1672961736711475200",
                  "thumb": "http://shop.back.aerwen.net/prod-api/Uploads/Goods/20231009/2E9F7284DE854663.jpg",
                  "title": "2024新款裙子夏季女法式桔梗碎花公主裙吊带连衣裙仙气仙森系 连衣裙 均码",
                  "skuId": 220,
                  "specifications": [{
                      "specTitle": "颜色分类",
                      "specValue": "碎花【收藏优先发货】"
                    },
                    {
                      "specTitle": "尺码 ",
                      "specValue": "S【建议70-95斤】"
                    }
                  ],
                  "price": 65.30,
                  "buyQuantity": 2
                }],
                "goodsTotalAmoun": 130.60,
                "orderAmount": 130.60,
                "payPrice": 2.00,
                "expressPrice": 0.00,
                "payStatus": 2,
                "deliveryStatus": 2,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 3,
                "statusName": "待收货"
              },
              {
                "orderId": 7,
                "orderGuid": "1713125767367495680",
                "orderNo": "Q2310141733050100001",
                "goodsList": [{
                  "goodsGuId": "1672964367177617408",
                  "thumb": "http://shop.back.aerwen.net/prod-api//Uploads/Goods/20231010/BD3521D2710CF9CD.jpg",
                  "title": "韩哚馨（HANDUOXIN）韩哚馨 感学院风短袖茶歇法式连衣裙子碎花长裙2023新款",
                  "skuId": 231,
                  "specifications": [{
                    "specTitle": "规格",
                    "specValue": "爆款加绒"
                  }],
                  "price": 199.00,
                  "buyQuantity": 1
                }],
                "goodsTotalAmoun": 199.00,
                "orderAmount": 199.00,
                "payPrice": 1.00,
                "expressPrice": 0.00,
                "payStatus": 2,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 2,
                "statusName": "待发货"
              },
              {
                "orderId": 6,
                "orderGuid": "1713124559743488000",
                "orderNo": "Q2310141728171060001",
                "goodsList": [{
                  "goodsGuId": "1680467515018448896",
                  "thumb": "http://shop.back.aerwen.net/prod-api/Uploads/Goods/20231014/EF0885623F14CA0C.jpg",
                  "title": "双汇 火腿肠 玉米热狗40g*8支 网兜装 出游 露营款",
                  "skuId": 0,
                  "specifications": null,
                  "price": 13.00,
                  "buyQuantity": 10
                }],
                "goodsTotalAmoun": 130.00,
                "orderAmount": 143.00,
                "payPrice": 1.00,
                "expressPrice": 13.00,
                "payStatus": 2,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 2,
                "statusName": "待发货"
              },
              {
                "orderId": 5,
                "orderGuid": "1713121315600338944",
                "orderNo": "Q2310141715235960001",
                "goodsList": [{
                  "goodsGuId": "1672964367177617408",
                  "thumb": "http://shop.back.aerwen.net/prod-api//Uploads/Goods/20231010/BD3521D2710CF9CD.jpg",
                  "title": "韩哚馨（HANDUOXIN）韩哚馨 感学院风短袖茶歇法式连衣裙子碎花长裙2023新款",
                  "skuId": 231,
                  "specifications": [{
                    "specTitle": "规格",
                    "specValue": "爆款加绒"
                  }],
                  "price": 199.00,
                  "buyQuantity": 1
                }],
                "goodsTotalAmoun": 199.00,
                "orderAmount": 199.00,
                "payPrice": 0.00,
                "expressPrice": 0.00,
                "payStatus": 1,
                "deliveryStatus": 1,
                "receiptStatus": 1,
                "orderStatus": 1,
                "isComment": 1,
                "status": 1,
                "statusName": "待付款"
              }
            ],
            "extra": {}
          }
        }
        this.page.num++;
        let orderList = [];
        if (res && res.data && res.data.result) {
          orderList = (res.data.result || []).map((order) => {
            return {
              id: order.orderId,
              orderNo: order.orderNo,
              // parentOrderNo: order.parentOrderNo,
              storeId: order.storeId,
              storeName: order.storeName,
              status: order.orderStatus,
              statusDesc: order.statusName,
              amount: order.payPrice,
              totalAmount: order.orderAmount,
              // logisticsNo: order.logisticsVO.logisticsNo,
              // createTime: order.createTime,
              goodsList: (order.goodsList || []).map((goods) => ({
                id: goods.id,
                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);
    // console.log(value,'asdasd');
    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?orderNo=${order.orderNo}`,
    });
  },
});