// shoppingGuid/page/pages/welfare/welfare.js
const wxService = require('../../../../utils/wxService')
import { Integer } from '../../../../utils/integerDigitalConvertion'
var app = getApp()
wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    navBar : [
      { name: '导购学院', type: 1, isActive: true },
      { name: '推荐商品', type: 2, isActive: false },
      { name: '优惠券福利', type: 3, isActive: false},
    ],
    current : 1,
    guidCollege : {
      pageSize : 10,
      pageNum : 1,
      totalPage : 0,
      list : [],
      currentPage : 1,
      noData : false,
    },
    //推荐商品
    recommandProducts : [],
    recommandProductsNoData: false,
    //优惠券
    coupons : {
      pageSize: 10,
      pageNum: 1,
      totalPage: 0,
      list: [],
      currentPage: 1,
      noData : false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //首次进来先加载导购学院的列表
    this.getGuidCollegeList();
  },

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

  },

  //点击事件
  //分类点击
  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;
    // tab 切换时 如果发现对应的列表没有加载过，则去加载
    if (this.data.current == 1){
      if (this.data.guidCollege.list.length == 0){
        this.getGuidCollegeList();
      }
    }
    else if (this.data.current == 2){
      if (this.data.recommandProducts.length == 0) {
        this.getRecommandProductList();
      }
    }
    else if(this.data.current == 3){
      if(this.data.coupons.list.length == 0){
        this.getCouponActivityList();
      }
    }

    this.setData({
      navBar: this.data.navBar,
      current: this.data.current
    });
  },
  //跳转导购学院详情
  onTapToGuidCollegeInfo(e){
    let item = e.currentTarget.dataset.item;
    let id = item.id;
    wx.navigateTo({
      url: '/shoppingGuid/page/pages/guidCollegeInfo/guidCollegeInfo?id=' + id,
    });
  },
  //定向发送优惠券
  onTapToSendConpon(e){
    let item = e.currentTarget.dataset.item;
    let id = item.id;
    let content = {
      title: item.couponName,
      id: item.couponId,
      url: item.imageBg
    }

    let tentacleInfo = {
      content: JSON.stringify(content),
      contentId: item.couponId,
      contentType: app.globalData.contants.SHARE_TYPE.PRODUCT_DETAIL, //内容类型 STAFF_RECOMMAND
      title: item.couponName, //标题
      type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
    }

    wxService.getTentacleContent(tentacleInfo).then(res => {
      if (res && res.id) {
        let tentacleId = res.id;
        let inner_id = Integer.digit(item.couponId, 10, 64);
        let inner_tentacleId = Integer.digit(tentacleId, 10, 64);
        var path = 'subPackage/page/pages/scanCoupon/scanCoupon' + '?i=' + inner_id + '&t=' + inner_tentacleId;
        //打开企业微信通讯录选择会员
        wx.qy.shareToExternalContact({
          appid: app.globalData.appId,//小程序的appid
          title: item.couponName, //小程序消息的title
          imgUrl: item.imageBg,//小程序消息的封面图
          page: path, //小程序消息打开后的路径
          success: function (r) {
            wx.showToast({
              title: '发送成功!'
            });
          },
          fail: function (err) {
            console.log('error---------------', err);
          }
        });
      }
    });
  },

  //立即推荐商品给用户
  onTapToRecommandProduct(e){
    let item = e.currentTarget.dataset.item;
    // 生成触点对象
    let content = {
      title: item.productName,
      id: item.productId,
      url: item.productImgUrl
    }
    let tentacleInfo = {
      content: JSON.stringify(content),
      contentId: item.productId,
      contentType: app.globalData.contants.SHARE_TYPE.PRODUCT_DETAIL, //内容类型 
      title: item.productName, //标题
      type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
    }

    wxService.getTentacleContent(tentacleInfo).then(res => {
      if (res && res.id) {
        let tentacleId = res.id;
        let inner_id = Integer.digit(item.productId, 10, 64);
        let inner_tentacleId = Integer.digit(tentacleId, 10, 64);
        var path = 'pages/productDetail/productDetail' + '?i=' + inner_id + '&t=' + inner_tentacleId;
        // let path = 'pages/productDetail/productDetail';
        console.log('推荐商品path-----', path)
        //打开企业微信通讯录选择会员
        wx.qy.shareToExternalContact({
          appid: app.globalData.appId,//小程序的appid
          title: item.productName, //小程序消息的title
          imgUrl: item.productImgUrl,//小程序消息的封面图
          page: path, //小程序消息打开后的路径
          success: function (res) {
            //todo:
            wx.showToast({
              title: '推荐成功！'
            });
          },
          fail: function (err) {
            console.log('error---------------', err);
          }
        });
      }
    });

    // 先不管触点 测试调用企业微信接口
    // let inner_id = Integer.digit(item.productId, 10, 64);
    // var path = 'pages/productDetail/productDetail' + '?i=' + inner_id;
    // wx.qy.shareToExternalContact({
    //   appid: app.globalData.appId,//小程序的appid
    //   title: item.productName, //小程序消息的title
    //   imgUrl: item.productImgUrl,//小程序消息的封面图
    //   page: path, //小程序消息打开后的路径
    //   success: function (res) {
    //     //todo:
    //     wx.showToast({
    //       title: '推荐成功！'
    //     });
    //   },
    //   fail: function (err) {
    //     console.log('error---------------', err);
    //   }
    // });


  },
  //去商城
  onTapToMall(){
    wx.redirectTo({
      url: '/pages/userCenter/userCenter',
    })
  },
  //获取导购学院列表
  getGuidCollegeList(){
    wx.showLoading({
      title: '加载中',
      mask: true
    })
      wxService.post(
        `/merchant/guideCollege/getPageInfoList?pageSize=${this.data.guidCollege.pageSize}&pageNum=${this.data.guidCollege.pageNum}`,
        {
          title : ''
        }
      ).then(res => {
      if (res) {
        wx.hideLoading();
        const { result, data } = res.data
        if (result == 0) {
          this.data.guidCollege.list = this.data.guidCollege.list.concat(data.content);
          this.data.guidCollege.totalPage = data.totalPages;
          if (this.data.guidCollege.list.length == 0) {
            this.data.guidCollege.noData = true;
          }

          this.setData({
            guidCollege: this.data.guidCollege
          });
        }
      }
    })
  },
  //获取推荐商品列表
  getRecommandProductList(){
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    
    wxService.post(`/merchant/share/productBonus/buyer/findPage?pageNo=1&pageSize=20`, {}).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          let list = data.content;
          list.forEach(item => {
            item.productImgUrl = item.productImgUrl ? 
            item.productImgUrl : 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/1571636466%281%29.jpg';
          });

          if(list.length == 0){
            this.data.recommandProductsNoData = true;
          }

          this.setData({
            recommandProducts: list,
            recommandProductsNoData: this.data.recommandProductsNoData
          })
        }
      }
    })
  },
  //获取优惠券券活动
  getCouponActivityList(){
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let pageNum = this.data.coupons.pageNum,
      pageSize = this.data.coupons.pageSize;
    wxService.post(`/marketing/shoppingguide/coupon/page4c?pageSize=${pageSize}&pageNo=${pageNum}`,
      {couponName: ''}
    ).then(res => {
      if (res) {
        //https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/coupon_bg.png 正常
        //https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/coupon_bg_cantUse.png //不可使用
        const { result, data } = res.data
        wx.hideLoading();
        if (result == 0) {
          let list = data.content ? data.content : [];
          list.forEach(item => {
            item.canUse = (item.couponSetting.status == 0 || item.couponSetting.status == 2) ? false : true;
            item.imageBg = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/coupon_bg.png';
            item.typeText = item.couponSetting.typeDesc;
            item.price = parseFloat(item.couponSetting.faceAmount / 100).toFixed(2);
            item.couponType = item.couponSetting.type;
          });

          this.data.coupons.list = this.data.coupons.list.concat(list);
          if(this.data.coupons.list.length == 0){
            this.data.coupons.noData = true;
          }
          this.setData({
            coupons: this.data.coupons
          });
        }
      }
    })
  },
  //展示优惠券二维码
  onTapShowQrcode(e){
    let item = e.currentTarget.dataset.item;
    wx.setStorageSync('_guidCouponInfo', item);
    wx.navigateTo({
      url: '/shoppingGuid/page/pages/couponQrcode/couponQrcode',
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('pull done')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.current == 1){ // 导购学院
      if (this.data.guidCollege.totalPage > this.data.guidCollege.pageNum){
        this.data.guidCollege.pageNum = this.data.guidCollege.pageNum + 1;
        this.getGuidCollegeList();
      }
      else{
        // wx.showToast({
        //   title: '没有更多数据啦~',
        //   icon : 'none'
        // });
      }
    }
    else if (this.data.current == 2){ //推荐商品

    }
    else if (this.data.current == 3){ //优惠券福利

    }
  },

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

  }
})