import { ElButton, ElIcon, ElLink } from 'element-plus'
import QrcodeVue from 'qrcode.vue'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import Cookies from 'js-cookie'
import request from '@/helpers/request'
import { state } from '@/state'
import { getCodeBaseUrl, setAuth } from '@/helpers/utils'
import { CircleCheck } from '@element-plus/icons-vue'
import logoIco from '@/common/images/logo.png'

export const getAssetsHomeFile = (fileName: string) => {
  const path = `../../images/${fileName}`
  const modules = import.meta.globEager('../../images/*')
  return modules[path].default
}

export default defineComponent({
  name: 'qrCode',
  props: {
    loginType: {
      type: String
    },
    onChange: {
      type: Function,
      default: (type: string) => {}
    },
    onClose: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      qrCode: '',
      isScan: false, // 是否扫码
      scanCode: '',
      codeTimerOut: false, // 是否超时或登录过期
      // 状态 no_scan 未扫码 scanned 已扫码 succeed 登录成功 filed 登录失败
      codeStatus: 'no_scan' as 'no_scan' | 'scanned' | 'succeed' | 'filed' // 扫码状态
    }
  },
  async mounted() {
    try {
      const scanCode = sessionStorage.getItem('scanCode')
      await this.getCode(scanCode)
      const str = this.loginType === 'TEACHER' ? 'teacher' : 'student'
      this.qrCode = `${getCodeBaseUrl(`/${str}`)}/#/scanLogin?code=${
        this.scanCode
      }`
      console.log(this.qrCode)
      state.loginPopupTimer = setInterval(async () => {
        await this.getList()
      }, 5000)
    } catch {
      //
    }
  },
  methods: {
    async getCode(code?: string) {
      try {
        const res = await request.get('/api-auth/getQRLoginCode', {
          params: {
            clientId: 'website',
            clientSecret: 'website',
            code
          }
        })
        this.scanCode = res.data.code
        this.codeStatus = res.data.codeStatus
        sessionStorage.setItem('scanCode', res.data.code)
      } catch {}
    },
    async getList() {
      try {
        console.log(this.scanCode)
        const res = await request.get('/api-auth/pollingQRLoginCode', {
          params: {
            code: this.scanCode
          }
        })
        console.log(res, 'getlist')
        const result = res.data
        // 判断是否有数据，如果没有数据则认定为超时
        if (!result) {
          this.codeTimerOut = true
          this.removeTimer()
          return
        }
        this.codeStatus = result.codeStatus
        if (result.codeStatus === 'succeed') {
          this.removeTimer()
          const { authentication, userType } = result
          const token =
            authentication.token_type + ' ' + authentication.access_token
          setAuth(
            JSON.stringify({
              token,
              loginUserType: userType
            })
          )
          this.onClose()
          window.location.reload()
        } else if (result.codeStatus === 'filed') {
          this.removeTimer()
        } else if (result.codeStatus === 'scanned') {
          this.isScan = true
        }
      } catch {
        console.log('error')
        this.codeTimerOut = true
        this.removeTimer()
      }
    },
    removeTimer() {
      // 取消定时器
      this.codeStatus = 'no_scan'
      this.isScan = false
      clearInterval(state.loginPopupTimer)
    }
  },
  render() {
    return (
      <div class={'text-center pt-4'}>
        {/* <div
          class={'absolute top-2 right-2 z-10'}
          onClick={() => {
            this.removeTimer()
            this.onChange('login')
          }}
        >
          <img
            src={getAssetsHomeFile('icon_pc_login.png')}
            class="w-14 h-14 cursor-pointer"
          />
        </div> */}
        {this.isScan ? (
          <>
            <ElIcon
              class="mx-auto w-[138px] h-[138px] align-middle"
              size={70}
              color="var(--el-color-primary)"
            >
              <CircleCheck />
            </ElIcon>
            <p class="text-lg text-[#666] mt-6">扫码成功</p>
            <p class="font-semibold text-[#1A1A1A] text-[20px] pt-4">
              请在手机上根据提示确认登录
            </p>

            <ElLink
              type="primary"
              underline={false}
              class="m-auto mt-3"
              onClick={async () => {
                const scanCode = sessionStorage.getItem('scanCode')
                await this.getCode(scanCode || '')
                this.isScan = false
              }}
            >
              返回扫描二维码
            </ElLink>
          </>
        ) : (
          <>
            <div class="mx-auto w-[192px] h-[192px] relative overflow-hidden rounded-[10px]">
              <QrcodeVue
                value={this.qrCode}
                size={192}
                class="p-2.5 border-4 border-[#2DC7AA] box-border rounded-[10px]"
              />
              {/* 手动在中间添加图标 */}
              <div class="absolute w-[192px] h-[192px] top-0 left-0 flex items-center justify-center">
                <img src={logoIco} class="w-9 h-9" />
              </div>
              {/* 登录是否过期 */}
              {this.codeTimerOut && (
                <div class="absolute inset-0 bg-black bg-opacity-75 flex items-center justify-center flex-col">
                  <p class="text-white text-sm pb-2">二维码已失效</p>
                  <ElButton
                    type="primary"
                    size="small"
                    onClick={async () => {
                      this.codeTimerOut = false
                      await this.getCode()
                      state.loginPopupTimer = setInterval(async () => {
                        await this.getList()
                      }, 5000)
                    }}
                  >
                    点击刷新
                  </ElButton>
                </div>
              )}
            </div>
            <div class="flex items-center justify-center pt-8 font-normal">
              {/* <img
                class="w-9 h-9 align-middle mr-4"
                src={getAssetsHomeFile('icon_scan.png')}
              />

              <div class={['text-left leading-[22px]']}>
                <p>
                  打开<span class={styles.txt}>酷乐秀学生端APP</span>
                </p>
                <p>扫一扫登录</p>
              </div> */}
              <div class="text-lg text-[#333] text-center">
                打开
                {this.loginType === 'TEACHER' ? '酷乐秀学院' : '酷乐秀'}
                App扫一扫登录
              </div>
            </div>
          </>
        )}
      </div>
    )
  }
})
