import {
  getAppUserInfo,
  getC1,
  getC2,
  getC3,
  handler2citys,
  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'
const citysData = require('./city.js')
import { Integer } from './integerDigitalConvertion'

let openCardLister = null

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

  getToken() {
    return super.getToken()
  }
  setGetAuthUserInfo(getAuthUserInfo) {
    this.getAuthUserInfo = getAuthUserInfo;
  }

  /**
   * 所有接口中返回401就登录
   * 返回402 重试 （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) {
      //   // 判断是否登陆过 登陆过 重新登陆 未登陆 跳转首页
      //   const baseUserInfo = this.getBaseUserInfo()
      //   if(!baseUserInfo) {
      //     wxService.router('/pages/userCenter/userCenter').replace()
      //     return false
      //   }
      //   // 条件限制  getUserInfoLimitCount：重试次数
      //   if (!this.getUserInfoLimitCount) {
      //     this.getUserInfoLimitCount = 1
      //   } else {
      //     this.getUserInfoLimitCount++
      //   }
      //   if (this.getUserInfoLimitCount > 3) {
      //     wx.showToast({
      //       title: '登录超出重试次数!',
      //       icon: 'none'
      //     })
      //     wxService.router(`/pages/userCenter/userCenter`).replace()
      //     return false
      //   } else {
      //     // 重新登陆 更新缓存
      //     this.reLogin()
      //   }

      //   setTimeout(()=>{
      //     const pages = getCurrentPages()
      //     const perpage = pages[pages.length - 1]
      //     perpage.onShow()
      //   },2000)

      // }
      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 {
          // 重新登陆之前判断是否登陆过 重新登陆
          const baseUserInfo = this.getBaseUserInfo()
          if (baseUserInfo) {
            // this.reLogin()
            return false
          }
        }
      } else if (res.msg && res.msg.indexOf('请重新授权') > -1) {
        wx.setStorageSync('reLoginErr', true)
        wxService.router(`/pages/userCenter/userCenter`).back()
      }
    })
  }

  // 所有页面都有接口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', '')
    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)
            
            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()
    })
  }

  //生成触点对象Id
  getTentacleContent(tentacleInfo) {
    console.log('生成触点对象Id', 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
      let TENTACLE_CONTENT = {
        id: data.id,
        tentacleType: data.type,
        tentacleId: data.tentacleId,
        contentType: data.contentType,
        contentId: data.contentId
      }

      let storageObj = {
        memberId: '',
        obj: 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(() => {

    })
  }
  //根据页面类型判断content取值
  getContentByContentType(item) {
    //1,2,3,8,9,10,11 页面  取页面标题
    if (item.contentType == 1 || item.contentType == 2 || item.contentType == 3 || item.contentType == 8 || item.contentType == 9 || item.contentType == 10 || item.contentType == 11) {
      item.content = item.content
    }
    // 详情
    if (item.contentType == 4 || item.contentType == 6) {
      let content = JSON.parse(item.content)
      item.contentArr = [content]
    }
    // 内容列表
    if (item.contentType == 5) {
      if (item.contentId) {
        let content = JSON.parse(item.content)
        item.contentArr = [content]
      } else {
        item.content = item.content
      }
    }
    // 推广列表
    if (item.contentType == 7) {
      if (item.contentId) {
        let content = JSON.parse(item.content)
        item.contentArr = content
      } else {
        item.content = item.content
      }
    }
  }

  //更新本地触点对象信息
  updateLocalTentacleInfo() {
    //先获取本地触点对象信息
    let tentacleInfo = wx.getStorageSync('TENTACLE_CONTENT');
    //获取从种草详情商品购买时存储的临时触点对象信息
    let tempTentacleInfo = wx.getStorageSync('TEMP_TENTACLE_INFO');
    //格式 
    /**
     * tempTentacleInfo = {
     *  memberId : '',
     *  obj : {}
      }
     * 
     */
    //判断tentacleInfo是否为空
    if (!tentacleInfo) {
      wx.setStorageSync('TENTACLE_CONTENT', tempTentacleInfo);
      return;
    }
    //tentacleInfo 不为空
    //判断先获取本地触点对象信息 中memberid 是否为空
    let memberId = tentacleInfo.memberId;
    // 若memberId 为空 表示从分享过来的链接 此时不能更新wx.getStorageSync('TENTACLE_CONTENT') 信息
    if (!memberId) {
      return;
    }

    //不为空 则表示 之前从种草详情中的商品直接购买过 直接更新本地TENTACLE_CONTENT
    wx.setStorageSync('TENTACLE_CONTENT', tempTentacleInfo);
  }

  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) => {

        }
      })
    })
  }

  getNavBarBackGroundColor(fc, bgc) {
    wx.setNavigationBarColor({
      frontColor: fc,
      backgroundColor: bgc,
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  }

  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()
    })
  }


  // 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]
    }
  }

  page(config) {
    const _self = this
    // 当前是否有用户信息
    config.data.currentHasUserInfo = false;
    // 当前页面是否需要授权
    config.data.currentPageRequireAuth = false;

    const CONFIG_PAPGE = {
      onLoad: function (...args) {
        const page = this
        _self.initAppGlobalDataSync()
        //修改参数
        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);
            }
          }
        });
        //如果打开的是分享界面则进行触点对象信息请求并存储到本地 放到后续的header中
        if (pageIsFromShare) {
          //调用接口
          _self.getTentacleContentByTentacleId(id);
        }

        config.onLoad && config.onLoad.apply(page, args);
      },
      onShow: function (...args) {
        const page = this
        _self.currentPage = page
        config.onShow && config.onShow.apply(page, args)
        const baseUserInfo = wx.getStorageSync('_baseUserInfo')
        if (baseUserInfo) {
          page.setData({
            currentHasUserInfo: true
          });
        } else {
          page.setData({
            currentHasUserInfo: false
          });
        }
      },
      onReady: function (...args) {
        config.onReady && config.onReady.apply(this, args)
      },
      onHide: function (...args) {
        const page = this
        config.onHide && config.onHide.apply(this, args)
        // page.setData({
        //   currentHasUserInfo: false
        // });
      },
      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)
          }
        }
      },
      //统一处理用户授权获取用户信息回调
      _getUserInfo(res) {
        _self.getAuthUserInfo(res.detail)
      },
      //处理分享页面打开时参数为memberId时生成触点对象信息
      generatePointObject(tentacleInfo){
        console.log('---call 生成触点接口----')
        console.log(tentacleInfo)

        _self.getTentacleContent(tentacleInfo).then(res => {
          console.log('-----处理分享页面打开时参数为memberId时生成触点对象信息------')
          console.log('-----成功返回是------',res);
          if (res && res.tentacleId) {
            let data = res;
            let TENTACLE_CONTENT = {
              id: data.id,
              tentacleType: data.type,
              tentacleId: data.tentacleId,
              contentType: data.contentType,
              contentId: data.contentId
            }

            let storageObj = {
              memberId: '',
              obj: 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')
            }

          }
        });
      },
    }
    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('已开卡', baseUserInfo)
        wxService.openCardList()
        resolve(baseUserInfo)
      } else if (!baseUserInfo || !baseUserInfo.memberActivateStatus) {
        console.log('去开卡', baseUserInfo)
        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
    })
  }

  getCitysEnterty() {
    const citys = citysData
    let list = {}
    if (this.citysEntertys) {
      list = this.citysEntertys
    } else {
      for (const key in citys) {
        if (citys.hasOwnProperty(key)) {
          const element = citys[key]
          handler2citys({
            city: element,
            result: { name: [], code: [] },
            list
          })
        }
      }
    }
    return list
  }

  getC1() {
    return getC1().then((res) => {
      return res
    }).catch(() => {
      if (this instanceof WXService) {
        this.getCitysEnterty()
      } else {
        const wxService = new WXService()
        wxService.getCitysEnterty()
      }
      return getC1().then((res) => {
        return res
      })
    })
  }

  getC2ByC1(c1Name) {
    return getC2(c1Name).catch(() => {
      if (this instanceof WXService) {
        this.getCitysEnterty()
      } else {
        const wxService = new WXService()
        wxService.getCitysEnterty()
      }
      return getC2(c1Name)
    })
  }

  getC3ByC2(c2Name) {
    return getC3(c2Name).catch(() => {
      if (this instanceof WXService) {
        this.getCitysEnterty()
      } else {
        const wxService = new WXService()
        wxService.getCitysEnterty()
      }
      return getC3(c2Name)
    })
  }

  getCityCode(c1, c2, c3) {
    function getKey(...args) {
      return args
        .join('###')
    }
    const key = getKey(c1, c2, c3)
    let result = ''
    let list = {}
    if (this instanceof WXService) {
      list = this.getCitysEnterty()
    } else {
      const wxService = new WXService()
      list = wxService.getCitysEnterty()
    }
    result = list[key]
    return result
  }

}

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