import { defineComponent } from 'vue'
import { Button, Image, Toast } from 'vant'
import { removeAuth, setAuth } from './utils'
import styles from './index.module.less'
import {
  listenerMessage,
  postMessage,
  promisefiyPostMessage,
  removeListenerMessage
} from '@/helpers/native-message'
import iconStudent from '@common/images/icon-student-default.png'
import logo from '@common/images/logo.png'
import ColPopup from '@/components/col-popup'
import InviteCode from './invite-code'
import { setLogin, state } from '@/state'
import request from '@/student/home-layout-orchestra/request-home'

export default defineComponent({
  name: 'login-music',
  data() {
    return {
      username: '',
      imgCodeStatus: false
    }
  },
  mounted() {
    this.username = state.orchestraInfo.phone
    removeAuth()

    listenerMessage('webViewOnResume', () => {
      promisefiyPostMessage({ api: 'getUserAccount' }).then(
        async (res: any) => {
          const content = res.content
          state.orchestraInfo.token = content.token.split(' ')[1]
          state.orchestraInfo.phone = content.phone
          state.orchestraInfo.nickname = content.nickname
          state.orchestraInfo.avatar = content.avatar
          state.orchestraInfo.unionId = content.unionId || 0
          this.username = state.orchestraInfo.phone
          if (content.unionId && this.$route.path === '/home-auth') {
            this.getUserInfo()
          }
        }
      )
    })
  },
  unmounted() {
    removeListenerMessage('webViewOnResume', () => {
      //
    })
  },
  methods: {
    onLoginSuccess() {
      // 调用原生api去关联账号
      postMessage({ api: 'bindUserAccount', content: { phone: this.username } })
      // 登录成功
      setTimeout(() => {
        Toast('授权成功')
      }, 100)
      setTimeout(() => {
        this.getUserInfo()
        // this.$router.push('/home')
        // window.location.href = location.origin + location.pathname + '#/home'
        // setTimeout(() => {
        // window.location.reload()
        // }, 100)
      }, 1000)
    },
    async getUserInfo() {
      try {
        const res = await request.post('/api-auth/smsLogin', {
          requestType: 'form',
          data: {
            clientId: 'student',
            clientSecret: 'student',
            phone: state.orchestraInfo.phone,
            token: state.orchestraInfo.token,
            isSurportRegister: true
          }
        })
        const { authentication } = res.data
        setAuth(authentication.token_type + ' ' + authentication.access_token)
        promisefiyPostMessage({
          api: 'setCache',
          content: {
            key: 'h5-colexiu-token',
            value: authentication.token_type + ' ' + authentication.access_token
          }
        })
        const userCash = await request.get(
          '/api-student/student/queryUserInfo',
          {
            initRequest: true // 初始化接口
          }
        )
        setLogin(userCash.data)
        this.$router.push('/home')
      } catch {
        //
      }
    },
    async onLogin() {
      try {
        const res = await request.post('/api-auth/smsLogin', {
          requestType: 'form',
          data: {
            clientId: 'student',
            clientSecret: 'student',
            phone: this.username,
            token: state.orchestraInfo.token,
            isSurportRegister: true
          }
        })

        const { authentication } = res.data
        setAuth(authentication.token_type + ' ' + authentication.access_token)
        promisefiyPostMessage({
          api: 'setCache',
          content: {
            key: 'h5-colexiu-token',
            value: authentication.token_type + ' ' + authentication.access_token
          }
        })
        this.onLoginSuccess()
      } catch {
        //
      }
    }
  },
  render() {
    return (
      <div class={styles.login}>
        <div class={styles.container}>
          <div class={[styles.userInfo, styles.loginCenter]}>
            <Image
              src={state.orchestraInfo.avatar || iconStudent}
              class={styles.img}
              fit="cover"
            />

            <p class={styles.name}>{state.orchestraInfo.name}</p>
          </div>

          <div class={[styles.tips, styles.loginCenter]}>
            <Image src={logo} class={styles.logo} fit="contain" />

            <p class={styles.text}>同意酷乐秀获取您的管乐团信息并登录</p>

            <p class={styles.phone}>{this.username}</p>
          </div>
        </div>

        <div class={styles.btnGroup}>
          <Button
            round
            color="#FF8057"
            class={styles.btn}
            onClick={this.onLogin}
          >
            授权登录
          </Button>

          <span
            class={styles.moreBtn}
            onClick={() => {
              this.$router.push('/home-login')
            }}
          >
            其他手机号登录
          </span>
        </div>

        {/* <ColPopup v-model={this.imgCodeStatus}>
          {this.imgCodeStatus && (
            <InviteCode
              phone={this.username}
              onLoginSuccess={this.onLoginSuccess}
            />
          )}
        </ColPopup> */}
      </div>
    )
  }
})
