import {
  defineComponent,
  toRefs,
  reactive,
  onMounted,
  ref,
  nextTick,
  computed
} from 'vue'
import {
  ElTag,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import classes from './index.module.less'
import teacherHeader from '@/common/images/icon_teacher.png'
import { state } from '@/state'
import userBanner from '../images/userBanner.png'
import changeIcon from '../images/changeIcon.png'
import backIcon from '../images/backIcon.png'
import peopleIcon from '../images/peopleIcon.png'
import planIcon from '../images/planIcon.png'
import memberIcon from '../images/memberIcon.png'
import noMemberIcon from '../images/noMemberIcon.png'

import ablumIcon from '../images/ablumIcon.png'
import noAblumIcon from '../images/noAblumIcon.png'
import onlineIcon from '../images/onlineIcon.png'
import noOnlineIcon from '../images/noOnlineIcon.png'
import styleIcon from '../images/styleIcon.png'
import nostyleIcon from '../images/noStyleIcon.png'
import videoIcon from '../images/videoIcon.png'
import noVideoIcon from '../images/noVideoIcon.png'
import sVipIcon from '../images/sVipIcon.png'
import vipIcon from '../images/vipIcon.png'
import noVipIcon from '../images/noVipIcon.png'
import icon_back from '@/common/images/icon_back.png'

import {
  getUserInfo,
  getUserType,
  getAuth,
  setAuth,
  removeAuth
} from '@/helpers/utils'
import { useRoute, useRouter } from 'vue-router'
import request from '@/helpers/request'
import mitt from '@/helpers/mitt'
export default defineComponent({
  name: 'loganInfo',

  props: {
    title: {
      type: String,
      default: ''
    }
  },
  setup(props, conent) {
    const states = reactive({
      title: props.title,
      user: {} as any,
      userType: '',
      showChange: false,
      iconList: [] as any
    })
    mitt.on('mittFn', () => {
      console.log('mittFn')
      setUser()
    })
    const route = useRoute()
    const router = useRouter()
    const users = computed(() => {
      return state.user.data
    })
    onMounted(() => {
      nextTick(() => {
        setUser()
      })
    })

    // 检验是否有对应徽章
    const checkBadge = (type: string) => {
      // tag : 老师点亮图标
      // STYLE:个人风采
      // VIDEO：视频课
      // LIVE：直播课，
      // MUSIC：曲目 逗号隔开
      let status = false
      const userInfo = users.value
      switch (type) {
        case 'STYLE':
        case 'VIDEO':
        case 'LIVE':
        case 'MUSIC':
          if (userInfo.tag) {
            status = userInfo.tag.indexOf(type) > -1
          }
          break
        case 'VIP':
          status = userInfo.userVip?.vipType === 'VIP'
          break
        case 'SVIP':
          status =
            userInfo.userVip?.vipType === 'SVIP' ||
            userInfo.userVip?.vipType === 'PERMANENT_SVIP'
          break
        default:
          status = false
          break
      }
      return status
    }
    const setUser = () => {
      states.user = users.value
      console.log(users.value, 'users.value')
      states.userType = getUserType()
      if (states.user.userType) {
        if (
          states.user.userType.indexOf('TEACHER') != -1 &&
          states.user.userType.indexOf('STUDENT') != -1
        ) {
          states.showChange = true
        } else {
          states.showChange = false
        }
      }
      // iconList

      if (states.userType == 'TEACHER') {
        states.iconList = []
        if (checkBadge('VIP') || checkBadge('SVIP')) {
          states.iconList.push(memberIcon)
        } else {
          states.iconList.push(noMemberIcon)
        }
        if (checkBadge('STYLE')) {
          states.iconList.push(styleIcon)
        } else {
          states.iconList.push(nostyleIcon)
        }
        if (checkBadge('VIDEO')) {
          states.iconList.push(videoIcon)
        } else {
          states.iconList.push(noVideoIcon)
        }
        if (checkBadge('LIVE')) {
          states.iconList.push(onlineIcon)
        } else {
          states.iconList.push(noOnlineIcon)
        }
        if (checkBadge('MUSIC')) {
          states.iconList.push(ablumIcon)
        } else {
          states.iconList.push(noAblumIcon)
        }
      } else {
        states.iconList = []
      }
      console.log('查看用户登录态', states.user)
    }
    const gotoPage = (val: string) => {
      router.push({ path: val })
    }
    const changeRoute = () => {
      const token = getAuth()
      let userType = ''
      let str = ''
      let nowPath = route.fullPath

      if (states.userType == 'TEACHER') {
        userType = 'STUDENT'
        str = '学生'
        if (nowPath.indexOf('userInfo') != -1) {
          nowPath = '/studentInfo'
        }
      } else {
        userType = 'TEACHER'
        str = '老师'
        if (nowPath.indexOf('studentInfo') != -1) {
          nowPath = '/userInfo'
        }
      }
      ElMessageBox.confirm(`是否确定切换到${str}？`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const url =
            userType === 'TEACHER'
              ? '/api-website/teacher/queryUserInfo'
              : '/api-website/student/queryUserInfo'
          const { data } = await request.get(url)
          console.log(data, userType)

          if (data.lockFlag) {
            // 账号已锁定
            ElMessage.error(`无法切换，${str}账号异常`)
          } else {
            setAuth(
              JSON.stringify({
                token,
                loginUserType: userType
              })
            )
            router.push({ path: '/' }).then(() => {
              window.location.reload()
            })
          }
        } catch {
          // state.user.status = 'init'
        }
      })
    }
    const logout = async () => {
      try {
        await request.get('/api-auth/exit', {})
        router.push({ path: '/' })
        removeAuth()
        setTimeout(() => {
          window.location.reload()
        }, 100)
      } catch (e) {
        console.log(e)
      }
    }
    const gotoFans = (nowPath: string) => {
      router.push({ path: nowPath })
    }
    const changeState = (val: string) => {
      if (val == 'strudent') {
        gotoPage('/studentInfo')
      } else if (val == 'teacher') {
        gotoPage('/userInfo')
      } else if (val == 'change') {
        changeRoute()
      } else if (val == 'back') {
        logout()
      }
    }

    return {
      ...toRefs(states),
      users,
      gotoPage,
      changeRoute,
      checkBadge,
      logout,
      changeState,
      gotoFans
    }
  },
  render() {
    return (
      <>
        <ElDropdown
          onCommand={val => this.changeState(val)}
          popper-class="loginPopper"
          trigger="hover"
          v-slots={{
            dropdown: () => (
              <>
                <div class={classes.dropdownWrap}>
                  <div class={classes.dropdownWrapUser}>
                    <div class={classes.userInfoWrap1}>
                      {/* <img
                        src={
                          this.user.heardUrl
                            ? this.user.heardUrl
                            : teacherHeader
                        }
                        class={classes.userHeader}
                        alt=""
                      /> */}
                      <div class={classes.titleWrap}>
                        <p class={classes.title}>{this.user.username}</p>
                        {(this.checkBadge('VIP') ||
                          this.checkBadge('SVIP')) && (
                          <img
                            class={classes.vipLogo}
                            src={
                              this.checkBadge('SVIP')
                                ? sVipIcon
                                : this.checkBadge('VIP')
                                ? vipIcon
                                : noVipIcon
                            }
                            style="object-fit: cover;"
                            alt=""
                          />
                        )}
                      </div>
                      <div class={classes.iconList}>
                        {this.userType == 'TEACHER' ? (
                          <p class={classes.teacherTag}>{'老师'}</p>
                        ) : (
                          <p class={classes.studentTag}>{'学生'}</p>
                        )}
                        {this.iconList.map(item => (
                          <img class={classes.icon} src={item} alt="" />
                        ))}
                      </div>
                    </div>
                    {/* <img src={userBanner} alt="" /> */}
                  </div>

                  {this.userType == 'TEACHER' ? (
                    <div class={classes.dropdownInfo}>
                      <div
                        class={classes.dropdownItem}
                        onClick={() => this.gotoFans('/userInfo/myFans')}
                      >
                        <p class={classes.dropdownItemTitle}>
                          {this.users.fansNum || 0}
                        </p>
                        <p class={classes.dropdownItemsubTitle}>粉丝</p>
                      </div>
                      <div
                        class={classes.dropdownItem}
                        onClick={() => this.gotoFans('/userInfo/musicClass')}
                      >
                        <p class={classes.dropdownItemTitle}>
                          {this.users.musicSheetNum || 0}
                        </p>
                        <p class={classes.dropdownItemsubTitle}>乐谱</p>
                      </div>
                      {/* <div class={classes.dropdownItem}>
                      <p class={classes.dropdownItemTitle}>134</p>
                      <p class={classes.dropdownItemsubTitle}>帖子</p>
                    </div> */}
                    </div>
                  ) : null}

                  <ElDropdownMenu>
                    {this.userType == 'TEACHER' ? (
                      <ElDropdownItem command="teacher" class="backItem">
                        <div class="dropdownItemWrap">
                          <img
                            class={classes.dropdownImg}
                            src={peopleIcon}
                            alt=""
                          />{' '}
                          个人中心
                        </div>
                        <img src={icon_back} alt="" class="icon_back" />
                      </ElDropdownItem>
                    ) : (
                      <ElDropdownItem command="strudent" class="backItem">
                        <div class="dropdownItemWrap">
                          <img
                            class={classes.dropdownImg}
                            src={peopleIcon}
                            alt=""
                          />{' '}
                          个人中心
                        </div>
                        <img src={icon_back} alt="" class="icon_back" />
                      </ElDropdownItem>
                    )}
                    {/* <ElDropdownItem  onClick={gotoPage('')}><img class={classes.dropdownImg} src={planIcon} alt="" /> 创作中心</ElDropdownItem> */}
                    {this.showChange ? (
                      <ElDropdownItem command="change" class="backItem">
                        <div class="dropdownItemWrap">
                          <img
                            class={classes.dropdownImg}
                            src={changeIcon}
                            alt=""
                          />{' '}
                          角色切换
                        </div>
                        <div class="changeWrap">
                          <span>
                            {' '}
                            {this.userType == 'TEACHER' ? '学生' : '老师'}
                          </span>
                          <img src={icon_back} alt="" class="icon_back" />
                        </div>
                      </ElDropdownItem>
                    ) : null}

                    <ElDropdownItem command="back" class="backItem">
                      <div class="lineItem">
                        <div class="backWrap">
                          <img class="backIcon" src={backIcon} alt="" />{' '}
                          退出登录
                        </div>
                        <img src={icon_back} alt="" class="icon_back" />
                      </div>
                    </ElDropdownItem>
                  </ElDropdownMenu>
                </div>
              </>
            )
          }}
        >
          <div class={classes.userInfoWrap}>
            {/* <p class={classes.title}>{this.user.username}</p> */}
            <img
              src={this.user.heardUrl ? this.user.heardUrl : teacherHeader}
              class={classes.userHeader}
              alt=""
            />
          </div>
        </ElDropdown>
      </>
    )
  }
})
