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

const discountBg = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/7_3_0/icon_dicount_coupon.png';
const dingeBg = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/7_3_0/icon_dinge_coupon.png';
const diyongBg = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/7_3_0/icon_diyong_coupon.png';

const defaultGoodsImg = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/product_defalut.jpg';

wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    navBar: [{ name: '招募榜', type: 1, isActive: true }, { name: '门店榜单', type: 2, isActive: false }],
    current : 1,
    staff : [],
    store : [],
    rankList:[],
    storeList:[],
    defaultAvatar: 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/home_default_logo.png',
    loadingText : '数据加载中...',
    coupon : {
      couponTypeArr: [
        { name: '打折券', type: 2, active: true }, 
        { name: '定额券', type: 3, active: false }, 
        { name: '抵用券', type: 1, active: false }
      ],
      currentCouponType : 2,
      couponList : []
    },
    goods : {
      goodsTypeArr: [
        { name: '最新', type: 'new', active: true },
        { name: '最热🔥', type: 'hot', active: false },
        { name: '推荐👍', type: 'recommend', active: false }
      ],
      currentGoodsType: 'new',
      goodsList: []
    },
    shareModel : {
      title : '',
      path : '',
      imageUrl : ''
    },
    showModal : false
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('guidBaseInfo----', wx.getStorageSync('guidBaseInfo'))
    this.getCouponList();
    this.getGoodsList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getRecruitRanking()  // 招募榜
  },
  //打开摄像头 扫码
  onTapScanQrcode(){
    wx.scanCode({
      success : res => {
        let result = res.result;
        wx.navigateTo({
          url: '/shoppingGuid/page/pages/couponWriteOff/couponWriteOff?id=' + result,
        });
      },
      fail : err => {
        console.log('扫码失败结果是--',err)
      },
    });
  },
  //获取排行榜
  getRecruitRanking() {
    wx.showLoading({
      title: '加载中'
    });

    wxService.post('/marketing/shoppingguide/recruitRanking').then(res => {
      if (res) {
        const { result, data } = res.data;
        if (result == 0) {
          wx.hideLoading()
          let list = data ? data : [];
          if(list.length == 0){
            this.data.loadingText = '暂无榜单信息~';
          }

          list.map(item => {
            item.member.qiyeInfo = item.member.qiyeInfo ? item.member.qiyeInfo : null;
            if (!item.member.qiyeInfo){
              item.member.qiyeInfo = {
                name : '暂无名称'
              }
            }
          });

          this.setData({
            rankList: list,
            loadingText : this.data.loadingText
          });
        }
      }
    });
  },
  // 门店榜
  getStoreRanking() {
    wx.showLoading({title: '加载中'});
    this.setData({loadingText : '数据加载中...'});
    wxService.post('/marketing/shoppingguide/storeRanking').then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading();
          if (!data){
            this.data.loadingText = '暂无榜单信息~';
          }
          
          this.setData({
            storeList: data || [],
            loadingText : this.data.loadingText
          })
        }
        
      }
    });
  },
  // 点击事件
  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
    },()=>{
      const { current } = this.data
      current == 1? this.getRecruitRanking() : this.getStoreRanking()
    });
  },
  //跳转到任务中心
  onTapToTaskCenter(){
    wx.navigateTo({
      url: '/shoppingGuid/page/pages/kpi/kpi',
    })
  },
  //跳转到优惠券列表
  onTapToCouponList(){
    wx.navigateTo({
      url: '/shoppingGuid/page/pages/moreCoupons/moreCoupons?type=' + this.data.coupon.currentCouponType,
    });
  },
  //优惠券tab点击
  onTapChangeCouponType(e){
    let index = e.currentTarget.dataset.index;
    this.data.coupon.couponTypeArr.map(item => {
      item.active = false;
    });

    this.data.coupon.couponTypeArr[index].active = true;
    this.data.coupon.currentCouponType = this.data.coupon.couponTypeArr[index].type;
    this.data.coupon.couponList = [];

    this.getCouponList();
    this.setData({
      coupon: this.data.coupon
    });

  },
  //获取优惠券列表
  getCouponList(){
    wx.showLoading({
      title: '加载中..',
    });
    let type = this.data.coupon.currentCouponType;
    wxService.post(`/marketing/shoppingguide/coupon/page4c?pageSize=3&pageNo=1`,{
      couponName : '',
      type: type,
    }).then(res => {
      if(res){
        let list = res.data.data.content ? res.data.data.content : [];
        list.forEach(item => {
          item.couponType = item.couponSetting.type;
          item.couponBg = item.couponType == 1 ? diyongBg : (item.couponType == 2 ? discountBg : dingeBg);   
        });

        this.data.coupon.couponList = list;
        this.setData({
          coupon: this.data.coupon,
        });
      }
    });
  },
  //展示优惠券二维码
  onTapShowQrcode(e) {
    let item = e.currentTarget.dataset.item;
    wx.setStorageSync('_guidCouponInfo', item);
    wx.navigateTo({
      url: '/shoppingGuid/page/pages/couponQrcode/couponQrcode',
    });
  },
  //定向发送优惠券
  onTapToSendConpon(e) {
    let item = e.currentTarget.dataset.item;
    let id = item.id;
    let content = {
      title: item.title,
      id: id,
      url: 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/icon_get_coupon.png'
    }
    let tentacleInfo = {
      content: JSON.stringify(content),
      contentId: item.id,
      contentType: app.globalData.contants.SHARE_TYPE.PRODUCT_DETAIL, //内容类型 STAFF_RECOMMAND
      title: item.title, //标题
      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.id, 10, 64);
        let inner_tentacleId = Integer.digit(tentacleId, 10, 64);
        var path = 'subPackage/page/pages/scanCoupon/scanCoupon' + '?i=' + inner_id + '&t=' + inner_tentacleId;
        this.data.shareModel.title = item.title;
        this.data.shareModel.imageUrl = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/icon_get_coupon.png';
        this.data.shareModel.path = path;
        this.setData({
          shareModel: this.data.shareModel,
          showModal: true
        });
      }
    });
  },
  //关闭模态框
  onTapCancelShare() {
    this.setData({
      showModal: false
    });
  },
  //群发
  onTapToSendByGroup(e) {
    let item = e.currentTarget.dataset.item;
    let id = item.id;
    let content = {
      title: item.title,
      id: item.id,
      url: 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/icon_get_coupon.png'
    }

    let tentacleInfo = {
      content: JSON.stringify(content),
      contentId: item.id,
      contentType: app.globalData.contants.SHARE_TYPE.PRODUCT_DETAIL, //内容类型 STAFF_RECOMMAND
      title: item.title, //标题
      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: 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/icon_get_coupon.png',//小程序消息的封面图
          page: path, //小程序消息打开后的路径
          success: function (r) {
            wx.showToast({
              title: '发送成功!'
            });
          },
          fail: function (err) {
          }
        });
      }
    });
  },

  //跳转到更多商品列表
  onTapToMoreProducts(){
    wx.navigateTo({
      url: '/shoppingGuid/page/pages/moreProducts/moreProducts?type=' + this.data.goods.currentGoodsType,
    });
  },

  //切换商品筛选
  onTapChangeGoodsType(e){
    let index = e.currentTarget.dataset.index;
    this.data.goods.goodsTypeArr.map(item => {
      item.active = false;
    });

    this.data.goods.goodsTypeArr[index].active = true;
    this.data.goods.currentGoodsType = this.data.goods.goodsTypeArr[index].type;
    this.data.goods.goodsList = [];
    this.getGoodsList();
    this.setData({
      goods: this.data.goods
    });
  },
  //获取商品列表
  getGoodsList(){
    wx.showLoading({
      title: '加载中..',
    });
    let order = this.data.goods.currentGoodsType;
    wxService.post(`/merchant/share/productBonus/buyer/findPageOrder?pageNo=1&pageSize=3&order=${order}`, {}).then(res => {
      if(res){
        let list = res.data.data.content ? res.data.data.content : [];
        list.map(item => {
          item.productImgUrl = item.productImgUrl ? item.productImgUrl  : defaultGoodsImg;
        });
        this.data.goods.goodsList = list;
        this.setData({
          goods: this.data.goods
        });
      }
    });
  },

  //定向发送
  //定向转发商品给用户 分享功能
  onTapToShare(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;
        this.data.shareModel.title = item.productName;
        this.data.shareModel.imageUrl = item.productImgUrl;
        this.data.shareModel.path = path;

        this.setData({
          shareModel: this.data.shareModel,
          showModal: true,
        });
      }
    });
  },

  //立即群发商品给用户
  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;
        //打开企业微信通讯录选择会员
        wx.qy.shareToExternalContact({
          appid: app.globalData.appId,//小程序的appid
          title: item.productName, //小程序消息的title
          imgUrl: item.productImgUrl,//小程序消息的封面图
          page: path, //小程序消息打开后的路径
          success: function (res) {
            wx.showToast({
              title: '推荐成功！'
            });
          },
          fail: function (err) {
            console.log('error---------------', err);
          }
        });
      }
    });

  },

  // 回到商城
  onTapToMall(){
    wx.navigateTo({
      url: '/pages/userCenter/userCenter',
    });
  },
  //跳转到会员
  onTapToMember(){
    wx.navigateTo({
      url: '/shoppingGuid/page/pages/myMemberList/myMemberList',
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res)
    console.log(this.data.shareModel)
    if (res.from == 'button') {
      return {
        title: this.data.shareModel.title,
        path: this.data.shareModel.path,
        imageUrl: this.data.shareModel.imageUrl
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCouponList();
    this.getGoodsList();
    if (this.data.current == 1){
      this.getRecruitRanking();
    }
    else if(this.data.current == 2){
      this.getStoreRanking();
    }

    setTimeout(() => {
      wx.stopPullDownRefresh();
    },3000);
    
  },

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

  },
})