// 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 logger = utils.logger

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    pages:[],
    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
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad () {
    // 设置 导航栏背景颜色
    // wxService.getNavBarBackGroundColor('#000000', '#ff0000')
    this.setData(
      {
        pages: [],
        groupLoadState: 'complete', // 活动分组加载标志
        homeApiLoading: true,
        render: null, // 渲染页面数据对象(安全渲染)
        isLastPage: false, // 页面段落加载完成
        renderPageOver: false, // 渲染页面结束
        // isAuthorization: true,
        outoHeigth: 500,
      },
      () => {
        // this.loadMore()
      }
    )
    handlerDataOnPage = new utils.HandlerDataOnPage()
    renderPage = require('../../utils/renderPage').getRenderPage()
    handlerDataOnPage.init(this, 'pages')
    this.initPage(this.data.pageId)
  },
  /** 
   * 监听子组件事件
   * */ 
  updatePage(ev) {
    const {pageId} = ev.detail
    // this.setData({
    //   pages: [],
    //   pageId
    // },()=>{
    //   this.initPage(pageId)
    // })
    wxService.router(`/subPackage/page/pages/subPage/subPage`).search({pageId})
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    // 取会员卡号
    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
    //   })
    // }
    // 获取手机信息
    wxService.getSystemInfo().then(res=> {
      this.setData({
        outoHeigth: res.windowHeight
      })
    })
    // 设置当前选中 Tab 
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
  },

  // page 信息
  initPage(pageId){
    this.setData({
      products: []
    })
    wx.showLoading({
      title: '加载中'
    })
    // wxService.post(`/merchant/modelPage/getDetailById?pageId=${pageId}&brandId=${app.globalData.brandId}`).then(res => {
    wxService.post(`/merchant/modelPage/mainSetting?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
        })
        // tabBar
        const currentTabBar = data.paragraphs.filter(item=> item.type == 5)
        
        let currentTabBarArr =[]
        currentTabBar.forEach(tab=> {
          currentTabBarArr = tab.tabBar.images
          console.log('---',  currentTabBarArr)
          currentTabBarArr.forEach(item=> {
            if(item.link){
              console.log('-link--',item.link.type, item.link.url)
            } else if(item.row){
              console.log('-row--')
            }
          })
        })
        // 段落
        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 })
      }

    }).finally(() => {
      wx.hideLoading();
    })
  },
  /**
	 * 渲染数据(合并之前的数据)
	 * @param products 数组数据
	 * @param isLastPage
	 * @param now
	 */
  renderPageFunc ({ products }) {
    let productData = handlerDataOnPage.handlerArray(products)
    logger.log('productData.keysNum', productData.keysNum(), productData)
    
      this.setData({
        ...productData
      },()=>{
        wx.hideLoading()
      })
 
  },

  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    let tentacleInfo = {
      content: this.route,
      title: this.route,
      contentType: 3,
      type: 3// 1:门店,2:员工(暂时不做),3:会员,4:第三方外部渠道,5:智能营销
    };
    wxService.getTentacleContent(tentacleInfo).then(res => {
      if (res && res.tentacleId) {
        let tentacleId = Integer.digit(res.tentacleId, 10, 64);
        var path = `pages/userCenter/userCenter?t=${tentacleId}`;
        console.log(path)
        return {
          path: path
        }
      }
    });
  }
})