// shoppingGuid/page/pages/userInfo/userInfo.js
const wxService = require('../../../../utils/wxService')
const utils = require('../../../../utils/util')

wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    memberId : null,
    navBar: [
      { name: '会员标签', type: 1, isActive: true }, 
      // { name: '手动标签', type: 2, isActive: false },
      { name: '订单信息', type: 3, isActive: false },
      { name: '退单信息', type: 4, isActive: false },
      { name: '优惠券', type: 5, isActive: false },
      { name: '积分', type: 6, isActive: false },
      { name: '经验值', type: 7, isActive: false },
    ],
    current: 1,
    onlineOrderStatus: [{ name: '线上订单', type: 1, isActive: true }, { name: '线下订单', type: 2, isActive: false }],
    returnOrderStatus: [{ name: '线上订单', type: 1, isActive: true },{ name: '线下订单', type: 2, isActive: false }],
    memberInfo: {},
    guider : {},
    memberTags : [],
    orderList : [],
    returnOrderList : [],
    coupons : [],
    pointHistory : [],
    expHistory : [],
    total : {
      totalConsume : 0, //累计消费
      totalPoint : 0,//当前积分
      totalExp : 0,//当前经验值
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let memberId = options.id ;
    this.data.memberId = memberId;
    this.getMemberFind(memberId);
    let currentUserInfo = wx.getStorageSync('_baseUserInfo');
    let userInfo = wx.getStorageSync('_userInfo');
    if (currentUserInfo.member){
      if (!currentUserInfo.member.name){
        currentUserInfo.member.name = userInfo.nickName;
      }
    }

    if (currentUserInfo){
      this.setData({
        guider: currentUserInfo,
      })
    }
    //获取会员下标签
    this.getMemberTags(memberId);
    //获取订单列表
    this.getUserOrderList(memberId);
    //获取线上退单
    this.getOnlineReturnOrderList(memberId);
    //获取优惠券列表
    this.getMemberCoupon(memberId);
    //获取会员积分
    this.getMemberPointHistory(memberId);
    //获取经验值流水
    this.getMemberExpHistory(memberId);
    //获取会员经验值
    this.getMemberExp(memberId);
    //获取会员积分
    this.getMemberPoint(memberId);
    //获取用户总消费额
    this.getMemberTotalConsumeAmount(memberId);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  //获取用户总消费额
  getMemberTotalConsumeAmount(memberId){

  },
  //获取优惠券信息
  getMemberCoupon(memberId){
    wxService.post(`/coupon/coupon/listWithMember?number=10000&size=1`, {
      memberId: memberId,
    }).then(res => {
      if (!res) return false;
      let list = res.data.data.content ? res.data.data.content : [];

      const canUse = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/coupon_bg.png',
        cantUse = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/coupon_bg_cantUse.png';
      list.forEach(item => {
        item.bg = item.status == 1 ? canUse : cantUse;
      });

      this.setData({
        coupons : list,
      })

    })
  },
  //获取积分
  getMemberPointHistory(memberId){
    wxService.post(`/member/memberPointLog/findPage?pageSize=10000&pageNo=1`,{
      memberId: memberId
    }).then(res => {
      if(!res) return ;
      let list = res.data.data.content ? res.data.data.content : [];
      this.setData({
        pointHistory: list
      })
    })
  },
  //获取会员当前积分
  getMemberPoint(memberId){
    wxService.get(`/member/memberPoint/getMemberPointInfo?memberId=${memberId}`).then(res => {
      if(!res) return ;
      let point = res.data.data ? res.data.data.point : 0;
      this.data.total.totalPoint = point;
      this.setData({
        total: this.data.total
      });
    });
  },
  //获取经验值流水
  getMemberExpHistory(memberId){
    wxService.post(`/member/exp/queryExpDetail?pageNum=1&pageSize=10000`,{
      memberId: memberId,
    }).then(res => {
      if(!res) return ;
      let list = res.data.data.content ? res.data.data.content : [];
      this.setData({
        expHistory : list
      });
    });
  },
  //获取会员经验值
  getMemberExp(memberId){
    wxService.post(`/member/exp/byMemberIdQueryExp?memberId=${memberId}`).then(res => {
      if(!res) return ;
      let obj = res.data.data;
      this.data.total.totalExp = obj.exp ? obj.exp : 0;
      this.setData({
        total: this.data.total
      })
    })
  },
  //获取会员详情
  getMemberFind(memberId) {
    wx.showLoading({
      title: '加载中'
    });

    wxService.post(`/member/find`, {
      memberId: memberId
    }).then(res => {
      if (!res) return false
      const { result, data } = res && res.data || res && res.result
      if (result == 0) {
        wx.hideLoading()
        data.member.age = utils.getAge(data.member.birthday)
        data.member.sex = data.member.sex ? data.member.sex : '保密';
        this.setData({
          memberInfo: data.member
        })
      }
    })
  },
  //获取会员下标签
  getMemberTags(memberId){
    wx.showLoading({
      title: '加载中'
    });
    wxService.get(`/marketing/memberTagBind/getByMemberId/${memberId}`).then(res => {
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        wx.hideLoading();
        this.data.memberTags = data ? data : [];
        this.setData({
          memberTags : this.data.memberTags
        });
      }
    }).finally(() => {})
  },
  //获取订单信息
  getUserOrderList(memberId){
    //获取线上订单
    wxService.post(`/sale/trade/buyer/history?pageSize=10000&pageNum=1`,{
      memberId : memberId,
    }).then(res => {
      if(!res) return ;
      let list = res.data.data ? res.data.data : [];

      let arr = list.map(item => {
        let statusText = item.status == 'N' ? '待支付' : (
          item.status == 'P' ? '待发货' : (
            item.status == 'D' ? '待收货' : (
              item.status == 'R' ? '已收货' : '已取消'
            )
          )
        );

        let products = item.skuVOList.map(p => {
          return {
            productName: p.productName,
            productId: p.productId,
            productCode: p.productCode,
            image: p.skuImgUrl ? p.skuImgUrl : 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/1571636466%281%29.jpg',
            skuId: p.skuId,
            skuCode: p.skuCode,
          }
        })
        return {
          orderNo: item.id,
          statusText: statusText,
          products: products,
          count: item.skuCount,
          payMoney: item.payAmount
        }
      });

      this.setData({
        orderList: arr,
      });
    })
  },
  //获取线下订单
  getOfflineOrder(memberId){
    wxService.post(`/sale/order/list?pageSize=10000&pageNo=1`, {
      memberId: memberId,
      storeId: [],
      consumeStartTime: '',
      consumeEndTime: ''
    }).then(res => {
      if (!res) return;
      let list = res.data.data.content ? res.data.data.content : [];
      let arr = list.map(item => {
        let statusText = '已完成';
        let products = item.productInfo.map(p => {
          return {
            productName: p.productName,
            productId: p.productId,
            productCode: p.productCode,
            image: 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/1571636466%281%29.jpg',
            skuId: p.skuId,
            skuCode: p.skuCode,
          }
        })
        return {
          orderNo: item.orderNo,
          statusText: statusText,
          products: products,
          count: item.productInfo.length,
          payMoney: parseFloat(item.realPayMoney/100).toFixed(2)
        }
      });

      this.setData({
        orderList: arr,
      });
    })
    
  },
  // 获取线上退单
  getOnlineReturnOrderList(memberId){
    wxService.post(`/sale/refund/buyer/history?pageSize=10000&pageNum=1`, {
      memberId: memberId,
    }).then(res => {
        if (!res) return;
        let list = res.data.data ? res.data.data : [];
        
        let arr = list.map(item => {
          let statusText = item.status == 'N' ? '待审核' : (
            item.status == 'A' ? '已审核' : (
              item.status == 'RJ' ? '已拒绝' : (
                item.status == 'R' ? '退货已发' : (
                  item.status == 'D' ? '已完成' : '已取消'
                ) 
              )
            )
          );
          let count = 0;
          let products = item.skuList.map(p => {
            count = count + p.count;
            return {
              image: p.skuImgUrl ? p.skuImgUrl : 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/1571636466%281%29.jpg',
              skuId: p.skuId,
            }
          })
          return {
            orderNo: item.id,
            statusText: statusText,
            products: products,
            count: count,
            payMoney: item.amount
          }
        });

        this.setData({
          returnOrderList: arr,
        });
    })

  },
  //获取线下退单
  getOfflineReturnOrderList(memberId){
    wxService.post(`/sale/orderReturn/findPage?pageSize=10000&pageNo=1`, {
      memberId: memberId,
    }).then(res => {
      if (!res) return;
      let list = res.data.data.content ? res.data.data.content : [];
      let arr = list.map(item => {
        let statusText = '已完成';
        let count = 0;
        let products = item.productInfo.map(p => {
          count = count + p.refundCount;
          return {
            productId: p.productId,
            productCode: p.productCode,
            image: 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/1571636466%281%29.jpg',
            skuId: p.skuId,
            skuCode: p.skuCode,
          }
        })

        return {
          orderNo: item.refundNo,
          statusText: statusText,
          products: products,
          count: count,
          payMoney: parseFloat(item.refundMoney / 100).toFixed(2)
        }
      });

      this.setData({
        returnOrderList: arr,
      });

    })
  },
  //打电话
  handelPhoneCall(e) {
    const {phone} = e.currentTarget.dataset;
    if(!phone){
      wx.showToast({
        title: '暂无手机号',
        icon : 'none'
      });
      return ;
    }
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  //点击事件
  //类型切换
  onTopBarTap(e){
    let index = e.currentTarget.dataset.index,
      item = e.currentTarget.dataset.item;
    this.data.navBar.forEach(nav => {
      nav.isActive = false;
    });

    this.data.navBar[index].isActive = true;
    this.data.current = this.data.navBar[index].type;

    this.setData({
      navBar: this.data.navBar,
      current: this.data.current
    });
  },
  //线上订单状态切换
  onTapChangeOnlineOrderStatus(e){
    let index = e.currentTarget.dataset.index,
      item = e.currentTarget.dataset.item;
    this.data.onlineOrderStatus.forEach(nav => {
      nav.isActive = false;
    });

    this.data.onlineOrderStatus[index].isActive = true;

    this.setData({
      onlineOrderStatus: this.data.onlineOrderStatus,
    });

    let type = this.data.onlineOrderStatus[index].type ;
    this.data.orderList = [];
    if(type == 1 ){ //线上订单
      this.getUserOrderList(this.data.memberId);
    }
    else{
      this.getOfflineOrder(this.data.memberId);
    }
  }, 
  //退单
  onTapChangeReturnOrderStatus(e){
    let index = e.currentTarget.dataset.index,
      item = e.currentTarget.dataset.item;
    this.data.returnOrderStatus.forEach(nav => {
      nav.isActive = false;
    });

    this.data.returnOrderStatus[index].isActive = true;

    this.setData({
      returnOrderStatus: this.data.returnOrderStatus,
    });

    let type = this.data.returnOrderStatus[index].type;
    this.data.returnOrderList = [];
    if (type == 1) { //线上订单
      this.getOnlineReturnOrderList(this.data.memberId);
    }
    else {
      this.getOfflineReturnOrderList(this.data.memberId);
    }

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

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

  }
})