import {
  get,
  post
} from '../../utils/http'
import {
  formatActivity
} from '../../utils/time'
import {
  throttle,
  debounce,
  trackUserEvent
} from '../../utils/util'
var WxParse = require('../../components/local/wxParse/wxParse.js')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  jsData: {
    columnsHeight: [0, 0],
    isListLoading: false
  },
  data: {
    list: [],
    page: 1,
    total: 0,
    coupon: null,
    homeData: null,
    visible: false,
    posterPopup: false,
    isLoading: true,
    btmToast: true,
    activity: {},
    needReqActivity: true,
    topBannerCurrentSwiper: 0, // 顶部轮播图当前滑动位置
    cardBannerCurrentSwiper: 0, // 开卡轮播图当前滑动位置
    navBarData: app.globalData.navBarData,
    navBarBgClass: '',
    currentNewAcount: 0,
    guildMessage: false, // 顶部导航栏背景
    allow_invite: 0, //是否展示邀请入口,1是,0否
    allow_receive: 0, //是否展示再次领取奖励入口,1是,0否
    newAcountImage: ['https://we-spa.oss-cn-shenzhen.aliyuncs.com/wxapp/20220609/newAcount.png', 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/wxapp/20220609/vFace.png', 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/wxapp/20220609/showLike.png'],
    inviteImg: 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/wxapp/20220811/%E4%BA%8C%E5%9B%BE/%E5%9B%BE%E7%89%87/%E9%82%80%E8%AF%B7%E8%80%85banner%402x.png', //邀请
    beInvitedImg: 'https://we-spa.oss-cn-shenzhen.aliyuncs.com/wxapp/20220811/%E4%BA%8C%E5%9B%BE/%E5%9B%BE%E7%89%87/%E7%BC%96%E7%BB%84%2010%402x.png', //被邀请
    matching: false,
    PopShow: true, //十月一弹窗显示
    swiperIndex: 0, //推荐项目轮播图下标
    classify: [], //美丽秘籍分类
    current: 0, //美丽秘籍下标
    value: '',
    columns: [
      [],
      []
    ],
    tempPics: [], //美丽秘籍内容列表
    tabClass: '', //美丽秘籍滑到顶部类名
    messageList: [], //消息列表
    notMessageTotal: 0, //未读消息数量
    skinInfo: "", //测服详情概要
    skin_type: ['干性肌肤', '中性肌肤', '油性肌肤', '混合型肌肤', '敏感肌肤', '痤疮肌肤'], //肤质:1-干性肌肤 2-中性肌肤 3-油性肌肤 4-混合型肌肤,5敏感肌肤,6 痤疮肌肤
    isTips: true, //距离提示
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取美丽秘籍分类
    // this.getClassify()
    console.log(options, 'options');
    if (options.fromAuthOrder && JSON.parse(options.fromAuthOrder)) {
      // 弹出订单确认等待loading层,用户也可主动关闭loading层
      this.setData({
        matching: true
      })
    }
    if (wx.getStorageSync('userInfo')) {
      // 调方法实时收取服务端推送过来的订单确认消息
      this.createSocketToReceiveMessage()
    }
    this.getInviteStatus()
    this.setData({
      visible: app.globalData.couponPopup,
      coupon: app.globalData.coupon,
      navBarHeight: app.globalData.navBarData.navBarHeight
    })
    this.getHomeData()
    this.check_new_record()
    if (wx.getStorageSync('day') != new Date().getDate()) {
      this.setData({
        posterPopup: true
      })
    }
    this.activityProgress()
    this.activityRules()
    wx.setStorageSync('day', new Date().getDate())
    if (options.click) {
      trackUserEvent(options.click)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    if (wx.getStorageSync('token') && this.data.needReqActivity) {
      this.getUserActivity()
    }
    this.getVersion()
    // 当切换了店铺时,重新请求一次数据
    let storeData = getApp().globalData.storeData
    let storeId = storeData.id || wx.getStorageSync('store_id')
    if (this.data.homeData && storeId != this.data.homeData.store.id && this.data.homeData.store.id) {
      this.getStoreInfo(storeId)
    }
    if (wx.getStorageSync('userInfo')) {
      // 获取消息列表
      this.getMessageList()
      // 获取未读消息数量
      this.getNotMessageTotal()
    }
    // 获取测服详情概要
    this.getSkinInfo()
  },
  //获取当前用户邀请状态
  getInviteStatus() {
    get('/api/user/power', {}, res => {
      this.setData({
        allow_invite: res.data.allow_invite,
        allow_receive: res.data.allow_receive,
        invite_id: res.data.invite_id
      })
    })
  },
  onInvite() {
    if (this.data.allow_receive != 1 && this.data.allow_invite != 1) {
      wx.showToast({
        title: '您还没有体验过项目,不满足参与活动条件',
        icon: "none"
      })
      return
    }
    wx.navigateTo({
      url: this.data.allow_invite == 1 ? '/pages/invitationDetails/invitationDetails' : `/pages/invitees/invitees?invite_id=${this.data.invite_id}`,
    })
  },

  createSocketToReceiveMessage() {
    if (!wx.getStorageSync('token')) {
      return
    }

    let token = wx.getStorageSync('token')
    let timer = null
    console.log('开始连接...')
    wx.connectSocket({
      url: `wss://ws.ijolijoli.com?access_token=${token}`,
      header: {
        'content-type': 'application/json'
      },
      method: "GET",
      success: (res) => {
        console.log('连接成功', res)
      },
      fail: (err) => {
        console.log('连接失败', err)
      },
      complete: (e) => {
        console.log('连接完成', e)
      }
    })
    wx.onSocketOpen((e) => {
      //当WebSocket创建成功时,触发onSocketOpen事件
      console.log("连接已打开", e);
      timer = setInterval(() => {
        wx.sendSocketMessage({
          data: JSON.stringify({
            type: 'ping'
          })
        });
      }, 30000);
    })
    wx.onSocketMessage((e) => {
      //当客户端收到服务端发来的消息时,触发onSocketMessage事件,参数e.data包含server传递过来的数据
      // console.log('收到服务端消息', e.data)
      let data = JSON.parse(e.data);
      // console.log(data)
      // 收到服务端订单添加消息后,若订单确认loading层未关闭,则直接跳转订单确认页;否则,对服务端推送消息不做任何逻辑处理
      if (this.data.matching && data.data.type === 'order_add') {
        // console.log('关闭loading层并跳转订单确认')
        this.orderConfirmOnclose()
        wx.redirectTo({
          url: '/pages/confirmProjectOrder/confirmProjectOrder?id=' + data.data.order_id,
        })
      }
      // 收到消息通知
      if (data.data.type === 'instation') {
        // 重新获取消息列表
        this.getMessageList()
        // 重新获取未读数量
        this.getNotMessageTotal()
      }
    })
    wx.onSocketClose((e) => {
      //当客户端收到服务端发送的关闭连接请求时,触发onSocketClose事件
      console.log("连接已关闭", e);
    })
    wx.onSocketError((e) => {
      //如果出现连接、处理、接收、发送数据失败的时候触发onSocketError事件
      console.log(e);
    })
  },

  orderConfirmOnclose() {
    this.setData({
      matching: false
    })
  },

  // 获取是否需要更新
  getVersion() {
    get('api/app/version', {}, (res) => {
      let version = wx.getStorageSync('versionIn')
      if (!version || res.data.op_version != version || version == null) {
        wx.setStorageSync('version1', '0')
        wx.setStorageSync('version2', '0')
        wx.setStorageSync('version3', '0')
        wx.setStorageSync('version4', '0')
        wx.setStorageSync('versionIn', res.data.op_version)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.timer_) {
      clearInterval(this.timer_)
    }
    wx.onSocketClose((e) => {
      console.log('WebSocket 已关闭!')
    })
  },

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.page * 10 < this.data.total) {
      this.getArticleList(++this.data.page)
    }
  },

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

  /**
   * 监听页面滚动事件
   */
  onPageScroll: function (e) {
    let top = 6 // 超过多少像素开始显示导航栏背景
    let tabScrollTop = 782 //超过多少像素固定美丽秘籍tab到顶部
    let scrollTop = e.scrollTop
    let {
      navBarBgClass,
      tabClass
    } = this.data
    if (scrollTop > tabScrollTop && !tabClass) {
      tabClass = 'articleFixed'
    } else if (scrollTop < tabScrollTop && tabClass) {
      tabClass = ''
    }
    this.setData({
      tabClass
    })
    if (scrollTop >= top && !navBarBgClass) {
      navBarBgClass = ' navbar-bg-white '
      app.globalData.navBarData.navBarBgClass = navBarBgClass
      this.setData({
        navBarBgClass,
        isTips: false
      })
    }
    if (scrollTop < top && navBarBgClass) {
      navBarBgClass = ''
      this.setData({
        navBarBgClass
      })
      app.globalData.navBarData.navBarBgClass = navBarBgClass
    }
  },
  // 去测肤
  goSkin() {
    wx.navigateTo({
      url: '/pages/plan/plan',
    })
  },
  goOrder(e) {
    let index = e.currentTarget.dataset.index
    let urlIndex = e.currentTarget.dataset.urlindex
    if (urlIndex == 7) {
      wx.navigateTo({
        url: `/pages/moreClassify/moreClassify?data=${JSON.stringify(this.data.homeData.shortcut)}`,
      })
      return
    }
    app.globalData.toViewIndex = index
    wx.switchTab({
      url: '/pages/orderBy/orderBy',
      success: function () {
        var page = getCurrentPages().pop();
        page.onPullDownRefresh();
      }
    })
  },
  // 轮播图改变
  changeSwiper(e) {
    this.setData({
      swiperIndex: e.detail.current
    })
  },
  /**
   * 切换状态
   */
  onTabsChange(e) {
    let current = e.currentTarget.dataset.index
    if (current == this.data.current) {
      return;
    }
    this.setData({
      current,
      page: 1,
    }, () => {
      this.getArticleList(1)

    })
  },
  /**
   * 获取美丽秘籍分类
   * /api/info/classify
   */
  getClassify() {
    get('api/info/classify', {}, (res) => {
      this.setData({
        classify: res.data.list
      }, () => {
        this.getArticleList()
      })
    })
  },
  /**
   * 获取美丽秘籍列表
   * /api/info
   */
  getArticleList(_page) {
    this.setData({
      spinning: true
    })
    let {
      tempPics,
      classify,
      page,
      value,
      current
    } = this.data;
    get('api/info', {
      page: _page || page,
      limit: 10,
      keyword: value,
      classify_id: classify[current].id,
    }, (res) => {
      res.data.list.map(item => {
        item.create_time = item.create_time.substring(0, 10)
      })
      if (_page == 1 || page == 1) {
        tempPics = []
        this.data.page = 1
      }
      tempPics.push(...res.data.list)
      this.setData({
        tempPics,
        total: res.data.total,
        spinning: false
      })
      this.jsData.isListLoading = true
    })
  },
  //获取图片尺寸数据
  loadPic: function (e) {
    var that = this,
      data = that.data,
      tempPics = data.tempPics,
      index = e.currentTarget.dataset.index
    if (tempPics[index]) {
      //以750为宽度算出相对应的高度
      tempPics[index].height = e.detail.height * 750 / e.detail.width
      tempPics[index].isLoad = true
    }
    that.setData({
      tempPics: tempPics
    }, function () {
      that.finLoadPic()
    })
  },
  //图片加载错误处理
  loadPicError: function (e) {
    var that = this,
      data = that.data,
      tempPics = data.tempPics,
      index = e.currentTarget.dataset.index
    if (tempPics[index]) {
      //图片加载错误时高度固定750,展示为正方形
      tempPics[index].height = 750
      tempPics[index].isLoad = true
    }
    that.setData({
      tempPics: tempPics
    }, function () {
      that.finLoadPic()
    })
  },
  //判断图片是否加载完成
  finLoadPic: function () {
    var that = this,
      data = that.data,
      tempPics = data.tempPics,
      length = tempPics.length,
      fin = true
    for (var i = 0; i < length; i++) {
      if (!tempPics[i].isLoad) {
        fin = false
        break
      }
    }
    if (fin) {
      if (that.jsData.isListLoading) {
        that.jsData.isListLoading = false
        that.renderPage()
      }
    }
  },
  //渲染到瀑布流
  renderPage: function () {
    var that = this,
      data = that.data,
      columns = data.columns,
      tempPics = data.tempPics,
      length = tempPics.length,
      columnsHeight = that.jsData.columnsHeight,
      index = 0
    if (this.data.page == 1) {
      columns = [
        [],
        []
      ]
    }
    for (var i = 0; i < length; i++) {
      index = columnsHeight[1] < columnsHeight[0] ? 1 : 0
      columns[index].push(tempPics[i])
      columnsHeight[index] += tempPics[i].height
    }
    that.setData({
      columns: columns,
      tempPics: []
    })
    that.jsData.columnsHeight = columnsHeight
  },
  /**
   * swiper滚动事件
   * @param {*} e
   */
  swiperChange: function (e) {
    let currentSource = e.currentTarget.dataset.currentSource
    if (currentSource == 'topBanner') {
      this.setData({
        topBannerCurrentSwiper: e.detail.current
      })
    }
    if (currentSource == 'cardBanner') {
      this.setData({
        cardBannerCurrentSwiper: e.detail.current
      })
    }
  },

  /**
   * 关闭弹框
   */
  onClose(e, _bool) {
    let key = _bool ? e : e.currentTarget.dataset.key
    this.setData({
      [key]: false
    })
    getApp().globalData.couponPopup = false
  },

  bindchanges(e) {
    this.setData({
      currentNewAcount: e.detail.current
    })
  },

  /**
   * 确认领取
   */
  onConfirm() {
    wx.showToast({
      title: '领取成功',
      icon: 'none'
    })
    getApp().globalData.couponPopup = false
    this.onClose('visible', true)
    // this.setData({ visible: false })
  },
  /**
   * 两点之间距离计算
   * @param {*} lat1 
   * @param {*} lng1 
   * @param {*} lat2 
   * @param {*} lng2 
   */
  getDistance(lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

    return distance;
  },


  /**
   * 获取店铺接口
   * /api/store
   */
  getStore() {
    get(
      'api/store', {
        page: 1,
        limit: 100,
        keyword: ""
      },
      (res) => {
        let lat1 = app.address.latitude,
          lng1 = app.address.longitude,
          storeList = res.data.list,
          distanceList = []
        //循环遍历计算获取当前定位到各门店的距离
        storeList.forEach(item => {
          let distanceInfo = {}
          distanceInfo["id"] = item.id
          distanceInfo["dist"] = this.getDistance(lat1, lng1, item.latitude, item.longitude)
          distanceList.push(distanceInfo)
        })
        //近到远排序
        let _distanceList = distanceList.sort(function (a, b) {
          return a.dist - b.dist
        })
        //切换门店
        this.getStoreInfo(String(_distanceList[0].id))
        wx.setStorageSync('store_id', String(_distanceList[0].id))
      }
    )
  },
  /**
   * 获取当前定位
   * @param {*} obj 
   */
  getPermission: function (obj) {
    let that = this
    wx.getLocation({
      success: function (res) {
        that.getStore()
        app.address = res
        let lat1 = app.address.latitude
        let lng1 = app.address.longitude
        that.setData({
          lat1,
          lng1,
        })
      },
      fail: function () {
        wx.getSetting({
          success: function (res) {
            var statu = res.authSetting;
            if (!statu['scope.userLocation']) {
              wx.showModal({
                title: '是否授权当前位置',
                content: '需要获取您的地理位置,请确认授权,否则无法定位最近店铺',
                success: function (tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //授权成功之后,再调用chooseLocation选择地方
                          wx.getLocation({
                            success: function (res) {
                              that.getStore()
                              app.address = res
                              let lat1 = app.address.latitude
                              let lng1 = app.address.longitude
                              that.setData({
                                lat1,
                                lng1,
                              })
                            },
                          })
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'success',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '调用授权窗口失败',
              icon: 'success',
              duration: 1000
            })
          }
        })
      }
    })
  },
  /**
   * 首页数据
   */
  getHomeData() {
    let that = this;
    this.getPermission(that); //获取当前定位  
    get('api/home', {}, (res) => {
      let nowDate = Math.round(new Date().getTime() / 1000).toString();
      // 判断推荐项目展示时间
      // let referrals = []
      // res.data.referrals.forEach(item => {
      //   if (nowDate.toString() > item.start_time.toString() && nowDate.toString() < item.end_time.toString()) {
      //     referrals.push(item)
      //   }
      // })
      // res.data.referrals = referrals
      // 判断推荐项目为两个的话添加进行展示
      // if (res.data.referrals.length < 3 && res.data.referrals.length != 1) {
      //   res.data.referrals.forEach(item => {
      //     res.data.referrals.push(item)
      //   })
      // }
      this.setData({
          homeData: res.data
        },
        () => {
          // this.getProjectList(1)
          this.setData({
            isLoading: false
          })
        }
      )
    })
  },


  /**
   * 首页数据
   */
  activityProgress() {
    get('api/activity/progress', {}, (res) => {
      this.setData({
        progressList: res.data.list
      })
    })
  },

  /**
   * 首页数据
   */
  check_new_record() {
    let that = this
    // get('api/user/plan/check_new_record', {}, (res) => {
    //   if (res.data.status == 1) {
    //     wx.showModal({
    //       title: '提示',
    //       content: '检测到新的美容计划,是否替换现有计划',
    //       success(res1) {
    //         if (res1.confirm) {
    //           console.log('用户点击确定', res.data.analysis_id)
    //           that.planReplace('yes', res.data.analysis_id)
    //         } else if (res1.cancel) {
    //           console.log('用户点击取消', res.data.analysis_id)
    //           that.planReplace('no', res.data.analysis_id)
    //         }
    //       }
    //     })
    //   }
    // })
  },

  /**
   * 首页数据
   */
  planReplace(op_type, analysis_id) {
    post('api/user/plan/replace', {
      op_type: op_type,
      analysis_id: analysis_id
    }, (res) => {
      this.getHomeData()
    })
  },

  cardingCatchTap() {
    wx.navigateTo({
      url: '../guildMessage/index',
    })
  },

  /**
   * 首页数据
   */
  activityRules() {
    let that = this
    // get('api/activity/rules', {}, (res) => {
    //   WxParse.wxParse('article', 'html', res.data.content, that, 5)

    // })
  },

  guildMessage() {
    this.setData({
      guildMessage: true
    })
  },

  onCloseLandscape() {
    this.setData({
      guildMessage: false
    })
  },

  /**
   * 首页列表
   */
  getProjectList(_page) {
    return
    let {
      list,
      page
    } = this.data
    get(
      'api/project', {
        store_id: this.data.homeData.store.id,
        page: _page || page,
        limit: 10
      },
      (res) => {
        if (_page == 1 || page == 1) {
          list = []
          this.data.page = 1
        }
        list.push(...res.data.list)
        this.setData({
          list,
          isLoading: false,
          total: res.data.total
        })
      }
    )
  },

  /**
   * 店铺信息
   * /api/store/info
   */
  getStoreInfo(store_id) {
    get(
      'api/store/info', {
        store_id
      },
      (res) => {
        this.setData({
            ['homeData.store']: res.data

          },
          () => {
            wx.setStorageSync('store_id', String(store_id))
            app.globalData.storeData = res.data
            this.getProjectList(1)
          }
        )
      }
    )
  },

  /**
   * 首页广告跳转
   */
  goToUrl(e) {
    console.log(e);
    let type = e.currentTarget.dataset.urltype
    if(type==0){
      return
    }
    if (e.currentTarget.dataset.url && type == 1) {
      if (e.currentTarget.dataset.url == '/pages/orderBy/orderBy') {
        wx.switchTab({
          url: '/pages/orderBy/orderBy'
        })
      } else if (e.currentTarget.dataset.url == '/pages/shoppingMall/shoppingMall') {
        wx.
        switchTab({
          url: '/pages/shoppingMall/shoppingMall'
        })
      } else {
        wx.navigateTo({
          url: e.currentTarget.dataset.url
        })
        trackUserEvent(e.currentTarget?.dataset?.source?.type)
      }
    }
    this.setData({
      posterPopup: false
    })
  },

  /**
   * 跳转店铺列表
   */
  goToStore() {
    wx.navigateTo({
      url: '/pages/store/store?defaultStore=' +
        JSON.stringify(this.data.homeData.store)
    })
  },

  /**
   * 跳转项目详情
   */
  goToProject(e) {
    let item = e.currentTarget.dataset.item || {}
    let projectId = item.project_id || item.id
    let storeId = item.store_id || this.data.homeData.store.id
    wx.navigateTo({
      url: `/pages/projectDetail/projectDetail?project_id=${projectId}&store_id=${storeId}`
    })
  },

  /**
   * 跳转变美计划
   */
  goToBeautyPlan(e) {
    let analysisId = e.currentTarget.dataset.analysisId
    wx.navigateTo({
      url: `/pages/beautyPlan/beautyPlan?analysis_id=${analysisId}`
    })
  },

  /**
   * 获取首次开卡优惠
   * api/user/activity
   */
  getUserActivity() {
    if (this.timer) {
      clearInterval(this.timer_)
    }
    get('api/user/activity', {}, (res) => {
      this.data.needReqActivity = false
      if (res.data) {
        res.data.currentTime = formatActivity(res.data.expire_time_seconds)
        this.setData({
          activity: res.data
        })
        this.timer_ = setInterval(() => {
          if (res.data.expire_time_seconds <= 0) {
            clearInterval(this.timer_)
          }
          res.data.expire_time_seconds--
          res.data.currentTime = formatActivity(res.data.expire_time_seconds)
          this.setData({
            activity: res.data
          })
        }, 1000)
      }
    })
  },

  /**
   * 开卡优惠关闭
   */
  onCloseToast() {
    this.setData({
      btmToast: false
    })
  },

  /**
   * 肤质检测结果
   */
  goToAnalysisResult(e) {
    if (!this.data.homeData.analysis.score > 0) {
      wx.navigateTo({
        url: '/pages/plan/plan?defaultStore=' +
          JSON.stringify(this.data.homeData.store)
      })
      return
    }
    let analysis = e.currentTarget.dataset.analysis || {}
    let analysisId = analysis.analysis_id
    let url = `/pages/skinRecord/skinRecord?id=${analysisId}`
    if (!analysisId) {
      this.gotoOrderBy()
      return
    }
    wx.navigateTo({
      url: url
    })
  },

  /**
   * 根据Url类型跳转
   */
  jumpByUrlType(e) {
    let item = e.currentTarget.dataset.item || {}
    let urlType = item.url_type || 0
    let url = item.url || ''
    // 跳转类型,0不跳转,1内部地址,2外部地址
    switch (urlType) {
      case 1:
        url && wx.navigateTo({
          url: url
        })
        break
      default:
        break
    }
  },
  //获取当前推荐原则
  recommendRule() {
    if (!this.data.homeData.analysis.score > 0) {
      wx.navigateTo({
        url: '/pages/plan/plan?defaultStore=' +
          JSON.stringify(this.data.homeData.store)
      })
      return
    }
    let url = `/pages/orderBy/orderBy`
    wx.switchTab({
      url: url
    })
  },
  /**
   * 预约下单tab
   */
  gotoOrderBy() {
    if (this.data.homeData.analysis_check == 1) {
      get('/v2/api/user/recommend_rule', {}, res => {
        if (res.data.status == 0) {
          wx.navigateTo({
            url: '/pages/recommendRule/recommendRule',
          })
        } else {
          wx.navigateTo({
            url: '/pages/faceDetectionDetails/faceDetectionDetails',
          })
        }
      })
    } else {
      if (!this.data.homeData.analysis.score > 0) {
        wx.navigateTo({
          url: '/pages/plan/plan?defaultStore=' +
            JSON.stringify(this.data.homeData.store)
        })
        return
      }
      let url = `/pages/orderBy/orderBy`
      wx.switchTab({
        url: url
      })
    }

  },
  onOderBy() {
    let url = `/pages/orderBy/orderBy`
    wx.switchTab({
      url: url
    })
  },
  // 跳转到领券详情
  getCoupon() {
    wx.navigateTo({
      url: '/pages/couponCenter/couponCenter',
    })
  },
  // 十月一活动
  onClosePop() {
    this.setData({
      PopShow: false,
    })
  },
  gotoActive() {
    wx.navigateTo({
      url: '/pages/activePage2/activePage2',
    })
    this.setData({
      PopShow: false
    })
  },
  // 点击跳转美丽秘籍
  goArticleDetail(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/articleDetail/articleDetail?id=${id}`,
    })
  },
  // 点击推荐项目跳转到项目
  goOtherUrl(e) {
    let url = e.currentTarget.dataset.url
    let type = e.currentTarget.dataset.type
    if (url == '/pages/orderBy/orderBy') {
      wx.switchTab({
        url: '/pages/orderBy/orderBy'
      })
    } else if (url == '/pages/shoppingMall/shoppingMall') {
      wx.switchTab({
        url: '/pages/shoppingMall/shoppingMall'
      })
    } else {
      wx.navigateTo({
        url: url,
      })
    }
    // if(type==1){
    //   wx.navigateTo({
    //     url:url,
    //   })
    // }else if(type==2){
    //   wx.navigateTo({
    //     url: `/pages/projectDetail/projectDetail?source=goods&id=${id}&store_id=${this.data.storeId}`,
    //   })
    // }else if(type==3){
    //   wx.navigateTo({
    //     url: `/pages/projectDetail/projectDetail?source=project&id=${id}&store_id=${this.data.storeId}`,
    //   })
    // }else{
    //   return
    // }
  },
  //获取消息列表
  getMessageList() {
    get('v2/api/message/list', {
      page: 1,
      limit: 3,
    }, (res) => {
      if (res.code == 200) {
        // 是否首页通知 1是 0不是
        let list = res.data.list.filter(item => {
          return item.notice != 0
        })
        this.setData({
          messageList: list
        })
        this.getWorkMessageList()
      }
    })
  },
  // 获取业务消息列表
  getWorkMessageList() {
    let that = this
    get('v2/api/message/notice', {
      page: 1,
      limit: 3,
    }, (res) => {
      if (res.code == 200) {
        let workMessageList = that.data.messageList
        workMessageList.push(...res.data.list)
        // 对通知和业务消息的集合做排序  最新的在上面
        workMessageList.sort((a, b) => {
          return new Date(b.create_time) - new Date(a.create_time)
        });
        //  截取前三个
        workMessageList = workMessageList.slice(0, 3)
        this.setData({
          messageList: workMessageList,
        })
      }
    })
  },
  // 获取未读消息数量
  getNotMessageTotal() {
    get('v2/api/message/total', {}, (res) => {
      if (res.code == 200) {
        this.getWorkMessage(res.data)
      }
    })
  },
  // 获取未读业务消息数量
  getWorkMessage(total) {
    get('v2/api/message/all', {}, (res) => {
      if (res.code == 200) {
        this.setData({
          notMessageTotal: Number(total) + Number(res.data)
        })
      }
    })
  },
  // 跳转到消息详情
  goMessageDetail(e) {
    let id = e.currentTarget.dataset.id
    let notice = e.currentTarget.dataset.notice
    // 是否是业务消息  是业务消息就跳转到消息中心
    if (notice) {
      wx.navigateTo({
        url: `/subPackagesC/pages/messageDetail/messageDetail?id=${id}`,
      })
    } else {
      wx.navigateTo({
        url: '/subPackagesC/pages/messageCenter/messageCenter',
      })
    }
  },
  // 跳转到消息列表
  goMessageCenter() {
    wx.navigateTo({
      url: '/subPackagesC/pages/messageCenter/messageCenter',
    })
  },
  // 获取测肤概要信息
  getSkinInfo() {
    // get('v2/api/home/analysis', {}, (res) => {
    //   if (res.code == 200) {
    //     this.setData({
    //       skinInfo: res.data
    //     })
    //   }
    // })
  },
  // 跳转到测肤记录详情
  goTestSkin() {
    wx.navigateTo({
      url: '/subPackagesD/pages/testSkin/testSkin?isRadio=true',
    })
  },
})