// pages/member/myOrder_v2/myOrder_v2.js
var app = getApp();
const storeAlone =["plugin.store-alone-temp.frontend.fightGroups.list.index","plugin.store-alone-temp.frontend.fightGroups.list.grouping","plugin.store-alone-temp.frontend.fightGroups.list.waitPay","plugin.store-alone-temp.frontend.fightGroups.list.waitSend","plugin.store-alone-temp.frontend.fightGroups.list.waitReceive","plugin.store-alone-temp.frontend.fightGroups.list.completed"];
let _search_screen_type='';
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    NavList:[],
    scrollTop: 0,
    //当前的订单状态
    selected: 0,
    isLoadMore: true,
    //shop 商城，cashier 收银台 store 门店
    orderType: 'shop',
    detailUrl: 'orderdetail',
    total_page: 0,
    page: 1,
    action: '',
    //全部订单
    orderList: [],
    //待付款
    waitPayList: [],
    //待发货
    waitSendList: [],
    //全待收货
    waitReceiveList: [],
    //已完成
    waitCompleteList: [],
    stopRefresh: false,
    //待付款-多订单合并付款的订单id数组
    order_ids: [],
    //是否开启合并支付
    isMultiplePay: false,

    keywords: "",
    searchType: 0,
    searchTypes: [
      {name: '商品名', value: 1,placeholder:"请输入商品名称"},
      {name: '订单号', value: 2,placeholder:"请输入商品编号"},
      {name: '姓名', value: 3,placeholder:"请输入收货人姓名"},
      {name: '手机号', value: 4,placeholder:"请输入收货人手机号"},
    ],
    searchScreenShow:false,
    // 控制合并支付按钮
    consolidated_payment:false,

    custom_receipt_confirmation_html:"",
    // 不显示tab
    noShowTab:false,
    // 置换亿栈身份标识
    debt_shop_member_type:''
  },

  setSearchScreenShow(){
    this.setData({
      searchScreenShow:!this.data.searchScreenShow
    });
  },
  setSearchType(evt){
    let index = evt.currentTarget.dataset.index;
    this.setData({
      searchType:index
    });
    this.setSearchScreenShow();
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if (options.orderType && options.orderType == 'cashier') {
      this.setData({
        orderType: 'cashier',
        detailUrl: 'cashierOrderdetail'
      });
    } else if (options.orderType && options.orderType == 'stock') {
      this.setData({
        orderType: 'stock',
        detailUrl: 'stockOrderdetail'
      });
    } else if (options.orderType && options.orderType == 'store') {
      this.setData({
        orderType: 'store',
        detailUrl: 'storeOrderdetail'
      });
    } else if (options.orderType && options.orderType == 'supplier') {
      this.setData({
        orderType: 'supplier',
        detailUrl: 'supplierOrderdetail'
      });
    } else if (options.orderType && options.orderType == 'subsidiary') {
      this.setData({
        orderType: 'subsidiary',
        detailUrl: 'subsidiaryOrderdetail'
      });
    } else if (options.orderType && options.orderType == 'hotel') {
      this.setData({
        orderType: 'hotel',
        detailUrl: 'HotelOrderDetail'
      });
    } else if (options.orderType && options.orderType == 'hotel_center') {
      this.setData({
        orderType: 'hotel_center',
        detailUrl: 'HotelCenterOrderDetail'
      });
    } else if (options.orderType && options.orderType == 'hotelcashier') {
      this.setData({
        orderType: 'hotelcashier',
        detailUrl: 'HotelCashierOrderDetail'
      });
    } else if (options.orderType && options.orderType == 'lease_toy') {
      this.setData({
        orderType: 'lease_toy',
        detailUrl: 'orderdetail'
      });
    } else if (options.orderType && options.orderType == 'groups') {
      this.setData({
        orderType: 'groups',
        detailUrl: 'groupDetail'
      });
    } else if(options.orderType && options.orderType == 'auction'){
      this.setData({
        orderType: 'auction',
        detailUrl: 'orderdetail'
      });
    } else if(options.orderType && options.orderType == 'grabGroup'){
      this.setData({
        orderType: 'grabGroup',
        detailUrl: 'grabGroupOrderDetail'
      });
    }else if(options.orderType && options.orderType == 'newRetail'){
      this.setData({
        orderType: 'newRetail',
        detailUrl: 'orderdetail'
      });
    }else if(options.orderType && options.orderType == 'groupWork'){
      this.setData({
        orderType: 'groupWork',
        detailUrl: 'orderdetail'
      });
    }else if(options.orderType && options.orderType == 'storeMang'){
      wx.setNavigationBarTitle({
        title: '订单管理',
      });
      this.setData({
        orderType: 'storeMang',
        detailUrl: 'storeOrderdetail'
      });
    }else if(options.member_type){
      this.setData({
        orderType: 'debt',
        detailUrl: 'orderdetail',
        debt_shop_member_type:options.member_type,
        debtId:options.debtId
      });
    }else if(options.orderType||options.ordertype){
      this.setData({
        orderType: options.orderType||options.ordertype,
        detailUrl: 'orderdetail'
      });
    }else {
      this.setData({
        orderType: 'shop',
        detailUrl: 'orderdetail'
      });
    }
    this.setNavList();
    if (options.status) {
      this.setData({
        selected: Number(options.status)
      });
    }
    this._getOrderList(this.data.selected);
  },
  // 返回的顶部导航栏列表
  setNavList() {
    //注意第二个是待支付相关（即需支付的订单），因为涉及到合并支付
    let NavList = [];
    let noshow = false;
    if (this.data.orderType == "cashier") {
      NavList = ["全部", "待付款", "已完成"];
    } else if (this.data.orderType == "hotel") {
      NavList = ["全部", "待付款", "待确认", "待入住", "已完成", "待退房"];
    } else if (this.data.orderType == "lease_toy") {
      // 租凭导航
      NavList = ["全部", "待支付", "待发货", "待收货", "待归还", "已完成"];
    } else if (this.data.orderType == "groups") {
      NavList = ["全部", "拼团中", "待付款", "待发货", "待收货", "已完成"];
    } else if (this.data.orderType == "grabGroup") {
      NavList = ["抢团中", "待付款", "待发货", "待收货", "已完成"];
    } else if (this.data.orderType == "warehousePurchasing") {
      NavList = ["全部", "待付款", "已完成", "已关闭"];
    } else if (this.data.orderType == 'stock'){
      NavList = ['全部'];
      noshow = true;
    } else if (this.data.orderType == 'ysSystem'){
      NavList = ['全部'];
    } else {
      NavList = ["全部", "待付款", "待发货", "待收货", "已完成"];
    }
    this.setData({
      NavList:NavList,
      noShowTab:noshow,
    });
  },
  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {


  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {
    if (this.data.stopRefresh) {
      wx.stopPullDownRefresh();
    } else {
      this._initData();
      this._getOrderList(this.data.selected);
    }

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {
    if (this.data.isLoadMore) {
      this._getMoreData(this.data.page, this.data.selected);
    } else {
      console.log('没有更多数据');
    }
  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {

  },
  inpbtn(e) {
    let val = e.detail.value;
    this.setData({
      keywords: val
    });
  },
  inpbtnclear() {
    this.setData({
      keywords: ''
    });
  },
  search() {
    this.setData({
      selected: 0
    });
    _search_screen_type=this.data.searchType;
    this._getOrderList(0);
  },
  _initData() {
    this.setData({
      keywords: '',
      isLoadMore: true,
      page: 1,
      total_page: 0
    });
  },
  _getOrderList(index) {
    // apiConfig 配置插件的请求api,请安装顶部标签页 this.NavList 的配置顺序填写对应的请求url
    //apiConfig为Map数据结构，key为this.orderType，value为api集合
    let apiConfig = new Map([
      ["cashier", ["plugin.store-cashier.frontend.Order.list", "plugin.store-cashier.frontend.Order.list.waitPay", "plugin.store-cashier.frontend.Order.list.Completed"]],
      [
        "store",
        [
          "plugin.store-cashier.frontend.store.center.order-list.index",
          "plugin.store-cashier.frontend.store.center.order-list.waitPay",
          "plugin.store-cashier.frontend.store.center.order-list.waitSend",
          "plugin.store-cashier.frontend.store.center.order-list.waitReceive",
          "plugin.store-cashier.frontend.store.center.order-list.Completed"
        ]
      ],
      [
        "supplier",
        [
          "plugin.supplier.frontend.order.index",
          "plugin.supplier.frontend.order.wait-pay",
          "plugin.supplier.frontend.order.wait-send",
          "plugin.supplier.frontend.order.wait-receive",
          "plugin.supplier.frontend.order.completed"
        ]
      ],
      [
        "hotel",
        [
          "plugin.hotel.frontend.hotel.list",
          "plugin.hotel.frontend.hotel.list.wait-pay",
          "plugin.hotel.frontend.hotel.list.wait-send",
          "plugin.hotel.frontend.hotel.list.wait-enter",
          "plugin.hotel.frontend.hotel.list.completed"
        ]
      ],
      [
        "hotel_center",
        [
          "plugin.hotel.frontend.hotel.center.order-list",
          "plugin.hotel.frontend.hotel.center.order-list.wait-pay",
          "plugin.hotel.frontend.hotel.center.order-list.wait-send",
          "plugin.hotel.frontend.hotel.center.order-list.wait-enter",
          "plugin.hotel.frontend.hotel.center.order-list.completed",
          "plugin.hotel.frontend.hotel.center.order-list.check-out"
        ]
      ],
      ["hotelcashier", ["plugin.hotel.frontend.Order.list", "plugin.hotel.frontend.Order.list.waitPay", "plugin.hotel.frontend.Order.list.Completed"]],
      [
        "onlineCar",
        [
          "plugin.net-car.frontend.order-list.index",
          "plugin.net-car.frontend.order-list.wait-pay",
          "plugin.net-car.frontend.order-list.loan-review",
          "plugin.net-car.frontend.order-list.loan",
          "plugin.net-car.frontend.order-list.pick-car",
          "plugin.net-car.frontend.order-list.license-number"
        ]
      ],
      [
        "lease_toy",
        [
          "plugin.lease-toy.api.order.order-list.index",
          "plugin.lease-toy.api.order.order-list.wait-pay",
          "plugin.lease-toy.api.order.order-list.wait-send",
          "plugin.lease-toy.api.order.order-list.wait-receive",
          "plugin.lease-toy.api.order.order-list.wait-refund",
          "plugin.lease-toy.api.order.order-list.completed"
        ]
      ],
      [
        "groups",
        [
          "plugin.fight-groups.frontend.controllers.list.index",
          "plugin.fight-groups.frontend.controllers.list.grouping",
          "plugin.fight-groups.frontend.controllers.list.waitPay",
          "plugin.fight-groups.frontend.controllers.list.waitSend",
          "plugin.fight-groups.frontend.controllers.list.waitReceive",
          "plugin.fight-groups.frontend.controllers.list.completed"
        ]
      ],
      [
        "subsidiary",
        [
          "plugin.subsidiary.frontend.order.index",
          "plugin.subsidiary.frontend.order.wait-pay",
          "plugin.subsidiary.frontend.order.wait-send",
          "plugin.subsidiary.frontend.order.wait-receive",
          "plugin.subsidiary.frontend.order.completed"
        ]
      ],
      [
        "auctioneer",
        [
          "plugin.auction.api.auctioneer-order",
          "plugin.auction.api.auctioneer-order.waitPay",
          "plugin.auction.api.auctioneer-order.waitSend",
          "plugin.auction.api.auctioneer-order.waitReceive",
          "plugin.auction.api.auctioneer-order.completed"
        ]
      ],
      [
        "auction",
        [
          "plugin.auction.api.auction-order",
          "plugin.auction.api.auction-order.waitPay",
          "plugin.auction.api.auction-order.waitSend",
          "plugin.auction.api.auction-order.waitReceive",
          "plugin.auction.api.auction-order.completed"
        ]
      ],
      [
        "grabGroup",
        [
          "plugin.snatch-regiment.api.order.grouping",
          "plugin.snatch-regiment.api.order.waitPay",
          "plugin.snatch-regiment.api.order.waitSend",
          "plugin.snatch-regiment.api.order.waitReceive",
          "plugin.snatch-regiment.api.order.completed"
        ]
      ],
      [
        "groupWork",
        [
          "plugin.group-work.frontend.modules.order.controllers.records.index",
          "plugin.group-work.frontend.modules.order.controllers.records.waitPay",
          "plugin.group-work.frontend.modules.order.controllers.records.waitSend",
          "plugin.group-work.frontend.modules.order.controllers.records.waitReceive",
          "plugin.group-work.frontend.modules.order.controllers.records.completed"
        ]
      ],
      [
        "warehouseTakeDelivery",
        [
          "plugin.warehouse.frontend.controllers.takeDelivery.order",
          "plugin.warehouse.frontend.controllers.takeDelivery.order.waitPay",
          "plugin.warehouse.frontend.controllers.takeDelivery.order.waitSend",
          "plugin.warehouse.frontend.controllers.takeDelivery.order.waitReceive",
          "plugin.warehouse.frontend.controllers.takeDelivery.order.completed"
        ]
      ],
      [
        "warehousePurchasing",
        [
          "plugin.warehouse.frontend.controllers.purchasing.order.index",
          "plugin.warehouse.frontend.controllers.purchasing.order.waitPay",
          "plugin.warehouse.frontend.controllers.purchasing.order.completed",
          "plugin.warehouse.frontend.controllers.purchasing.order.cancelled"
        ]
      ],
      [
        "stock",
        [
          "plugin.order-inventory.frontend.order-list.get-inventory-list",
        ]
      ],
      ["ysSystem", ["plugin.ys-system.frontend.history-order.index",]]
    ]);
    //defaultApi : 商城商品订单接口
    let defaultApi = ["order.list", "order.list.waitPay", "order.list.waitSend", "order.list.waitReceive", "order.list.Completed"];
    let activeApiArr = []; //暂存获取到当前的api集合
    // console.log("orderType:::",this.data.orderType);
    if (apiConfig.has(this.data.orderType)) {
      //先通过has()判断apiConfig是否给key
      activeApiArr = apiConfig.get(this.data.orderType); //获取key(即this.data.orderType)设置的api集合
      if(app.globalData.store_alone_temp == 1){
        activeApiArr = storeAlone;
      }
    }else if(app.globalData.store_alone_temp == 1) {
      // 门店独立模板
      activeApiArr = ["plugin.store-alone-temp.frontend.order.index", "plugin.store-alone-temp.frontend.order.wait-pay", "plugin.store-alone-temp.frontend.order.wait-send","plugin.store-alone-temp.frontend.order.wait-receive","plugin.store-alone-temp.frontend.order.completed"];
    } else {
      activeApiArr = defaultApi; //has()为false。没配置，默认当作商城订单请求
    }

    try {
      console.log(index,activeApiArr[index]);
      this.data.action  = activeApiArr[index];
    } catch (error) {
      console.log("获取请求api数据失败报错：：", error);
    }
    if (this.data.orderType == "newRetail") {
      this.data.action = "plugin.new-retail.frontend.orderData.getList"; //新零售，所有状态一个接口
    }

    if (this.data.orderType == "storeMang") {
      this.data.action = "plugin.shop-assistant.frontend.order.order-list"; //店铺助手
    }

    this._getNetData(this.data.action, index);

  },
  //获取订单数据
  _getNetData(api, index) {
    let that = this;
    let urlStr = app.getNetAddresss(api);
    urlStr += "&page=" + this.data.page;
    if(this.data.debt_shop_member_type){
      urlStr += '&debt_shop_member_type=' + this.data.debt_shop_member_type
      urlStr += '&debtor_id=' + this.data.debtId
    }
    if (this.data.orderType == "newRetail") {
      // 新零售
      let order_status = "";
      switch (Number(index)) {
      case 0:
        order_status = 5;
        break;
      case 1:
        order_status = 4;
        break;
      case 2:
        order_status = 1;
        break;
      case 3:
        order_status = 2;
        break;
      case 4:
        order_status = 3;
        break;
      default:
        order_status = 5;
      }
      urlStr += `&search[keyword]=${this.data.keywords || ''}`;
      urlStr += `&search[order_status]=${order_status}`;
    }else if(this.data.orderType == "storeMang"){
      let mapStatus = ['', 'wait_pay', 'wait_send', 'wait_receive', 'completed'];
      urlStr += `&page=1`;
      urlStr += `&status=${mapStatus[index]}`;
      if(this.data.keywords!='' && _search_screen_type!==''){
        urlStr += `&search[search_type]=${this.data.searchTypes[_search_screen_type].value}`;
        urlStr += `&search[keyword]=${this.data.keywords}`;
      }
    }else{
      urlStr += "&keyword=" + this.data.keywords;
    }

    app._getNetWork({
      url: urlStr,
      showToastIn: false,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let myData = res.data;
          that.data.total_page = myData.total;
          if (index == 0) {
            that.setData({
              orderList: myData.data
            });
          } else if (index == 1) {
            that.setData({
              waitPayList: myData.data
            });
          } else if (index == 2) {
            that.setData({
              waitSendList: myData.data
            });
          } else if (index == 3) {
            that.setData({
              waitReceiveList: myData.data
            });
          } else if (index == 4) {
            that.setData({
              waitCompleteList: myData.data
            });
          } else {
            that.setData({
              waitRefund: myData.data
            });
          }
          that.setData({
            custom_receipt_confirmation_html:myData.receipt_goods_notice
          });
          try {
            let info = wx.getStorageSync('yz_basic_info');
            if(info.consolidated_payment){
              that.setData({
                consolidated_payment:info.consolidated_payment == '1'?true:false
              });
            }
          } catch (error) {
            console.log(error);
          }
        } else {
          if (res.data.url) {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500,
              success: function() {
                setTimeout(function() {
                  //要延时执行的代码
                  wx.navigateBack({
                    delta: 1
                  });
                }, 1500); //延迟时间
              },
            });
            return false;
          }
        }
        wx.stopPullDownRefresh();
      },
      fail: function(res) {
        wx.stopPullDownRefresh();

      }
    });
		
  },
  _getMoreData(page, index) {
    let that = this;
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let urlStr = app.getNetAddresss(this.data.action);
      if (this.data.orderType == "newRetail") {
        let order_status = "";
        switch (Number(index)) {
        case 0:
          order_status = 5;
          break;
        case 1:
          order_status = 4;
          break;
        case 2:
          order_status = 1;
          break;
        case 3:
          order_status = 2;
          break;
        case 4:
          order_status = 3;
          break;
        default:
          order_status = 5;
        }
        urlStr += `&search[keyword]=${this.data.keywords || ''}`;
        urlStr += `&search[order_status]=${order_status}`;
      }else if(this.data.orderType == "storeMang"){
        let mapStatus = ['', 'wait_pay', 'wait_send', 'wait_receive', 'completed'];
        urlStr += `&page=${this.data.page}`;
        urlStr += `&status=${mapStatus[index]}`;
        if(this.data.keywords!='' && _search_screen_type!=''){
          urlStr += `&search[search_type]=${this.data.searchTypes[_search_screen_type]}`;
          urlStr += `&search[keyword]=${this.data.keywords}`;
        }
      }else{
        urlStr += "&keyword=" + this.data.keywords;
      }
      urlStr += "&page=" + this.data.page;
      
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let myData = res.data;
            if (index == 0) {
              that.setData({
                orderList: that.data.orderList.concat(myData.data)
              });

            } else if (index == 1) {
              that.setData({
                waitPayList: that.data.waitPayList.concat(myData.data)
              });

            } else if (index == 2) {
              that.setData({
                waitSendList: that.data.waitSendList.concat(myData.data)
              });

            } else if (index == 3) {
              that.setData({
                waitReceiveList: that.data.waitReceiveList.concat(myData.data)
              });
            } else if (index == 4) {
              that.setData({
                waitCompleteList: that.data.waitCompleteList.concat(myData.data)
              });
            } else {
              that.setData({
                waitRefund: that.waitRefund.concat(myData.data)
              });
            }
          }

        },
        fail: function(res) {
          console.log(res);

        }
      });
    }
  },
  swichTabTItem(e) {
    let index = e.detail.index;
    this.setData({
      selected: index
    });
    this._initData();
    this._getOrderList(this.data.selected);
  },
  onPageScroll(event) {
    this.setData({
      scrollTop: event.scrollTop
    });
  },
  stopRefresh(e) {
    let bol = e.detail;
    this.setData({
      stopRefresh: bol
    });
  },
  //接收到合并多订单支付的通知方法
  multiplePayAction(e) {
    let order_ids = e.detail;
    this.setData({
      order_ids: order_ids
    });
    if (order_ids.length > 0) {
      this.setData({
        isMultiplePay: true
      });
    } else {
      this.setData({
        isMultiplePay: false
      });
    }
  },
  //待付款状态下-多订单合并支付,order_ids-订单id数组
  toMultiplePay() {
    //type-1订单支付，type-2订单合并支付
    wx.navigateTo({
      url: '/packageD/buy/orderPay/orderPay?order_id=' + this.data.order_ids.join(',') + '&status=2'
    });
  },
  //确认收货订单
  cofirmOrderAction(e) {
    let order = e.detail;
    if (this.data.selected == 0) {
      //全部订单列表
      this._getOrderList(this.data.selected);
    } else if (order == 'pay') {
      this._getOrderList(this.data.selected);
    } else {
      let waitReceiveList = this.data.waitReceiveList;
      for (let i = 0; i < waitReceiveList.length; i++) {
        if (order == waitReceiveList[i].id) {
          waitReceiveList.splice(i, 1);
        }
      }
      this.setData({
        waitReceiveList: waitReceiveList
      });

    }
  },
});
