import { mapState, mapActions } from 'vuex'
import API from '@/api'
import User from '@/store/db/User.js'
import { confirmPopup, openBlankWindow, getMeechatType } from '@/util/util'
import ScatterJS from 'scatter-js/dist/scatter.esm'

export const otherInfoMixins = {
  data () {
    return {
      accountList: null,
      userInfo: null,
      meechatType: getMeechatType()// meechat版本
    }
  },
  computed: {
    ...mapState({
      members: state => state.group.members,
      groupId: state => state.group.groupId,
      sessionList: state => state.chat.sessionList,
      meId: state => state.userId,
      meInfo: state => state.userInfo
    }),
    linkToOther () {
      let youId = this.userInfo.user_id
      let sessionId = Number(youId) < Number(this.meId) ? `${youId}-${this.meId}` : `${this.meId}-${youId}`

      return `${location.origin}/#/pm/${sessionId}`
    }
  },
  methods: {
    ...mapActions(['getUserInfo']),
    sendMsg () {
      this.visible = false

      let youId = this.userInfo.user_id
      let sessionId = Number(youId) < Number(this.meId)
        ? `${youId}-${this.meId}`
        : `${this.meId}-${youId}`

      let repeatFlag = this.sessionList.some(e => {
        return e.session_id == sessionId
      })

      if (!repeatFlag) {
        let obj = {
          cover_photo: this.userInfo.cover_photo,
          is_group: '0',
          name: this.userInfo.nick_name,
          // read_hash:null
          session_id: sessionId
        }
        this.$store.commit('addSessionItem', obj)
      }

      // 创建members,应对还没聊天记录的情况
      let myId = this.meInfo.user_id
      let members = {}
      members[myId] = {
        cover_photo: this.meInfo.cover_photo,
        nick_name: this.meInfo.nick_name
      }
      members[this.userInfo.user_id] = {
        cover_photo: this.userInfo.cover_photo,
        nick_name: this.userInfo.nick_name
      }

      this.$store.commit('updateGroup', {
        key: 'members',
        data: members
      })
      this.$store.commit('updateGroup', {
        key: 'privateName',
        data: this.userInfo.nick_name
      })
      this.$router.push({ path: `/pm/${sessionId}` })
    }
  },
  async created () {
    if (!this.meInfo) {
      await this.getUserInfo()
    }
    API.user.getOtherInfo({
      target_id: this.userId,
      group_id: this.groupId || null
    }).then(({ data }) => {
      this.accountList = data.data.binds
      this.userInfo = data.data
      this.visible = true

      if (data.data.user_id) {
        // 更新他人的信息
        let objUser = new User()
        let newData = {
          cover_photo: data.data.cover_photo,
          nick_name: data.data.nick_name,
          user_name: data.data.user_name
        }
        objUser.updateObject(newData, { user_id: data.data.user_id })
      }
    })
  }
}

// 绑定相关
export const bindAccountMixins = {
  data () {
    return {
      isLoading: false
    }
  },
  computed: {
    ...mapState({
      scatter: state => state.scatter
    })
  },
  methods: {
    ...mapActions([
      'setScatter',
      'doScatterLogin',
      'doScatterBind',
      'getUserInfo'
    ]),
    async bindEos () {
      this.isLoading = true

      if (window.EOS) {
        this.doScatterBind().then(() => {
          this.isLoading = false
          this.getUserInfo()
        }).catch((e) => {
          console.log(e)
          this.isLoading = false
        })
      } else {
        // 连接scatter
        await ScatterJS.scatter.connect('MEE_CHAT').then(async connected => {
          if (connected) {
          // 设置scatter
            this.setScatter(ScatterJS.scatter)

            // 清空全局scatter引用
            window.ScatterJS = null

            this.doScatterBind().then(() => {
              this.isLoading = false
              this.getUserInfo()
            }).catch((e) => {
              console.log(e)
              this.isLoading = false
            })
          }
        })
      }
    },
    async bindTg () {
      this.winHandler = openBlankWindow('')
      let { data } = await API.user.tgCSRF({
        type: 'bind'
      })

      this.winHandler.location.href = data.data.url

      var loop = setInterval(() => {
        if (this.winHandler != null && this.winHandler.closed) {
          clearInterval(loop)
          this.winHandler = null
        }
      }, 800)
      this.bindCheck(data.data.csrf_token)
    },
    async bindCheck (uuID, times) {
      this.isLoading = true
      if (times === 0) {
        // 第一次调用
        clearTimeout(this.timeoutHandler)
      } else if (times >= 60) {
        return false
      }

      let res = {}
      try {
        // 校验telegram
        res = await API.user.tgBind2({ csrf_token: uuID })
      } catch (ex) {
        this.isLoading = false
      }

      if (res.data && res.data.data && res.data.data.status > 0) {
        this.isLoading = false

        if (this.winHandler != null) {
          this.winHandler.close()
          this.winHandler = null
        }

        this.getSyncInfo && this.getSyncInfo(this.params)// 关联页
        this.getUserInfo()
      } else if (!res.data) {
        if (this.winHandler != null) {
          this.winHandler.close()
          this.winHandler = null
        }
      } else if ((this.winHandler != null) || (res.data && res.data.status == 0)) {
        // 定时检查是否登录成功
        this.timeoutHandler = setTimeout(() => {
          this.bindCheck(uuID, ++times)
        }, 1000)
      }
    },
    unbindAccount (type) {
      confirmPopup(`${this.$t('userinfo.unbindMsg')} ${type.toLocaleUpperCase()} ?`).then(() => {
        API.user.unBind({
          type
        }).then(() => {
          if (type == 'eos') this.scatter && this.scatter.forgetIdentity && this.scatter.forgetIdentity()

          this.$showTips(this.$t('userinfo.unbindSuccess'))
          this.getUserInfo()
        })
      })
    }
  }
}
