import {
  getAppUserInfo,
  getC1,
  getC2,
  getC3,
  needOpenCard,
  getCurrentRouter
} from './helper'
import Router from './router'
import ManageDate from './manageDate'
import { cEvent } from './event'
import Http from './Http'
const Promise = require('../lib/bluebird')
const config = require('../config/index').envInfo
import utils from './util'
let openCardLister = null
const pathData = require('./currentAccessiblePath.js')
import * as watch from "./watch.js";
import { Integer } from './integerDigitalConvertion'

/**
 * 单例
 */
const manageDate = new ManageDate()
class WXService extends Http {
  constructor() {
    super()
    this.Promise = Promise
    this.currentPage = null
  }

  getToken() {
    return super.getToken()
  }

  /**
   * 所有接口中
   * 返回401 重试 （getUserInfoLimitCount：重试次数）,超过重试次数提示会员系统异常,请联系管理员
   */
  request({
    url,
    data,
    header,
    method,
    dataType,
    responseType,
    success,
    fail,
    complete }) {
    return super.request.apply(this, arguments).finally(() => {
      this.setPageLoadStatus()
      wx.hideLoading()
    }).catch(res => {
      // 用户未登录
      if (res.msg && res.msg.indexOf('未登录') > -1) {
        if (!this.getUserInfoLimitCount) {
          this.getUserInfoLimitCount = 1
        } else {
          this.getUserInfoLimitCount++
        }
        console.log('count', this.getUserInfoLimitCount)
        if (this.getUserInfoLimitCount > 3) {
          wx.showToast({
            title: '会员系统异常,请联系管理员',
            icon: 'none',
            duration: 2000
          })
        } else {
          this.reLogin()
        }
      } else if (res.msg && res.msg.indexOf('请重新授权') > -1) {
        wx.setStorageSync('reLoginErr', true)
        this.replace('/pages/userCenter/userCenter')
      }
    })
  }

  // 所有页面都有接口load状态
  setPageLoadStatus() {
    if (this.currentPage) {
      this.nextTick(() => {
        this.currentPage.setData({
          loadStatus: this.state
        })
      })
    }
  }

  /**
   * 页面导航
   * @param url
   * @param switchTab 是否是switchTab导航
   */
  router(url, switchTab) {
    return new Router(url, switchTab)
  }

  back(dintance) {
    this.router().back(dintance)
  }

  replace(url) {
    this.router(url).replace()
  }

  all() {
    return Promise.all.apply(Promise, arguments)
  }
  /**
   * 更新缓存 登陆
   * 
  */
  reLogin() {
    wx.setStorageSync('token', '')
    wx.setStorageSync('reLoginErr', false)
    const app = getApp()
    var _this = this
    return _this.login().then(result => {
      if (result.code) {
        _this.post(`/member/minaLogin`, {
          code: result.code,
          wechatInfo: null,
          brandId: app.globalData.brandId,
        }).then(response => {
          if (response) {
            let dataResp = response.data.data
            wx.setStorageSync('token', dataResp.token)
            wx.setStorageSync('_baseUserInfo', dataResp)
            wx.setStorageSync('reLoginErr', false)
            // 刷新页面
            setTimeout(() => {
              const pages = getCurrentPages()
              const perpage = pages[pages.length - 1]
              perpage.onShow()
            }, 2000)
            return Promise.resolve({ response })
          }
        }).catch(err => {
          return Promise.reject(err)
        })
      } else {
        return Promise.reject({ state: 2, info: res.data.data })
      }
    }).catch(err => {
      console.log(err)
    })
  }

  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          resolve(res)
          wx.setStorageSync('_loginCode', res.code)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
  }

  getBaseUserInfo() {
    if (!this.baseUserInfo) {
      let baseUserInfo = wx.getStorageSync('_baseUserInfo')
      this.baseUserInfo = baseUserInfo
    }
    return this.baseUserInfo
  }

  // 通过unionId获取用户信息并更新token(防止token信息过期)
  getUserInfo() {
    const baseUserInfo = this.getBaseUserInfo()
    wx.showLoading({
      title: '正在加载...',
      icon: 'none'
    })

    console.log(JSON.stringify(baseUserInfo))
    return this.get('i-user/info', {
      unionId: baseUserInfo.unionId,
      minaOpenId: baseUserInfo.openId
    }).then((res) => {
      console.log('i-user/info res is %o ', res)
      if (res.data.code === -10001) {
        this.showToast(`${res.data.message}`)
        return Promise.reject({ state: -10001 })
      } else if (res.data.data.isMember === '1') {
        let baseUserInfo = this.getBaseUserInfo()
        let newBaseUserInfo = { ...baseUserInfo, ...res.data.data }
        this.baseUserInfo = newBaseUserInfo
        wx.setStorageSync('_baseUserInfo', newBaseUserInfo)
        // wx.setStorageSync('buyer-token', res.data.data.token)
        wx.setStorageSync('token', res.data.data.token)
        this.startReport()
        return Promise.resolve({ state: 1, info: res.data.data })
      } else {
        // this.openCard()
        return Promise.resolve({ state: 2, info: res.data.data })
      }
    }).finally(() => {
      wx.hideLoading()
    })
  }

  getManageDate() {
    return manageDate
  }

  selectAll(selector, options) {
    return new Promise((resolve, reject) => {
      wx.createSelectorQuery().selectAll('.page-body').fields(options, (res) => {
        resolve(res)
      }).exec()
    })
  }

  scrollOffset() {
    return new Promise((resolve, reject) => {
      wx.createSelectorQuery().selectViewport().scrollOffset(function (res) {
        resolve(res)
      }).exec()
    })
  }

  showModal(config = {}) {
    return new Promise((resolve, reject) => {
      wx.showModal({
        ...config,
        success: (res) => {
          if (res.confirm) {
            config.success ? config.success(res) : resolve(res)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          console.error(err)
        }
      })
    })
  }

  getSystemInfo() {
    return new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success: (res) => {
          resolve(res)
        },
        fail: (res) => {
          reject(res)
        },
        complete: (res) => {

        }
      })
    })
  }
  getAssPath() {
    const paths = pathData
    let pathArr = []
    for (const key in paths) {
      if (paths.hasOwnProperty(key)) {
        let pathObj = {}
        pathObj[key] = paths[key]
        pathArr.push(pathObj)
      }
    }
    return pathArr
  }

  trialList() {
    //
    let localPath = this.getAssPath()
    
    // 如果 localPath  则返回true
    wx.showLoading({
      title: '加载中'
    })
    return this.get(`/member/trial/list`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          // 对应的path
          let currentPaths = [];
          localPath.forEach(item => {
            if (item.hasOwnProperty(data)) {
              currentPaths = item[data]
            } else {
              console.log(222);
            }
          })
          return Promise.resolve({ currentPaths })
        }
      }
    })
  }

  // getAssPath () {
  //   const paths = pathData
  //   let pathArr = []
  //   for(const key in paths){
  //     if (paths.hasOwnProperty(key)) {
  //       pathArr.push(key)
  //     }
  //   }
  //   return pathArr
  // }
  // handlerPage (page) {
  //   const AccreditWhitePages = [
  //     'pages/welcome/welcome'
  //   ] // 免授权页面白名单
  //   const _self = this
  //   const app = _self.getApp()

  //   const baseUserInfo = wx.getStorageSync('_baseUserInfo')
  //   if (baseUserInfo && baseUserInfo.isMember === '1') {
  //     app.globalData.openCard = true
  //   }
  //   return new Promise((resolve, reject) => {
  //     let accreditUserInfo = wx.getStorageSync('_accreditUserInfo')
  //     if (app.globalData.openCard && accreditUserInfo) {
  //       resolve()
  //       return false
  //     }
  //     if (AccreditWhitePages.indexOf(page.route) > -1) {
  //       resolve()
  //     } else if (accreditUserInfo) {
  //       getAppUserInfo().then(() => {
  //         if (this.lock) {
  //           return false
  //         }
  //         if ((!baseUserInfo || baseUserInfo.isMember !== '1') && needOpenCard()) {
  //           reject({ state: 1 })
  //           _self.lock = false
  //         } else {
  //           _self.lock = false
  //           resolve()
  //         }
  //       }).catch((res) => {
  //         reject()
  //       })
  //     } else {
  //       reject({ state: 1 })
  //     }
  //   }).catch((err) => {
  //     if (err && err.state === 1) {
  //       const modifyMottoRoute = [
  //         "pos/express/pages/orderList/orderList",
  //         "pos/express/pages/confirm/confirm"
  //       ]
  //       let router = '/pages/welcome/welcome';
  //       if (modifyMottoRoute.indexOf(page.route) > -1) {
  //         page.options.motto = 'express';
  //       }
  //       wxService.router('/pages/welcome/welcome').search({
  //         route: `${page.route}`,
  //         options: JSON.stringify(page.options)
  //       }).replace()
  //     }
  //     return Promise.reject()
  //   })
  // }

  // 设置异步的全局变量值
  initAppGlobalDataSync() {
    const app = this.getApp()
    if (!app.globalData.userInfo) {
      const userInfo = wx.getStorageSync('_userInfo')
      app.globalData.userInfo = userInfo
    }
    if (!app.globalData.baseUserInfo) {
      const baseUserInfo = wx.getStorageSync('_baseUserInfo')
      app.globalData.baseUserInfo = baseUserInfo
    }
    if (!app.globalData.userNo) {
      const token = wx.getStorageSync('token')
      app.globalData.userNo = token.split('###')[0]
    }
  }

  //生成触点对象Id
  getTentacleContent(tentacleInfo) {
    return this.post('/marketing/tentacleContent/getTentacleContent', tentacleInfo).then((res) => {
      let data = res.data.data
      return Promise.resolve(data);
    }).finally(() => { })
  }

  //根据触点对象id获取触点对象信息
  getTentacleContentByTentacleId(id) {
    this.post('/marketing/tentacleContent/queryTentacleContentById', { id: id }).then((res) => {
      let data = res.data.data
      if (!data) {
        return;
      }

      let TENTACLE_CONTENT = {
        id: data.id,
        tentacleType: data.type,
        tentacleId: data.tentacleId,
        contentType: data.contentType,
        contentId: data.contentId
      }

      let storageObj = {
        memberId: '',
        obj: TENTACLE_CONTENT
      }

      //记录触点统计
      this.markerTentacleInfo(TENTACLE_CONTENT);

      if (data.status == 1) {
        var timestamp = Date.parse(new Date())
        var expiration = timestamp + 1800000
        wx.setStorageSync('TENTACLE_CONTENT', storageObj)
        wx.setStorageSync('TIME_EXPIRATION', expiration)
      }
      else {
        wx.removeStorageSync('TENTACLE_CONTENT')
        wx.removeStorageSync('TIME_EXPIRATION')
      }
    }).finally(() => {

    })
  }

  //记录触点信息
  markerTentacleInfo(tentacleContent) {
    //1 未登录时不调用改接口 
    //2 半个小时之内如果调用过该接口则忽略 
    // console.log('触点信息是---', tentacleContent)
    let { memberId } = wx.getStorageSync('_baseUserInfo') ? wx.getStorageSync('_baseUserInfo') : {};
    if (memberId) {
      var currentTimestamp = Date.parse(new Date())
      let lastRemarkTime = wx.getStorageSync('lastRemarkTime') ? wx.getStorageSync('lastRemarkTime') : 0;
      //如果当前时间大于记录时间 说明半个小时已过
      if (currentTimestamp > lastRemarkTime) {
        //记录
        this.callApiRemarkTentacle(memberId, tentacleContent);
      }
      else {
        //小于半个小时
        //看一下当前触点于之前的的是不是一个触点，如果是一个触点 则不调用接口
        let lastRemarkTentacle = wx.getStorageSync('lastRemarkTentacle');
        if (lastRemarkTentacle) {
          // 678273783177551872
          if (lastRemarkTentacle.id != tentacleContent.id) {
            this.callApiRemarkTentacle(memberId, tentacleContent);
          }
        }
      }
    }
  }

  //调用接口记录触点信息
  callApiRemarkTentacle(memberId, tentacleContent) {
    wxService.post(`/member/share/inviteFriendsLoginLog/saveBatch`, {
      memberId: memberId,
      tentacleContent: tentacleContent,
    }).then(res => {
      if (res) {
        if (res.data.result == 0) {
          //调用接口成功 开始保存
          var currentTimestamp = Date.parse(new Date())
          var expiration = currentTimestamp + 1800000;
          wx.setStorageSync('lastRemarkTime', expiration);
          wx.setStorageSync('lastRemarkTentacle', tentacleContent);
        }
      }
    });
  }

  page(config) {
    const _self = this
    const { sr } = this.getApp()
    config.data.experAccessible;
    config.data.currentHasUserInfo = false;

    // wx.removeStorageSync('isExperiencer')
    // const baseUserInfo = wx.getStorageSync('_baseUserInfo')
    //  // 获取当前会员是否是体验者
    //  const { member } = baseUserInfo
    //  const curMemberTrial = member && member.trial || false
    //  console.log('d', curMemberTrial)
    //  wx.setStorageSync('isExperiencer', curMemberTrial)

    const CONFIG_PAPGE = {
      onLoad: function (...args) {
        const page = this
        _self.initAppGlobalDataSync()
        watch.setWatcher(page);
        //处理触点信息数据
        //修改参数
        let pageIsFromShare = false, id = null;
        args.forEach(item => {
          if (item['t']) {
            pageIsFromShare = true;
            id = Integer.digit(item['t'], 64, 10);
            if (item['i']) {
              item['id'] = Integer.digit(item['i'], 64, 10);
            }
          }
          if (item['m']) {
            item['memberId'] = Integer.digit(item['m'], 64, 10);
            if (item['i']) {
              item['id'] = Integer.digit(item['i'], 64, 10);
            }
            // id = item['memberId'];
          }
          if (item['scene']) {
            pageIsFromShare = true;
            let sceneParam = decodeURIComponent(item['scene']);
            let tParam = '';
            //判断是不是有触点参数
            if (sceneParam.indexOf('t=') > -1) {
              let tArr = sceneParam.split('&');
              for (let i = 0; i < tArr.length; i++) {
                if (tArr[i].indexOf('t=') > -1) {
                  tParam = tArr[i].split('t=')[1];
                  break;
                }
              }
            }

            let idParam = sceneParam.split('&')[0];
            let shareId = idParam && idParam.split('=')[1] || 0;
            // console.log(shareId)
            // console.log(idParam)
            //处理pageId的
            if (idParam.indexOf('pageId') > -1) {
              item['pageId'] = shareId;
            }
            if (tParam) {
              id = Integer.digit(tParam, 64, 10);
            }
            //
            if (shareId && shareId != 0) {
              item['id'] = Integer.digit(shareId, 64, 10);
            }
          }
        });
        //如果打开的是分享界面则进行触点对象信息请求并存储到本地 放到后续的header中
        if (pageIsFromShare && id) {
          //调用接口
          _self.getTentacleContentByTentacleId(id);
        }
        config.onLoad && config.onLoad.apply(page, args)
      },
      onShow: function (...args) {
        // wx.removeStorageSync('isExperiencer')
        // const baseUserInfo = wx.getStorageSync('_baseUserInfo')
        // // 获取当前会员是否是体验者
        //  const { member } = baseUserInfo
        //  const curMemberTrial = member && member.trial || false
        //  console.log('d', curMemberTrial)
        //  wx.setStorageSync('isExperiencer', curMemberTrial)
        const isExperiencer = wx.getStorageSync('isExperiencer') || false

        console.log('获取当前会员是否是体验者', isExperiencer)

        const page = this
        _self.currentPage = page
        config.onShow && config.onShow.apply(page, args)
        // 获取当前页
        let router = getCurrentRouter()
        const baseUserInfo = _self.getBaseUserInfo()
        // this.setData({
        //   experAccessible: true
        // })
        // if (baseUserInfo) {
          _self.trialList().then(res => {
            if (!res.length) {
              this.setData({
                experAccessible: true
              })
            }
            const { currentPaths } = res
            
            //有版本号
            if (currentPaths.length > 0){
              // 是体验者
              if (currentPaths.indexOf(router.route) > -1 && isExperiencer) {
                this.setData({
                  experAccessible: true
                })
              } else {
                  this.setData({
                    experAccessible: false
                  })
              }
            } else {
              // 不限制
              this.setData({
                experAccessible: true
              })
            }

          //   // if (currentPaths.indexOf(router.route) > -1 && isExperiencer || currentPaths.length == 0) {
          //   //   this.setData({
          //   //     experAccessible: true
          //   //   })
          //   // } else {
          //   //   this.setData({
          //   //     experAccessible: false
          //   //   })
          //   // }

          })

          console.log('000',this.data.experAccessible);
          
        // }

      },
      onReady: function (...args) {
        config.onReady && config.onReady.apply(this, args)
      },
      onHide: function (...args) {
        const page = this
        config.onHide && config.onHide.apply(this, args)

      },
      onUnload: function (...args) {
        config.onUnload && config.onUnload.apply(this, args)
      },
      onPageScroll: function (...args) {
        config.onPageScroll && config.onPageScroll.apply(this, args)
      },
      onShareAppMessage: function (...args) {
        const page = this
        const baseUserInfo = wx.getStorageSync('_baseUserInfo')
        let openId = ''
        if (baseUserInfo) {
          openId = baseUserInfo.openId
        }
        // 处理页面分享
        if (config.onShareAppMessage) {
          try {
            let shareConfig = config.onShareAppMessage.apply(this, args)
            if (!shareConfig) {

            } else {

            }
            return shareConfig
          } catch (e) {
            console.error(e)
          }
        }
      }
    }
    Page(Object.assign({}, config, CONFIG_PAPGE))
  }

  checkSession() {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: (data) => {
          resolve(data)
        },
        fail: (data) => {
          reject(data)
        }
      })
    })
  }

  nextTick(fn) {
    if (wx.nextTick) {
      wx.nextTick(() => {
        fn()
      })
    } else {
      setTimeout(() => {
        fn()
      }, 0)
    }
  }

  showToast({ title, icon = 'none' }) {
    wx.showToast({
      title,
      icon
    })
  }

  getConnectedWifi() {
    return new Promise((resolve, reject) => {
      wx.getConnectedWifi({
        success: (res) => {
          resolve(res)
        },
        fail: (res) => {
          reject(res)
        },
        complete: () => { }
      })
    })
  }

  navigateToMiniProgram(options) {
    const _self = this
    const promise = new Promise((resolve, reject) => {
      if (!openCardLister) {
        openCardLister = cEvent.on('openCardSuccess', function (data) {
          openCardLister = null
          resolve(data)
        })
      }
      this.showOpenCardModal({ _self, options, reject })
    })
    return promise
  }

  showOpenCardModal({ options, _self, reject }) {
    if (this.showOpenCardModelLock) {
      return false
    }
    this.showOpenCardModelLock = true // 避免多次弹出开卡对话窗
    // 开卡
    wx.navigateToMiniProgram({
      appId: 'wxeb490c6f9b154ef9', // 固定为此 appid，不可改动
      extraData: options, // 包括 encrypt_card_id, outer_str, biz三个字段，须从 step3 中获得的链接中获取参数
      success: function (data) {
        console.log('navigateToMiniProgram success data is %o', data)
        _self.lock = false
      },
      fail: function (data) {
        console.log('navigateToMiniProgram fail data is %o', data)
        this.router('/pages/userCenter/userCenter')
        // this.router('/pages/welcome/welcome')

        _self.lock = false
        reject(data)
      },
      complete() {
        _self.showOpenCardModelLock = false
      }
    })

    // wx.showModal({
    //   title: '请激活会员卡',
    //   content: '为了您更好的购物体验，请您先完善会员信息',
    //   showCancel: true,
    //   success: res => {
    //     if (res.confirm) {
    //       wx.navigateToMiniProgram({
    //         appId: 'wxeb490c6f9b154ef9', // 固定为此 appid，不可改动
    //         extraData: options, // 包括 encrypt_card_id, outer_str, biz三个字段，须从 step3 中获得的链接中获取参数
    //         success: function (data) {
    //           console.log('navigateToMiniProgram success data is %o', data)
    //           _self.lock = false
    //         },
    //         fail: function (data) {
    //           console.log('navigateToMiniProgram fail data is %o', data)
    //           _self.lock = false
    //           reject(data)
    //         }
    //       })
    //     } else {
    //       this.router('/pages/welcome/welcome')
    //       console.log('取消开卡跳转')
    //     }
    //   },
    //   complete: () => {
    //     this.showOpenCardModelLock = false
    //   }
    // })
  }
  /**
   * 开卡
  */
  openCard() {
    const baseUserInfo = wx.getStorageSync('_baseUserInfo')
    return new Promise((resolve, reject) => {
      if (baseUserInfo && baseUserInfo.memberActivateStatus) {
        console.log('已开卡')
        wxService.openCardList()
        resolve(baseUserInfo)
      } else if (!baseUserInfo || !baseUserInfo.memberActivateStatus) {
        console.log('去开卡')
        return this.navigateToMiniProgram({
          biz: baseUserInfo.biz,
          encrypt_card_id: baseUserInfo.encryptCardId,
          outer_str: baseUserInfo.outerStr
        })
      } else {
        reject({ state: 0 })
      }
    })
    // 注释原因  所有跳转前 判断新老会员
    // return new Promise((resolve, reject) => {
    //   if (baseUserInfo && baseUserInfo.member && baseUserInfo.member.mobile) {
    //     console.log('已开卡')
    //     wxService.openCardList()
    //     resolve(baseUserInfo)
    //   } else if (!baseUserInfo || !baseUserInfo.member || !baseUserInfo.member.mobile) {
    //     console.log('去开卡')
    //     return this.navigateToMiniProgram({
    //       biz: baseUserInfo.biz,
    //       encrypt_card_id: baseUserInfo.encryptCardId,
    //       outer_str: baseUserInfo.outerStr
    //     })
    //   } else {
    //     reject({ state: 0 })
    //   }
    // })
  }
  /**
   * 查看微信卡包中的卡券
   */
  openCardList() {
    // wechatCardId wechatCode
    const { wechatCardId, wechatCode } = wx.getStorageSync('_baseUserInfo')
    wx.openCard({
      cardList: [{
        cardId: wechatCardId,
        code: wechatCode
      }],
      success(res) {
        console.log('openCardList success', res)
      },
      fail(err) {
        console.log('openCardList fail data is %o', err)
      }
    })
  }

  getRandom(num = 1) {
    let random = Math.random()
    if (random < 0.1) {
      random += 0.1
    }
    let precision = 1
    for (let i = 1; i <= num; i++) {
      precision = precision * 10
    }
    return Math.floor(random * precision)
  }

  // 打开登录弹框
  openAuthModal() {
    return new Promise((resolve, reject) => {
      resolve({
        isAuthorization: true
      })
      return false
    })
  }
}

const wxService = new WXService()
module.exports = wxService
