const Promise = require('../lib/bluebird')
let c1C2Map = {}
let c2C3Map = {}
export function handler2citys ({
  city,
  result,
  list
}) {
  const len = Object.keys(city).length
  let res = {
    name: [...result.name],
    code: [...result.code]
  }
  let name = city.name
  let arginName = res.name.join('') // 原城市名
  res.name.push(name)
  res.code.push(city.code)
  if (res.code.length === 2) {
    const pName = res.name.join('###')
    const code = res.code.join('')
    list[`${pName}`] = `${code}`
    if (!c1C2Map[arginName]) {
      c1C2Map[arginName] = new Set()
    }
    c1C2Map[arginName].add(name)
  }
  if (len > 2) {
    for (const key in city) {
      if (city.hasOwnProperty(key) && key !== 'name' && key !== 'code') {
        const element = city[key]
        handler2citys({
          city: element,
          result: res,
          list
        })
      }
    }
  } else {
    const pName = res.name.join('###')
    const code = res.code.join('')
    list[`${pName}`] = `${code}`
    if (!c2C3Map[arginName]) {
      c2C3Map[arginName] = new Set()
    }
    c2C3Map[arginName].add(name)
  }
}

export function getC1 () {
  return new Promise((resolve, reject) => {
    let keys = Object.keys(c1C2Map)
    if (keys.length) {
      resolve(keys)
    } else {
      reject('c1C2Map is empty object')
    }
  })
}

export function getC2 (c1Name) {
  return new Promise((resolve, reject) => {
    let keys = c1C2Map[c1Name]
    if (keys) {
      resolve(keys)
    } else {
      reject('c1C2Map is empty object')
    }
  })
}

export function getC3 (c2Name) {
  return new Promise((resolve, reject) => {
    let keys = c2C3Map[c2Name]
    if (keys) {
      resolve(keys)
    } else {
      reject('c2C3Map is empty object')
    }
  })
}

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

export function getAppUserInfo () {
  const userInfo = wx.getStorageSync('_userInfo')
  if (userInfo) {
    return Promise.resolve({ userInfo })
  } else {
    return Promise.reject(new Error('userinfo is null'))
  }
}


export default {
  c1C2Map,
  c2C3Map
}

export function checkOpenCard () {
  const baseUserInfo = wx.getStorageSync('_baseUserInfo')
  let isMember = '0'
  if (baseUserInfo && baseUserInfo.isMember === '1') {
    isMember = '1'
  }
  const pass = isMember === '1'
  return pass
}
