<template>
  <header id="header">
    <div class="wrap">
      <div class="left-part">
        <img v-if="user.isQingQue" class="logo" src="http://gm.nkfzs.com/favicon.ico" alt="游戏中心"/>
        <img v-else class="logo" :src="getAssetsFile('default_logo.png')" alt="游戏中心"/>
        {{ user.projectName }}
      </div>
      <div class="menu">
        <el-menu
          :default-active="route.path"
          class="el-menu-wrapper"
          :ellipsis="false"
          router
          mode="horizontal"
        >
          <el-menu-item index="/home">首页</el-menu-item>
          <el-menu-item index="/cate">分类</el-menu-item>
          <el-menu-item index="/my_game">我的游戏</el-menu-item>
        </el-menu>
      </div>
      <div class="search-wrap">
        <el-autocomplete
          v-model="search.params.keywords"
          :fetch-suggestions="searchChange"
          placeholder="请输入游戏名称"
          :prefix-icon="Search"
          clearable
          @select="handleSelect"
          @keyup.enter="handleKeyEnter"
          maxlength="30"
        />
      </div>
      <div class="mob-search" v-if="route.path === '/home' && platform.mobile">
        <van-search shape='round' @click="router.push({ path: '/search' })" />
      </div>
      <div  class="mini-menu" v-if="platform.mobile && route.path !== '/home' ">
        <img v-if="route.path !== '/search'" :src="getAssetsFile('search_circle.png')" alt="" @click="router.push({ path: '/search' })" />
        <i class="verticle" />
        <img :src="getAssetsFile('menu.png')" alt="" @click="show=true"/>
      </div>
      <div class="user">
        <span v-if="!user.isLogin" class="el-dropdown-link">
          <img :src="getAssetsFile('gamer.png')" @click="loginFormVisible = true" />
        </span>
        <el-dropdown v-else trigger="click" >
          <span class="el-dropdown-link">
            <img :src="getAssetsFile('gamer.png')" />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item class="clearfix" @click="toSetting">
                账号设置
              </el-dropdown-item>
              <el-dropdown-item class="clearfix" @click="logOut">
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </header>
  <div class="header-hidden"/>
  <el-dialog
    v-model="loginFormVisible"
    :center="true"
    title="登录"
    width="30%"
  >
    <div class="login-box-header">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        class="login_from"
        label-position="left"
        :model="loginForm"
        style="max-width: 400px"
        @submit.prevent="submitForm(ruleFormRef)">
        <el-tabs v-model="login_typ" style="width: 50%;" @tab-change="resetForm(ruleFormRef)">
          <el-tab-pane label="密码登录" name="pwd" />
          <el-tab-pane label="验证码登录" name="sms" />
        </el-tabs>
        <template v-if="login_typ === 'pwd'">
          <el-form-item label="" prop="account">
            <el-input v-model="loginForm.account" type="text" placeholder="请输入账号" clearable :prefix-icon="User" />
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              show-password
              placeholder="请输入密码"
              autocomplete="off"
              :prefix-icon="Lock" />
            <el-input
              v-model="loginForm.password"
              type="hidden"
              autocomplete="off"
              id="md5_password"
              show-password
              placeholder="请输入密码"
              :prefix-icon="Lock" />
          </el-form-item>
        </template>
        <template v-else-if="login_typ === 'sms'">
          <el-form-item label="" prop="account">
            <el-input v-model="loginForm.account"  type="text" placeholder="请输入手机号" clearable :prefix-icon="Cellphone" />
          </el-form-item>
          <el-form-item label="" prop="smsCaptcha">
            <el-input v-model="loginForm.smsCaptcha" type="number" placeholder="请输入验证码" :prefix-icon="Lock">
              <template #append>
                <div>
                  <el-button @click="getCaptcha" color="#ed8c0f" style="width: 100px;" :disabled ="!can_send">{{smsMessage}}</el-button>
                </div>
              </template>
            </el-input>
          </el-form-item>
        </template>
        <!-- <el-form-item style="margin-top:-10px;margin-bottom:-5px;">
                    <el-checkbox v-model="checked" style="color:#a0a0a0;margin-top:-10px;">记住我</el-checkbox>
                </el-form-item> -->
        <div class="btn">
          <el-button
            round
            class="submit_btn"
            block
            type="primary"
            size="large"
            native-type="submit">登&emsp;录</el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
  <van-popup
    v-model:show="show"
    position="top"
    :style="{ width: '100%', height: 'auto' }"
  >
    <van-cell
      class="menu_title"
      v-for="(item, index) in user.menuPath"
      :key="index"
      :title="item.text"
      @click="toPath(item.url)"/>
    <van-cell v-if="user.isLogin" title="账号设置" @click="toSetting"/>
    <van-cell v-if="user.isLogin" title="退出登录" @click="logOut"/>
  </van-popup>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store'
import Message from '@/utils/Message'
import local from '@/utils/local'
import { getAssetsFile } from '@/utils/imgResolve'
import { Lock, User, Cellphone, Search } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getUserLogin, captchaLogin, getCaptchaHttp, getGameList } from '@/api/index'

// const img:any = inject('img')
const router = useRouter()
const route = useRoute()
const { user } = useStore()
const { search } = useStore()
// showSuccessToast('成功文案')
// showFailToast('失败文案')
const show = ref(false)
const game_name = ref(local.get('searchText') || '')
// 绑定el-autocomplete组件
const oriMenu = reactive([
  { text: '首页', value: 1, url: '/home' },
  { text: '分类', value: 2, url: '/cate' },
  { text: '我的游戏', value: 3, url: '/my_game' }
])
const currentIndex = ref(local.get('headerPath') || '') // 取保存的title
console.log('currentIndex', currentIndex.value)

if (route.query.account) {
  currentIndex.value = '我的'
  console.log('1234567', currentIndex.value)
}

// 顶部导航栏
onMounted(() => {
  const token = sessionStorage.getItem('token') || ''
  if (token) {
    user.isLogin = true
    user.getUserProfile()
  }
})

// 退出登录
const logOut = () => {
  // console.log(22);
  show.value = false
  user.menuPath = oriMenu
  sessionStorage.removeItem('token')
  user.isLogin = false
  router.push({ path: '/login' })
}
const toSetting = () => {
  show.value = false
  router.push('/settings')
}
interface LinkItem {
  id: string
  value: string
}
const links: any = ref<LinkItem[]>([])

const searchChange = async(str: string, cb: (arg: any) => void) => {
  currentIndex.value = ''
  local.remove('headerPath')
  if (str && str.length > 0) {
    game_name.value = str
    try {
      var params = reactive({
        type: 0,
        tag_id: 0,
        page: 1,
        pagesize: 10,
        keywords: str
      })
      var { data } = await getGameList(params)
      links.value = data.data.lists
      links.value = links.value.map((item:any, index:any) => {
        return {
          id: `${index}`,
          value: `${item.screen_name}`
        }
      })
      links.value = links.value.filter((item:any) => {
        return item.value.indexOf(str) > -1
      })
      cb(links.value)
    } catch (error: any) {
      // links.value.push({
      //   id: '-1',
      //   value: '暂无匹配数据'
      // })
      // cb(links.value)
      console.log(error)
      Message.error(error.data.msg)
    }
  } else {
    cb([])
  }
}

const handleSelect = (item: LinkItem) => {
  if (item) {
    if (route.path !== '/search') {
      router.push({ path: '/search' })
    }
    search.onSearch()
    local.set('searchText', game_name.value)
  }
}

// 手动回车跳转搜索页
const handleKeyEnter = () => {
  if (route.path !== '/search') {
    router.push({ path: '/search' })
  }
  search.onSearch()
  local.set('searchText', game_name.value)
}

watch(currentIndex, () => { }, { deep: true, immediate: true })
const platform = computed(() => {
  var u = navigator.userAgent
  return {
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
    iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, // 是否iPad
    webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1 // 是否微信
  }
})
const toPath = (url: any) => {
  show.value = false
  router.push({ path: url })
}
declare let md5: any

const loginFormVisible = ref<boolean>(false)
const rules = reactive<FormRules>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 255, message: '请正确输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur,change' }
  ],
  smsCaptcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})
interface login {
    account: string,
    password: string,
    timestamp: number | string,
    smsCaptcha:string | undefined
}
const loginForm = reactive<login>({
  account: '',
  password: '',
  timestamp: parseInt(`${Date.now() / 1000}`),
  smsCaptcha: undefined
})
const ruleFormRef = ref<FormInstance>()
const login_typ = ref<'pwd'| 'sms'>('sms')
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const can_send = ref<boolean>(true)
const smsMessage = ref<'获取验证码' | number>('获取验证码')
const VALID = 60
const settimes = () => {
  var interval:any
  const setTimeFn = () => {
    (smsMessage.value as number)--
    if (smsMessage.value as number < 0 || can_send.value === true) {
      clearInterval(interval)
      can_send.value = true
      smsMessage.value = '获取验证码'
    }
  }
  interval = setInterval(function() {
    setTimeFn()
  }, 1000)
}
const getCaptcha = async() => {
  if (loginForm.account.length !== 11) {
    return Message.error('请输入有效手机号！')
  }
  await getCaptchaHttp({ mobile: loginForm.account }).then((res) => {
    console.log(res)
    can_send.value = false
    smsMessage.value = VALID
    settimes()
    sessionStorage.setItem('LOGIN_CAPTCHA', Math.round(new Date().getTime() / 1000).toString())
    Message.success('验证码已发送，请注意查收')
  }).catch((error) => {
    console.log(error)
    Message.error(error.data.msg)
  })
}
const submitForm = async(formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      if (login_typ.value === 'pwd') {
        // 登录密码加密
        let md5Pwd: any = document.querySelector('#md5_password')
        // eslint-disable-next-line no-undef
        md5Pwd = md5(md5(md5(loginForm.password)) + loginForm.timestamp)

        const params = {
          account: loginForm.account,
          password: md5Pwd,
          timestamp: loginForm.timestamp
        }
        getUserLogin(params).then(async(res) => {
          // console.log('res---->', res);
          if (res.data.code === 200) {
            Message.success('登录成功')
            // 保存用户信息 和 token
            sessionStorage.setItem('token', res.data.data.token)
            sessionStorage.setItem('account', loginForm.account)
            localStorage.setItem('from', '1')
            user.isLogin = true
            await user.getUserProfile()
            // 跳转我的游戏页面
            setTimeout(() => {
              router.push({ path: '/my_game', query: { account: loginForm.account }})
              local.set('headerPath', '我的')
            }, 1000)
          }
        }).catch(err => {
          // console.log('err===>', err);
          Message.error(err.data.msg)
        })
      } else if (login_typ.value === 'sms') {
        const params = {
          mobile: loginForm.account,
          captcha: loginForm.smsCaptcha
        }
        console.log(params)

        await captchaLogin(params).then(async(res) => {
          console.log(res)
          if (res.data.code === 200) {
            Message.success('登录成功')
            sessionStorage.setItem('token', res.data.data.token)
            sessionStorage.setItem('account', loginForm.account)
            localStorage.setItem('from', '2')
            user.isLogin = true
            await user.getUserProfile()
            setTimeout(() => {
              router.push({ path: '/my_game', query: { account: loginForm.account }})
              local.set('headerPath', '我的')
            }, 1000)
          }
        }).catch((error) => {
          console.log(error)
          Message.error(error.data.msg)
        })
      }
    } else {
      console.log('登录失败', fields)
    }
  })
}
</script>

<style lang="scss" scoped>
#header{
    width: 100%;
    max-width: 100vw;
    background-color: #fff;
    position: fixed;
    z-index: 1000;
    .wrap{
        margin: 0 auto;
        height: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;
        .left-part{
            display: flex;
            align-items: center;
            font-family: 'zihunchaoji';
            white-space: nowrap;
        }
        .menu{
            padding: 0 5rem 0 1rem;
            .el-menu--horizontal.el-menu{
                border: 0;
                >.el-menu-item.is-active{
                    border: 0;
                }
            }
            .el-menu-item{
              border: 0;
            }
        }
        .search-wrap{
          width: 8.5rem;
          :deep(.el-input__wrapper){
              border-radius: 1rem;
          }
        }
        .user{
          cursor: pointer;
          .el-dropdown-link{
            overflow: hidden;
            width: 2rem;
            height: 2rem;
            border-radius: 50%;
            >img{
              width: 2rem;
              height: 2rem;
              display: block;
            }
          }

        }
        .mini-menu{
          display: flex;
          align-items: center;
          >img{
            width: 25px;
            height: 25px;
          }
          .verticle{
            width: 1px;
            height: 30px;
            background-color: #ddd;
            margin: 0 10px;
          }
        }
    }
}
.header-hidden{
  height: 3rem;
}
.login-box-header{
  padding: 1rem;
  .submit_btn{
    width: 100%;
    display: block;
  }
}
</style>
