// pages/userCenter.js
const app = getApp()
const wxService = require('../../utils/wxService')
const utils = require('../../utils/util')
const envInfo = require('../../config/index').envInfo
let renderPage = null // 渲染页面数据对象(安全渲染)
let handlerDataOnPage = null
let config = require('../../configScreen/configScreen');
import { Integer } from '../../utils/integerDigitalConvertion'
const { memberId, member } = wx.getStorageSync('_baseUserInfo')
const logger = utils.logger

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    pages: [],
    paddingBottom :'0',
    render: null, // 渲染页面数据对象(安全渲染)
    renderPageOver: false, // 渲染页面结束
    integralNum: 0,
    couponNum: 0,
    // isAllScreen: fullSucreen.isAllScreen
    isAllScreen: config.isAllScreen,
    token: '',
    isAuthorization: false,
    pageId: 3,
    baseUserInfo: null,
    // cardMember: null,
    pageBackgroundColor: 0,
    guidePageModalShow: false,
    shareBenefitModalShow: false,
    currHomePageId: '',
    skuVOList: [],
    benefitData: '',
    isQiye: false,
    x : 0,
    y : 0,
    contactUsModal : false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initPage();
  
    // this.setData({
    //   x: utils.configSliderBlock(app).x,
    //   y: utils.configSliderBlock(app).y,
    // })

    // 判断环境是不是企业微信
    let env = wx.getStorageSync('_qyWeChat');
    this.setData({
      isQiye: env ? true : false
    });

    let memberId = options.memberId;
    if (memberId) {
      let tentacleInfo = {
        content: '首页',
        title: '首页',
        tentacleId: memberId,
        contentType: app.globalData.contants.SHARE_TYPE.HOME,
        type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
      };

      this.generatePointObject(tentacleInfo);
    }
    // 邀请奖励弹框
    if (options && options['scene']) {
      let idParam = decodeURIComponent(options['scene']).split('&')[0]
      let TYPE = idParam && idParam.split('=')[1] || 0
      if (TYPE == '-1'){
        this.setData({
          shareBenefitModalShow: true
        })
        this.getShareImg()
      }
    }

  },
  startmessage(e){
    console.log('联系我插件信息startmessage----', e)
  },
  completemessage(e){
    let ret = e.detail;
    console.log('联系我插件信息completemessage----',ret)
    if (ret.errcode == -3002 || ret.errcode == -3004 || ret.errcode == -3005) {
      wx.showToast({
        title: '联系失败，请联系管理员',
        icon : 'none'
      });
    }
    else if (ret.errcode == -3008){
      wx.showToast({
        title: '暂无客服人员',
        icon: 'none'
      });
    }
    else{
      this.setData({
        contactUsModal : true,
      });
    }
  },
  // 获取邀请奖励图片
  getShareImg() {
    wxService.get(`/member/share/inviteFriends/buyer/getValid`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            benefitData: data
          })
        }
      }
    })
  },
  /** 
   * 监听子组件事件
   * */
  updatePage(ev) {
    const { pageId } = ev.detail
    // this.setData({
    //   pages: [],
    //   pageId
    // },()=>{
    //   this.initPage(pageId)
    // })
    wxService.router(`/subPackage/page/pages/subPage/subPage`).search({ pageId })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    let tentacleInfo = wx.getStorageSync('TENTACLE_CONTENT');

    // 取会员卡号
    const baseUserInfo = wx.getStorageSync('_baseUserInfo')
    const cardMember = wx.getStorageSync('_cardMember')
    // 登录接口返回err
    const reLoginErrFlag = wx.getStorageSync('reLoginErr')
    if (baseUserInfo && !reLoginErrFlag) {
      this.setData({
        token: wx.getStorageSync('token'),
        baseUserInfo,
        cardMember,
        isAuthorization: false
      }, () => {
        // 积分数量
        this.getMemberPointInfo()
        // 优惠券数量
        this.getMemberCouponInfo()
      })
    }
    else if (!baseUserInfo && reLoginErrFlag) {
      this.setData({
        isAuthorization: true
      })
    }
    else {
      this.setData({
        isAuthorization: true
      })
    }
    // if (baseUserInfo){
    //   this.setData({
    //     token: wx.getStorageSync('token'),
    //     baseUserInfo,
    //     // cardMember,
    //     isAuthorization: false
    //   })

    //   // 积分数量
    //   this.getMemberPointInfo()
    //   // 优惠券数量
    //   this.getMemberCouponInfo()
    // } else {
    //   this.setData({
    //     isAuthorization: true
    //   })
    // }
    // 获取plus购买信息
    // this.getPlusPurchase()
    // 获取手机信息
    wxService.getSystemInfo().then(res => {
      this.setData({
        outoHeigth: res.windowHeight
      })
    })
    // 设置当前选中 Tab 
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
  },
  
  // 查询积分信息
  getMemberPointInfo() {
    wx.showLoading({
      title: '加载中'
    })
    wxService.get(`/member/memberPoint/getMyPointInfo`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            integralNum: data && data.point || 0
          })
        }
      }
    })
  },
  // 查询优惠券数量
  getMemberCouponInfo() {
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/coupon/coupon/memberCouponCount`).then(res => {
      if (res) {
        const { result, data } = res && res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            couponNum: data && data[1] || 0
          })
        }
      }
    })
  },
  // page 信息
  initPage() {
    this.setData({
      pages: [],
      products: [],
      groupLoadState: 'complete', // 活动分组加载标志
      homeApiLoading: true,
      render: null, // 渲染页面数据对象(安全渲染)
      isLastPage: false, // 页面段落加载完成
      renderPageOver: false, // 渲染页面结束
      // isAuthorization: true,
      outoHeigth: 500,
    })
    handlerDataOnPage = new utils.HandlerDataOnPage()
    renderPage = require('../../utils/renderPage').getRenderPage()
    handlerDataOnPage.init(this, 'pages')
    this.initHomePage()

  },
  initHomePage() {
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/merchant/modelPage/mainSetting/mall?brandId=${app.globalData.brandId}`).then(res => {
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        this.setData({
          pageBackgroundColor: data.page.backgroundColor || 0
        })
        // 动态设置title
        wx.setNavigationBarTitle({
          title: data.page.title
        })
        // 首页 pageId
        // data.page.pageId
        this.setData({
          currHomePageId: data.page.pageId
        })
        
        // 段落
        const products = data.paragraphs
        const filterResult = products.map((res, index) => {
          return {
            ...res, index
          }
        }).filter(item => {
          // wx.hideLoading()
        })

        const render = renderPage.initPaging(filterResult).initRenderData(products)
        this.data.render = render
        const renderData = render.next()
        this.data.renderPageOver = renderData.done
        this.renderPageFunc({ products: renderData.value })
        // this.renderPageFunc({ products: products })
        //是否有tabbar 或 plus
        let tabbar = products.filter(item => item.type == 5);
        let plus = products.filter(item => item.type == 9);

        if(plus.length != 0){
            this.setData({
              paddingBottom : '320rpx'
            })
        }
        else if (tabbar.length != 0){
          this.setData({
            paddingBottom: '140rpx'
          })
        }
        else{
          this.setData({
            paddingBottom: '40rpx'
          })
        }
      }
    }).finally(() => {
      wx.hideLoading();
    })
  },
  /**
	 * 渲染数据(合并之前的数据)
	 * @param products 数组数据
	 * @param isLastPage
	 * @param now
	 */
  renderPageFunc({ products }) {
    this.data.pages = [];
    // 9 plus(9/5-权重高)
    let newProducts = [...products]
    let typeArr = []
    newProducts.map(item => typeArr.push(item.type))
    if (typeArr.includes(9) && typeArr.includes(5)) {
      newProducts.forEach((item, index) => {
        if (item.type == 5) { newProducts.splice(index, 1) }
      })
    }

    let productData = handlerDataOnPage.handlerArray(newProducts)
    this.setData({
      ...productData
    }, () => {
      wx.hideLoading()
    })
  },

  // 获取plus购买信息
  // getPlusPurchase() {
  //   wxService.get(`/sale/premium/query`).then(res => {
  //     if(!res) return false
  //     const { result, data } = res.data
  //     if (result == 0) {
  //       this.setData({
  //         skuVOList: data
  //       })
  //     }
  //   }).finally(() => {
  //   })
  // },
  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    //修改为参数memberId
    const { memberId, member } = wx.getStorageSync('_baseUserInfo')
    var path = `pages/userCenter/userCenter`;
    console.log('首页memberId------', memberId)
    if (memberId) {
      let m = Integer.digit(memberId, 10, 64);
      path = `pages/userCenter/userCenter?m=${m}`;
    }
    return {
      title:'舞象星品荟-社交商城',
      path: path
    }
  }
})