require('./uni-bootstrap.js');
import bus from './utils/eventbus'
import {
  _ACTIVITY_INFO_KEY,
  _ACTIVITY_PERIOD_DIALOG_KEY
} from './utils/global-key'
import { _GLOBAL_CART_KEY } from './utils/index'
const Base64 = require('./utils/base64')
// 环境变量
import envNameConfig from './env'
// const envNameConfig = require('./env').default
require('./utils/util')
require('./utils/log')
require('./utils/router')
var amap = require('./src/js/amap-wx.js')
const { fhGetUserInfo } = require('./api/auth/index.js')
const {
  fhGetHospitalAddress,
  fhGetPatientInfo
} = require('./api/hospital/index')
import {
  fhGetRemoteVisitsSetting,
  fhPutPatientRecord
} from './api/remote/index'
import request from './src/js/request'
import { fhGetHospitalMes } from './api/newborn/index'
import { sceneDecode } from './utils/util'

// 版本号
const _VERSION = '1.2.0'

function Loading(title = '正在加载') {
  wx.showLoading({
    title,
    mask: true
  })
}

function hLoading() {
  wx.hideLoading()
}

App({
  onLaunch: async function () {
    // 检查更新
    this.checkUpdate()
  },
  onShow({ query }) {
    console.log(query, '🤣🤣🤣🤣传进来的');
    this.initLoad(query, 'query')
    // 自定义导航相关的信息
    this.getNavBarInfo()
  },

  async initLoad(query) {
    let isQrcodeEnter = false
    let envInfo = wx.$env.env
    const bingfangId = 0
    if (query.scene) {
      if (query.scene.includes('rid-')) {
        const { rid } = sceneDecode(query.scene)
        const { results } = await request({
          url: `/nurse/client/hospitalization-record/${rid}`
        })
        const value = {
          sickroomId: +results.sickroomId,
          bedNumber: results.bedNumber,
          env: envInfo
        }
        this.setHospitalInfo()
        this.globalData.hospitalInfo = value
        wx.setStorageSync('hospital-info', value)
        wx.setStorageSync(
          'hospital-scene',
          Base64.encode(`${+value.sickroomId}#${value.bedNumber}#${envInfo}`)
        )
      } else if (query.scene.includes('newborn')) {
        // 新生儿短链进入
        console.log('🤣🤣🤣🤣🤣🤣短链进入的')
        console.log(query, '🤣🤣🤣🤣传进来的');
        wx.setStorageSync('hospitalFlag', true)
        const { hid, id } = sceneDecode(query.scene)
        console.log(hid, '/hid');
        console.log(id, '/id');
        const value = { hospitalId: hid }
        wx.setStorageSync('hospital-info', value)
        this.getHospitalMes(hid)
        // wx.setStorageSync('msgFlag', true)
      }
      else {
        if (query.scene.includes('hhs-')) {
          this.globalData.hospitalScene = query.scene.split('hhs-')[1]
        } else {
          this.globalData.hospitalScene = query.scene
          isQrcodeEnter = true
        }
        const res =
          (await this.decodeInfo({ scene: this.globalData.hospitalScene })) ||
          {}
        envInfo = res.env
        wx.setStorageSync('hospital-info', res)
        wx.setStorageSync('hospital-scene', this.globalData.hospitalScene)
        // 新生儿 
        res.hospitalFlag ? wx.setStorageSync('hospitalFlag', true) : wx.setStorageSync('hospitalFlag', false)
        this.setHospitalInfo(res)
      }
    } else {
      if (query.bingfangId === 'null') {
        query.bingfangId = null
      }
      // 家属代点餐跳转逻辑
      if (!wx.getStorageSync('hospital-info') && !query.bedNumber) {
        wx.redirectTo({
          url: '/store/pages/hospital/index'
        })
        return
      }
      const value = wx.getStorageSync('hospital-info') || {
        sickroomId: +query.sickroomId,
        sickareaId: +query.sickareaId,
        bingfangId: query.bingfangId || bingfangId,
        // 从家属代点单进入小程序若存在query.bedNumber则赋值,否则默认1床
        bedNumber: query.bedNumber || '1床',
        env: envInfo
      }
      // this.globalData.hospitalScene = Base64.encode(
      //   `${+value.sickroomId}#${value.bedNumber}#${envInfo}`
      // )
      // wx.setStorageSync('memberId', query.patientId)
      wx.setStorageSync('msgFlag', true)
      this.setHospitalInfo(value)
    }
    await this.getStorage()
    // await this.clearStorage()
    if (!wx.getStorageSync('hospitalFlag')) {
      const { addressTitle } = await this.getHospitalAddress()
      this.globalData.addressTitle = addressTitle
    }


    const memberId = wx.getStorageSync('memberId')
    !memberId ? await this.login() : await this.fhGetPatientInfo()
    isQrcodeEnter && (wx.getStorageSync('hospitalFlag') ? null : this.updateRecord())
  },

  // 解密扫码进入小程序携带的信息
  decodeInfo(query) {
    // query= 'WXYijaSdsGc'
    return new Promise((resolve, reject) => {
      let { scene } = query
      let sickroomId = 28
      let bedNumber = '0001床'
      let env = 'dev'
      let sickareaId = null
      let bingfangId = null
      if (scene) {
        if (scene.includes('%')) {
          scene = decodeURIComponent(scene)
          console.log('info decodeURIComponent for scene', scene)
        }
        if (!scene.includes('#')) {
          scene = Base64.decode(scene)
          console.log('info Base64.decode for scene', scene)
          // 医院二位码进入
          if (scene.includes('@')) {
            wx.setStorageSync('hospitalFlag', true)
            const arr = scene.split('#')
            const acc = arr[1].split('@')
            this.getHospitalMes(acc[0])
            const value = { hospitalId: acc[0], hospitalFlag: true }
            wx.setStorageSync('hospital-info', value)
            resolve(value)
            return
          }
        }

        if (scene.includes('#')) {
          const active = scene.split('#')
          console.log('info split(#) for active')
          const sickroomIdIndex = active[0].indexOf('s')
          const wardIndex = active[0].indexOf('a')
          const bingfangIndex = active[0].indexOf('b')
          // 网签二维码有 sab
          const hasSAB = !!(
            ~active[0].indexOf('s') &
            ~active[0].indexOf('a') &
            ~active[0].indexOf('b')
          )
          console.log('info 网签SAB', hasSAB)
          // 科室id
          sickroomId = active[0].slice(sickroomIdIndex + 1, wardIndex)
          sickroomId = hasSAB ? sickroomId : active[0]
          // 病区id
          sickareaId = active[0].slice(wardIndex + 1, bingfangIndex)
          sickareaId = hasSAB ? sickareaId : active[1]
          // 病房id
          bingfangId = hasSAB ? active[0].slice(bingfangIndex + 1) : 0
          // 病房不需要 bingfangId = hasSAB ? bingfangId : active[0]
          bedNumber = active[1]
          bedNumber = hasSAB ? bedNumber : active[2]
          env = active[2]
          env = active[active.length - 1]
          // 修复bug
          if (hasSAB) {
            // 如果是网签则拿下标为1的作为床位号
            bedNumber = active[1]
          } else {
            // 长度为3说明没有病房号，只需要取病床号
            if (active.length == 4) {
              bedNumber = active[2]
            }
            // 长度为4说明有病房号
            if (active.length == 5) {
              bingfangId = active[2]
              bedNumber = active[3]
            }
          }
          console.log('info pick active params', {
            sickroomId,
            sickareaId,
            bingfangId,
            bedNumber,
            env
          })
        }
      } else {
        const temp = wx.getStorageSync('hospital-info') || {}
        sickroomId = temp.sickroomId || sickroomId
        bedNumber = temp.bedNumber || bedNumber
        env = temp.env || env
      }

      const res = {
        sickroomId: +sickroomId,
        bedNumber,
        sickareaId: +sickareaId,
        bingfangId: +bingfangId,
        env
      }
      wx.setStorageSync('hospital-info', res)
      this.setHospitalInfo(res)
      resolve(res)
    })
  },
  /**
     * 获取医院信息
     *
     */
  async getHospitalMes(hospitalId) {
    console.log('🐱‍👤🐱‍👤🐱‍👤')
    try {
      const { results } = await fhGetHospitalMes(hospitalId)
      wx.setStorageSync('exactaddress', results.hospitalName)
    } catch (e) {
      return Promise.reject(e)
    }
  },
  // 获取医院相关信息
  getHospitalInfo() {
    return (
      this.globalData.hospitalInfo || wx.getStorageSync('hospital-info') || {}
    )
  },

  /**
   * 存储进入获取到的医院相关的信息
   * @param {Object} value 需要存入的数据，必须是对象类型
   */
  setHospitalInfo(value) {
    const temp = this.getHospitalInfo()
    const res = {
      ...temp,
      ...value
    }
    wx.setStorageSync('hospital-info', res)
    this.globalData.hospitalInfo = res
  },

  // 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
  onShareAppMessage() {
    const title = '医便民'
    const path = ''
    const imageUrl = ''

    return {
      title,
      path,
      imageUrl
    }
  },

  Tips(title, option = {}) {
    wx.showToast(
      Object.assign(
        {
          title,
          mask: true,
          icon: 'none'
        },
        option
      )
    )
  },

  // 获取胶囊相关信息
  getNavBarInfo() {
    try {
      if (this.retryNavInfoTimer) {
        clearInterval(this.retryNavInfoTimer)
        this.retryNavInfoTimer = null
      }
      // 获取系统信息
      const systemInfo = wx.getSystemInfoSync() || {}
      // 胶囊按钮位置信息
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect() || {}
      wx.$log.info(
        `进入小程序获--取系统信息：${JSON.stringify(
          systemInfo
        )}；获取胶囊位置信息：${JSON.stringify(menuButtonInfo)}`
      )

      const defaultMenuHeight = 32
      const defaultStatusBarHeight = 44
      const defaultBarHeight = 86
      const defaultMenuTop = 48

      const { top, height, right, bottom, left } = menuButtonInfo
      const { screenWidth, statusBarHeight, safeArea, screenHeight } =
        systemInfo
      if (safeArea && safeArea.bottom) {
        const { height } = safeArea
        this.globalData.safeArea = {
          ...safeArea,
          unsafeHeight: screenHeight - height
        }
      }

      // 导航栏高度 = 状态栏到胶囊的间距（胶囊距上距离-状态栏高度） * 2 + 胶囊高度 + 状态栏高度
      const navBarHeight =
        (top - statusBarHeight) * 2 + height + statusBarHeight
      const menuRight = screenWidth - right
      const menuBotton = top - statusBarHeight
      const menuHeight = height || defaultMenuHeight
      const menuTop = top || defaultMenuTop
      const menuLeft = left

      // 旧的方法
      const CustomBar = bottom + top - statusBarHeight

      const barheight = CustomBar || defaultBarHeight
      const statusHeight = statusBarHeight || defaultStatusBarHeight

      const results = {
        navBarHeight:
          typeof navBarHeight === 'string' ? defaultBarHeight : navBarHeight,
        menuRight,
        menuBotton,
        menuHeight,
        menuTop,
        barheight,
        height: statusHeight,
        menuLeft
      }
      this.globalData = {
        ...this.globalData,
        ...results
      }

      wx.$log.info(
        `进入小程序获--取系统信息：${JSON.stringify(
          systemInfo
        )}；获取胶囊位置信息：${JSON.stringify(
          menuButtonInfo
        )}；计算结果：${results}`
      )

      // 标记获取胶囊信息结束
      this.globalData.navBarFlag = true
    } catch (e) {
      console.error('error', e)
      wx.$log.error(`计算自定义导航栏报错：${e}`)
      this.retryNavInfoTimer = setInterval(() => {
        this.getNavBarInfo()
      }, 500)
    }
  },

  // 获取环境变量配置
  getEnvConfig() {
    return this.globalData.envConfig || {}
  },

  // 查询更新信息
  checkUpdate() {
    // 版本更新提示
    wx.getUpdateManager().onCheckForUpdate(res => {
      if (res.hasUpdate) {
        // 如果有新版本
        // 小程序有新版本，会主动触发下载操作（无需开发者触发）
        wx.getUpdateManager().onUpdateReady(() => {
          // 当新版本下载完成，会进行回调
          wx.showModal({
            title: '更新提示',
            content: '新版本已更新，请重启应用',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.getUpdateManager().applyUpdate()
              }
            }
          })
        })
      }
    })
  },

  // 进入获取本地存储的内容，存在globalData中
  getStorage() {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token')
      const storeId = wx.getStorageSync('storeid')
      const merchantId = wx.getStorageSync('merchantid')
      const memberId = wx.getStorageSync('memberId')

      const res = {
        token,
        storeId,
        merchantId,
        memberId
      }

      this.globalData.baseInfo = res

      resolve(res)
    })
  },

  // 清理部分临时保存的storage
  clearStorage() {
    return new Promise((resolve, reject) => {
      wx.setStorageSync(_ACTIVITY_INFO_KEY, {})
      wx.setStorageSync(_ACTIVITY_PERIOD_DIALOG_KEY, false)
      wx.setStorageSync(_GLOBAL_CART_KEY, [])
      resolve()
    })
  },

  // 监听globalData
  watch(key, method) {
    const obj = this.globalData
    // 加个前缀生成隐藏变量，防止死循环发生
    const ori = obj[key] // obj[key]这个不能放在Object.defineProperty里

    if (ori) {
      // 处理已经声明的变量，绑定处理
      method(ori)
    }
    Object.defineProperty(obj, key, {
      configurable: true, // 属性是否可以被删除或者可否被重新定义特性
      enumerable: true, // 是否可以被枚举,简单讲就是在使用Object.keys()时，是否能拿到键值
      set: value => {
        this['_' + key] = value
        method(value) // 数据有变化的时候回调函数，实现同步功能
      },
      get: () => {
        // 在其他界面调用key值的时候，这里就会执行。
        if (typeof this['_' + key] === 'undefined') {
          if (ori || ori === '') {
            // 这里读取数据的时候隐藏变量和 globalData设置不一样，所以要做同步处理
            this['_' + key] = ori
            return ori
          } else {
            return undefined
          }
        } else {
          return this['_' + key]
        }
      }
    })
  },

  // 新版登录
  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          const { code } = res
          if (code) {
            this.getUserInfo({ code }, resolve, reject)
          }
        },
        fail(e) {
          console.log('debug error', e)
          reject(Error(e))
        }
      })
    })
  },

  // 获取用户信息
  async getUserInfo(data, resolve, reject) {
    try {
      const { results } = await fhGetUserInfo(data)
      if (results) {
        const { mobile, token, memberId, openId } = results || {}

        token && wx.setStorageSync('token', token)
        openId && wx.setStorageSync('openid', openId)

        if (memberId) {
          wx.setStorageSync('memberId', memberId)
          this.fhGetPatientInfo()
        } else {
          this.globalData.patientInfo = { id: null }
        }
        wx.setStorageSync('btnflag', !memberId)

        if (mobile) {
          wx.setStorageSync('auth-phone', mobile)
        }
        wx.setStorageSync('anflag', !mobile)
        wx.setStorageSync('phoneflag', !!mobile)

        resolve && resolve()
      } else {
        wx.setStorageSync('phoneflag', false)
        wx.setStorageSync('btnflag', true)
        wx.setStorageSync('anflag', true)
        this.globalData.isLoginEd = false
        this.globalData.patientInfo = { id: null }
        reject && reject(Error('未知用户'))
      }
    } catch (e) {
      wx.setStorageSync('phoneflag', false)
      wx.setStorageSync('btnflag', true)
      wx.setStorageSync('anflag', true)
      this.globalData.isLoginEd = false
      this.globalData.patientInfo = { id: null }
      console.error('debug axios', e)
      reject && reject(Error(e))
    }
    if (wx.getStorageSync('msgFlag')) {
      bus.emit('refeshLogin', { flag: true })
    }
  },

  // 获取医院信息
  async getHospitalAddress() {
    try {
      const { sickroomId = 1, bedNumber = '' } = this.getHospitalInfo()
      const { results } = await fhGetHospitalAddress({
        hospitalId,
        sickroomId,
        bedNumber: bedNumber
      })
      const { latitude, longitude, poiName, hospitalId } = results
      wx.setStorageSync('latitude', latitude)
      wx.setStorageSync('longitude', longitude)
      wx.setStorageSync('exactaddress', poiName)
      this.globalData.hospitalAddress = results
      this.setHospitalInfo({ hospitalId })
      bus.emit('loadHospitalInfoEnd', { flag: true })

      wx.getStorageSync('hosppitalFlag') ? null : this.getRemoteVisitsSetting(hospitalId, sickroomId)

      return { addressTitle: poiName }
    } catch (e) {
      console.log('debug axios: ', e)
      return { addressTitle: null }
    }
  },

  // 获取患者信息
  async fhGetPatientInfo() {
    try {
      const { results } = await fhGetPatientInfo()
      this.globalData.patientInfo = results || { id: null }
    } catch (e) {
      console.log('debug axios', e)
    }
  },

  // 获取医院远程探视的配置
  async getRemoteVisitsSetting(hospitalId, sickroomId) {
    try {
      const { results } = await fhGetRemoteVisitsSetting(hospitalId, sickroomId)
      this.globalData.remoteSetting = results
    } catch (e) {
      console.log('debug axios', e)
    }
  },

  // 更新患者记录
  async updateRecord() {
    const memberId = wx.getStorageSync('memberId')
    const info = wx.getStorageSync('hospital-info')
    try {
      const { results } = await fhPutPatientRecord(
        {},
        memberId,
        info.hospitalId
      )
      this.globalData.patientInfo.lastSickroomName = results.sickroomName
      return results
    } catch (error) {
      return error
    }
  },

  // 获取当前授权用户的memberId
  getMemberId() {
    return this.globalData?.baseInfo?.memberId || null
  },

  Loading,
  hLoading,
  bus,

  globalData: {
    baseInfo: null,
    memberId: '5',
    isLoginEd: false,
    userInfo: null,
    userid: null,
    count: 0,
    token: null,
    apply: false,
    scene: null,
    appid: '',
    btnflag: true,
    phoneflag: false,
    anflag: true,
    shareImageUrl: '',
    shareCode: '',
    height: 0,
    leave: 0,
    platformCouponInfo: {},
    // 加入购物车的特惠商品
    preferentialFoods: {},
    // 和胶囊相关的数据
    barheight: 84,
    navBarHeight: 84, // 导航栏高度
    menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
    menuBotton: 4, // 胶囊距底部间距（保持底部间距一致）
    menuHeight: 32, // 胶囊高度（自定义内容可与胶囊高度保证一致）
    menuTop: 48, // 胶囊距底部间距（保持底部间距一致）
    menuLeft: 320,
    familyMemberId: 4, // 家属ID
    // 版本号
    version: _VERSION,
    host: 'https://api.yibianmin.lz517.cn/',
    // 患者信息
    Form: null,
    safeArea: {},
    // 医院信息
    hospitalInfo: {},
    // 患者家属信息
    familyMemberInfo: null,
    // 类型
    memberType: 'PATIENT',
    // 远程探视id
    id: null,
    // 患者详情
    patientInfo: null,
    // 远程探视房间信息
    remoteInfo: null,
    // 远程探视配置
    remoteSetting: null,
    // 签署讲解支付设置：1.线上沟通前可支付，2，线上沟通后可支付
    paymentSetting: null,
    // 参与方可提前多少分钟进入
    advanceTime: null

  },

  data: {
    amap: amap,
    key: 'e70024fc157c30072966dd2d838bcb97'
  }
})
