const wxService = require('./wxService')
const moment = require('../lib/moment.min')
const Promise = require('../lib/bluebird')
const _ = require('../lib/underscore.min')
const envInfo = require('../config/index').envInfo
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/*格式化日期 2017-09-01*/
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

/* 获取当前页url */
function getCurrentPageUrl() {
  var pages = getCurrentPages() // 获取加载的页面
  var currentPage = pages[pages.length - 1] // 获取当前页面的对象
  var url = currentPage.route // 当前页面url
  return url
}

/* 获取当前页带参数的url */
function getCurrentPageUrlWithArgs() {
  var pages = getCurrentPages() // 获取加载的页面
  var currentPage = pages[pages.length - 1] // 获取当前页面的对象
  var url = currentPage.route // 当前页面url
  var options = currentPage.options // 如果要获取url中所带的参数可以查看options

  /** 
   * 拼接url的参数
  */
  var urlWithArgs = url + '?'
  for (var key in options) {
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

  return urlWithArgs
}
/** 
 * 获取当前帐号信息
*/
function getAccountInfo() {
  let accountInfo = wx.getAccountInfoSync();
  return accountInfo
}

/** 
 * 图片宽高比
*/
function imageUtil(e) {
  var imageSize = {};
  var originalWidth = e.detail.width;//图片原始宽 
  var originalHeight = e.detail.height;//图片原始高 
  var originalScale = originalHeight / originalWidth;//图片高宽比 
  //获取屏幕宽高 
  wx.getSystemInfo({
    success: function (res) {
      // var windowWidth = res.windowWidth/2; 
      // var windowHeight = res.windowHeight/2; 
      // var windowWidth = (res.windowWidth - 30)/2;
      var windowWidth = (res.windowWidth - 15) / 2;
      var windowHeight = res.windowHeight / 2;
      var windowscale = windowHeight / windowWidth;//屏幕高宽比 
      if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比 
        //图片缩放后的宽为屏幕宽 
        imageSize.imageWidth = windowWidth;
        imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
      } else {//图片高宽比大于屏幕高宽比 
        //图片缩放后的高为屏幕高 
        // imageSize.imageHeight = windowHeight; 
        // imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight; 
        imageSize.imageHeight = originalHeight * windowWidth / originalWidth;
        imageSize.imageWidth = windowWidth;
      }
    }
  })
  return imageSize;
}

/**
 * 判断用户滑动
 * 左滑还是右滑
 */
function getTouchData(endX, endY, startX, startY) {
  let turn = "";
  if (endX - startX > 50 && Math.abs(endY - startY) < 50) {      //右滑
    turn = "right";
  } else if (endX - startX < -50 && Math.abs(endY - startY) < 50) {   //左滑
    turn = "left";
  }
  return turn;
}

/** 
 * view宽高比
*/
function aspectRatio(h, w) {
  let viewStyle = {}
  let originalScale = h / w
  wxService.getSystemInfo().then(res => {
    let windowscale = res.windowHeight / res.windowWidth
    if (originalScale < windowscale) {
      viewStyle.width = res.windowWidth
      viewStyle.height = (res.windowWidth * h) / w;
    } else {
      viewStyle.width = (res.windowHeight * w) / h
      viewStyle.height = res.windowHeight
    }
  })
  return viewStyle;
}

/** 
 * 解析 url 参数
*/
function parseUrl(query) {
  var result = [];
  // var query = url.split("?")[1];
  var queryArr = query.split("&");
  queryArr.forEach(function (item) {
    var obj = {};
    var value = item.split("=")[0];
    var key = item.split("=")[1];
    obj[value] = key;
    result.push(obj);
  });
  return result;
}


function getCurrentRouter() {
  var pages = getCurrentPages() // 获取加载的页面
  var currentPage = pages[pages.length - 1] // 获取当前页面的对象
  return currentPage
}

function getNowTime() {
  return wxService.getManageDate().getNow()
}

function getAppUserInfo() {
  const app = getApp()
  if (app.globalData.userInfo) {
    return Promise.resolve({ userInfo: app.globalData.userInfo })
  } else {
    return Promise.reject('userinfo is null')
  }
}
/** 邮箱校验 */
function validateEmail(email) {
  let str = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
  return str.test(email)
}


/**
 * 处理分页数据安全加载,渲染
 * 小程序1M的限制
 */
class HandlerDataOnPage {
  init(target, originArrName) {
    if (target && target.data && originArrName) {
      this.target = target.data
      this.OriginArrayName = originArrName
    }
  }

  handlerArray(dataArray = []) {
    const target = this.target
    const arrayName = this.OriginArrayName
    dataArray = dataArray || []
    this.validate()
    if (toString.call(dataArray) !== '[object Array]') {
      throw new Error('dataArray invaild')
    }

    let len = target[arrayName].length
    target[arrayName] = target[arrayName].concat(dataArray)

    return this.trunObject(dataArray, len)
  }

  editArray(dataArray = [], startIndex = -1) {
    if (startIndex < 0) {
      throw new Error('editArray startIndex must > -1')
    }
    return this.trunObject(dataArray, startIndex)
  }

  trunObject(dataArray = [], len) {
    const arrayName = this.OriginArrayName
    function RenderArray2Object() { };
    RenderArray2Object.prototype.keysNum = function () {
      return Object.keys(this).length
    }
    let renderArray2Object = new RenderArray2Object()
    for (let i = 0, s = dataArray.length; i < s; i++) {
      renderArray2Object[`${arrayName}[${len + i}]`] = dataArray[i]
    }
    return renderArray2Object
  }

  validate() {
    const target = this.target; const arrayName = this.OriginArrayName
    target[arrayName] = target[arrayName] || []
    if (!target) {
      throw new Error('target invaild')
    }
    if (!(target[arrayName] && toString.call(target[arrayName]) === '[object Array]')) {
      target[arrayName] = []
    }
  }

  clearOriginArr() {
    const target = this.target; const arrayName = this.OriginArrayName
    this.validate()
    target[arrayName] = []
  }
}

class Logger {
  log() {
    // if (envInfo.env === 'prod') {
    //   return
    // }
    let args = Array.prototype.slice.apply(arguments)

    let params = Array.prototype.slice.apply(arguments)
    const desc = args.shift()
    let tip = `======= ${desc} =======`
    args.forEach(() => {
      tip += ',%o'
    })
    params[0] = tip
    console.log.apply(console, params)
  }
}

// 通过点击按钮 获取用户信息并登陆注册到crm系统中
function getUserInfoByBtn(userInfo) {
  const logger = new Logger()
  const app = getApp()
  if (Object.keys(userInfo).length === 1) {
    return wxService.Promise.reject(userInfo.errMsg)
  }
  return wxService.login().then((res) => {
    logger.log(' wx getUserInfoByBtn success res --->', res)
    return Promise.all([Promise.resolve(userInfo), Promise.resolve(res)])
  }).then((res) => {
    logger.log(' wx _userInfo success res --->', res)
    wx.setStorageSync('_userInfo', res[0].userInfo)
    wx.setStorageSync('_wechatInfo', res[0])
    wx.setStorageSync('reLoginErr', false)
    wx.showLoading({
      title: '正在加载...',
      icon: 'none',
      mask: true
    })
    return wxService.post(`/member/minaLogin`, {
      code: res[1].code,
      wechatInfo: res[0],
      brandId: app.globalData.brandId,
    })
  }, (err) => {
    return Promise.reject(err)
  }).then(response => {
    logger.log('getCrmUserInfo response', response)
    if (response.data.data.rspCode === -1) {
      return Promise.reject(response.data.data)
    }
    return Promise.resolve(response.data.data)
  }).finally(() => {
    wx.hideLoading()
  })
}


const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getSum(preValue,curValue,index, array) {
  return preValue + curValue;
}

function _getUserInfo(ev) {
  const userInfo = ev.detail || ev
  return getUserInfoByBtn(userInfo).then((data = {}) => {
    const { token } = data
    wx.setStorageSync('_accreditUserInfo', userInfo)
    wx.hideNavigationBarLoading()
    if (token) {
      wx.setStorageSync('token', token)
    } else {
      wx.setStorageSync('token', '')
    }
    wx.setStorageSync('_baseUserInfo', data) // 缓存用户信息
    setUserInfo()   // 判断有无开卡
  }).catch(err => {
    if (err) {
      console.log('err', err)
      wx.showToast({
        title: `您已拒绝授权!`,
        icon: 'none'
      })
    }
  })
}
function setUserInfo() {
  const userInfo = wx.getStorageSync('_baseUserInfo')
  // 新用户去激活领卡 
  if (userInfo && userInfo.member && !userInfo.member.mobile) {
    console.log('去开')
    wxService.openCard()
    return false
  } else {
    console.log('已开')
  }
  // 跳转
  const urls = getCurrentPages()
  setTimeout(() => {
    const item = urls[0].options
    const route = urls[0].route
    console.log('----------item', route, item)
    if (route) {
      try {
        const options = item
        wxService.router(`/${route}`).search(options).replace()
      } catch (e) {
        wxService.router('/pages/userCenter/userCenter').replace()
      }
    } else {
      wxService.router('/pages/userCenter/userCenter').replace()
    }
  }, 200)
}

wxService.setGetAuthUserInfo(_getUserInfo);

module.exports = {
  _getUserInfo,
  formatTime,
  getSum,
  getCurrentPageUrl,
  getCurrentRouter,
  getCurrentPageUrlWithArgs,
  getNowTime,
  getUserInfoByBtn,
  moment,
  parseUrl,
  _,
  // _: underscore,
  HandlerDataOnPage,
  formatTime: formatTime,
  formatDate,
  getAppUserInfo,
  formatNumber: formatNumber,
  logger: new Logger(),
  getTouchData,
  getAccountInfo,
  aspectRatio,
  imageUtil,
  validateEmail
}
