const baseUrl = require('../../api/index').config
const store = require('../../api/order.js')
const { _AUTH_PHONE_KEY } = require('../../utils/global-key')

const { compareVersion } = require('../../utils/util')
const { fhPutInfo} = require('../../api/hospital/index.js')
import { fhIsVerityPatientVerty } from '../../api/sign/index'
const { Loading, Tips, bus, hLoading } = getApp()
const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true
  },
  properties: {
    visible: {
      type: Boolean,
      value: false,
      observer() {
        this.init()
      }
    },
    isPage: {
      type: Boolean,
      value: false
    }
  },
  // 组件数据
  data: {
    isPageHidden: false, // 页面是否处于隐藏状态
    btnflag: false,
    phoneflag: false,
    // 动画
    animationData: null,
    // 是否有新版授权的能力
    canIUseGetUserProfile: false
  },
  // 组件方法
  methods: {
    init(data = {}) {
      this.tempDetail = data
      this.animation = wx.createAnimation({
        duration: 600
      })
      this.setData(
        {
          btnflag: wx.getStorageSync('btnflag'),
          phoneflag: wx.getStorageSync('phoneflag')
        },
        () => {
          const { btnflag } = this.data
          if (!btnflag) {
            this.scrollX('-100%')
          }
        }
      )
    },
    // 滑动效果
    scrollX(x) {
      this.setData({
        animationData: this.animation.translateX(x).step().export()
      })
    },
    // 获取用户信息
    getUserProfile(e) {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
      // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: res => {
          this.authUserInfo(res)
        }
      })
    },
    // 获取用户信息
    bindGetUserInfo: function (e) {
      //接下来写业务代码
      wx.getUserInfo({
        success: rawUserInfo => {
          this.authUserInfo(rawUserInfo)
        },
        fail(err) {
          console.log('auth Error:', err)
          hLoading()
        }
      })
    },
    // 授权信息
    authUserInfo(rawUserInfo) {
      Loading()
      wx.login({
        success: res => {
          const { code } = res
          const accountInfo = wx.getAccountInfoSync()
          var appId = accountInfo.miniProgram.appId

          const sendData = {
            ...rawUserInfo,
            code,
            appId
          }

          wx.request({
            url:
              wx.$unienv.VUE_APP_BASE_API +
              baseUrl.unionUrl +
              '/mini-users/auth-user-info',
            method: 'POST',
            data: sendData,
            header: {
              'content-type': 'application/json'
            },
            success: data => {
              const { results } = data.data
              if (data.data.code == 200) {
                const { openId, memberId, token,nickName,avatarUrl } = results || {}
                wx.setStorageSync('token', token)
                wx.setStorageSync('openid', openId)
                wx.setStorageSync('memberId', memberId)
                wx.setStorageSync('phoneflag', true)
                wx.setStorageSync('btnflag', false)
                wx.setStorageSync('avatar-name', {nickName,avatarUrl})
                if(wx.getStorageSync('memberId')) {
                  console.log(111)
                  this.handleAuthedIdent()
                  if(!wx.getStorageSync('hospitalFlag')) this.putInfo()
                }
                this.scrollX('-100%')
                getApp().getStorage()

                getApp().fhGetPatientInfo()

                hLoading()
              } else if (data.data.code == 2002) {
                wx.showToast({
                  title: data.data.message,
                  duration: 1000,
                  mask: true,
                  icon: 'none',
                  success: function () {
                    setTimeout(function () {
                      wx.redirectTo({
                        url: '/pages/empty/empty'
                      })
                    }, 2000)
                  }
                })
              } else if (data.data.code == 520) {
                wx.showToast({
                  title: data.data.message,
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: data.data.message,
                  icon: 'none'
                })
                wx.hideLoading()
              }
            }
          })
        },
        fail: function () {
          Tips('授权出错，请重试')
        }
      })
    },
    /**
     * 扫码登录时编辑患者住院信息
     *
     */
     async putInfo() {
       try{
         const memberId = wx.getStorageSync('memberId')
         const { hospitalId } = wx.getStorageSync('hospital-info')
         await fhPutInfo(
          memberId,
          hospitalId
        )
       } catch (e) {
        console.log('debug axios: ', e)
      }
     },
     /***
    * 患者是否认证过
    */
  async handleAuthedIdent() {
    wx.showLoading({ title: "正在加载中", mask: true })
    try {
      const params = {
        patientId: wx.getStorageSync('memberId')
      }
      const {
        results
      } = await fhIsVerityPatientVerty(params);
      wx.setStorageSync('authedFlag', results)
    } catch (e) {
      console.log(e)
    } finally {
      wx.hideLoading()
    }
  },
    // 获取手机号
    getPhoneNumber: function (e) {
      const { isPage } = this.data
      var that = this
      Loading()
      wx.login({
        success: function (res) {
          //res.code
          that.setData({
            code: res.code
          })
          var openid = wx.getStorageSync('openid')
          const accountInfo = wx.getAccountInfoSync()
          var appid = accountInfo.miniProgram.appId
          store.takePhone(
            wx.$unienv.VUE_APP_BASE_API +
              baseUrl.unionUrl +
              '/mini-users/auth-user-phone',
            {},
            {
              appId: appid,
              code: that.data.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              shareManCardNo: that.data.shareManCardNo,
              activityType: that.data.activityType,
              openId: openid
            },
            '加载中',
            function (res) {
              if (res.code == 200) {
                wx.setStorageSync('memberId', res.results.memberId)
                wx.setStorageSync('token', res.results.token)
                wx.setStorageSync('phoneflag', false)
                wx.setStorageSync('btnflag', false)
                wx.setStorageSync('anflag', false)
                wx.setStorageSync(_AUTH_PHONE_KEY, res.results.phoneNumber)
                getApp().getStorage()
                getApp()
                  .updateRecord()
                  .then(() => {
                    isPage
                      ? wx.navigateBack({
                          delta: 1
                        })
                      : bus.emit(
                          'onNeedAuth',
                          Object.assign({}, that.tempDetail, {
                            show: false,
                            authFlag: true
                          })
                        )
                  })
              }
              wx.hideLoading()
            },
            function (err) {
              Tips('授权手机出错，请重试')
            }
          )
        },
        fail(err) {
          console.log('login error', err)
          hLoading()
        }
      })
    }
  },
  // 生命周期
  lifetimes: {
    attached() {
      const { SDKVersion } = wx.getSystemInfoSync()

      if (
        wx.getUserProfile &&
        compareVersion(SDKVersion, '2.14.1') &&
        compareVersion(SDKVersion, '2.15.0')
      ) {
        this.setData({
          canIUseGetUserProfile: true
        })
      }
      if (this.data.isPage) {
        this.init()
      }
    },
    ready() {
      // 订阅
      bus.on('onNeedAuth', this.init.bind(this))
    }
  },
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      const { isPageHidden } = this.data

      // show事件发生前，页面不是处于隐藏状态时
      if (!isPageHidden) {
        return
      }

      // 重新执行定时器等操作
    },
    // 页面被隐藏
    hide() {
      this.setData({
        isPageHidden: true
      })

      // 清除定时器等操作
    },
    // 页面尺寸变化时
    resize() {}
  }
}

Component(componentOptions)
