<template>
  <el-container class="login-container">
    <el-header height="40px" style="background: #fff6e8;" class="p0">
      <top v-if="topLoadin" @userNavTo="userTo"></top>
    </el-header>
    <el-main class="p0">
      <login-top-menus :routers="visibleRouters"></login-top-menus>
      <login-form-banner ref="loginForm" :is-login="isLogin" :login-form="loginForm" :login-rules="loginRules"
                         :loading="loading"></login-form-banner>
      <div class="fx-column fx-cen-cen">
        <index-card-subject-query class="mt20 index-block"/>
        <index-card-elective-test class="mt20 index-block"/>
        <index-card-career class="mt20 index-block"/>
        <index-preference-simulate class="mt20 index-block"/>
        <index-preference class="mt20 index-block"/>
        <index-news-top-wrapper class="mt20 index-block"/>
      </div>
      <bottom-p class="mt20"></bottom-p>
      <el-dialog v-if="dialogVisible" title :visible.sync="dialogVisible" width="850px">
        <complete-profile @completed="handleProfileCompleted"
                          style="margin-left:250px; padding:0 30px"></complete-profile>
      </el-dialog>
      <el-dialog v-if="forgetDialogVisiable" :visible.sync="forgetDialogVisiable" title="忘记密码" width="650px"
                 style="height:600px">
        <forget-password @resetPwdSuccess="forgetDialogVisiable=false"></forget-password>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import store from '@/store'
import router from '@/router'
import { mapActions, mapGetters } from 'vuex'
import auth from '@/utils/auth'
import { getFrontInitialRouters } from '@/api/system/user'
import forgetPassword from '@/views/components/forget-pwd.vue'
import CompleteProfile from '@/views/components/complete-profile.vue'
import RouterHelpMixin from '@/router/router-help-mixin'
import LoginTopInfo from '@/views/index/components/login-top-info'
import LoginFormBanner from '@/views/index/components/login-form-banner'
import LoginTopMenus from '@/views/index/components/login-top-menus'
import loginCheckMixin from '@/views/components/blocks/index-login-check-mixin'
import IndexCardElective from '@/views/index/components/index-card-elective'
import IndexCardSubjectQuery from '@/views/index/components/index-card-subject-query'
import IndexCardElectiveTest from '@/views/index/components/index-card-elective-test'
import IndexPreferenceSimulate from '@/views/index/components/index-preference-simulate'
import IndexPreference from '@/views/index/components/index-preference'
import IndexCardCareer from '@/views/index/components/index-card-career'
import IndexNewsTopWrapper from '@/views/index/components/index-news-top-wrapper'

export default {
  mixins: [RouterHelpMixin, loginCheckMixin],
  components: {
    IndexNewsTopWrapper,
    IndexCardCareer,
    IndexPreference,
    IndexPreferenceSimulate,
    IndexCardElectiveTest,
    IndexCardSubjectQuery,
    IndexCardElective,
    LoginTopMenus,
    LoginFormBanner,
    LoginTopInfo,
    forgetPassword,
    CompleteProfile
  },
  provide() {
    return {
      to: this.to,
      userTo: this.userTo,
      handleLogin: this.handleLogin,
      logout: this.logout,
      handleForgetPwd: this.handleForgetPwd
    }
  },
  data() {
    return {
      forgetDialogVisiable: false,
      topLoadin: true,
      isLogin: auth.getToken(),
      loginObj: {},
      loading: false,
      gradeLoading: false,
      navList: [],
      loginForm: {
        username: '',
        password: '',
        // rememberMe: false,
        // code: "",
        // uuid: "",
        relation: 1,
        grade: 2,
        year: ''
      },
      loginRules: {
        relation: [
          {
            required: true,
            trigger: 'blur',
            message: '请选择学生端或者老师端'
          }
        ],
        grade: [
          {
            required: true,
            trigger: 'blur',
            message: '请选择学校类别'
          }
        ],
        username: [
          {
            required: true,
            trigger: 'blur',
            message: '用户名不能为空'
          }
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '密码不能为空'
          }
        ],
        code: [
          {
            required: true,
            trigger: 'change',
            message: '验证码不能为空'
          }
        ]
      },
      options: {
        img: store.getters.avatar //裁剪图片的地址
      },
      submitLoading: false,
      schoolData: [],
      gradeData: [],
      classData: [],
      areaSchoolAndYears: {},
      isSecd: false,
      times: 120,
      form: {
        username: '',
        phoneNumber: '',
        code: '',
        schoolId: '',
        gradeId: [],
        clazzId: []
      },
      subjectData: [],
      dialogVisible: false,
      id: 0,
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          setTimeout(() => {
            const nodes = Array.from({
              length: level + 1
            }).map((item) => {
              let a = ''
              if (level == '0') {
                a = '省'
              } else if (level == '1') {
                a = '市'
              } else {
                a = '区'
              }
              return {
                value: 1212,
                label: `选项${a} `,
                leaf: level >= 2
              }
            })
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes)
          }, 1000)
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'isFrontStudent',
      'isFrontTeacher',
      'isFrontMaster',
      'currentUser'
    ]),
    visibleRouters() {
      return this.navList.filter((r) => r.meta?.title && !r.hidden)
    }
  },
  created() {
    let u = navigator.userAgent
    let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
    if (isAndroid) {
      let url = this.$route.fullPath.split('?')[1]
      if (url && !this.isLogin) {
        let urlData = url.split('&')
        for (let i = 0; i < urlData.length; i++) {
          this.loginObj[urlData[i].split('=')[0]] =
            urlData[i].split('=')[1]
        }
        if (this.loginObj.username && this.loginObj.password) {
          // 直接发起登录
          this.loading = true
          this.Login(this.loginObj)
            .then(() => {
              this.isLogin = true
              this.loading = false
              this.getUser()
              this.getNav()
              // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
            })
            .catch(() => {
              this.loading = false
            })
        }
      }
    } else {
      this.getUser()
      this.getNav()
    }
  },
  methods: {
    ...mapActions(['GenerateRoutes', 'Login', 'LogOut', 'GetInfo']),
    getNav() {
      console.log(
        'getNav called',
        'real menu=' + !!(this.islogin && this.currentUser.isBind),
        this.currentUser,
        this.isLogin
      )
      if (this.isLogin) {
        this.GenerateRoutes().then((accessRoutes) => {
          console.log('GenerateRoutes accessRoutes', accessRoutes)
          router.addRoutes(accessRoutes) // 动态添加可访问路由表
          this.navList = JSON.parse(
            JSON.stringify(
              this.$store.state.permission.topbarRouters
            )
          )
        })
      } else {
        getFrontInitialRouters().then((res) => {
          this.navList = res.data.map((r) => ({
            path: r.path,
            meta: r.meta
          }))
        })
      }
    },
    gouAction(data) {
      // 22.6.7 hht 作废此方法，只处理了有限级跳转
      if (data && data.length > 0) {
        if (data[0].children && data[0].children.length > 0) {
          if (
            data[0].children[0].children &&
            data[0].children[0].children.length > 0
          ) {
            return data[0].children[0].children.path
          } else {
            return data[0].path + '/' + data[0].children[0].path
          }
        } else {
          return data[0].path
        }
      } else {
        return ''
      }
    },
    handleClick(data) {
      let item = JSON.parse(JSON.stringify(data))
      let routes = undefined //三级菜单
      let second = [] //二级
      let routesTo = []
      if (item.children) {
        //有二级菜单
        item.children.forEach((item2) => {
          if (item2.children) {
            item2.children.forEach((item3) => {
              item3.path =
                item.path + '/' + item2.path + '/' + item3.path
            })
            if (!routes && item2.children.length) {
              //一级菜单下面第一个有3个菜单的二级菜单
              routes = item2.children
              routesTo = item2.children
            }
          } else {
            if (!routes) {
              routes = []
            }
            routesTo = item.children
          }
          item2.path = item.path + '/' + item2.path
          item2.level = 2
          second.push(item2)
        })
        auth.setActiveMenu(second[0].path)
        // let fal = false
        // second.forEach((item) => {
        //   if (!fal && item.children && item.children.length > 0) {
        //     auth.setActiveMenu(item.path)
        //     fal = true
        //   }
        // })

        auth.setMenuTab(second)
        this.three = true
        this.$store.commit('SET_SIDEBAR_ROUTERS', routes)
      } else {
        //没有二级菜单
        this.$store.commit('SET_SIDEBAR_ROUTERS', [])
        this.$router.push({
          path: item.path
        })
      }
      let path = this.findLeafDescendantPath(data)
      if (path) {
        this.$router.push({
          path: path
        })
        auth.setMenuListAction(path)
      } else {
      }
      auth.setMenuList(routes)
    },
    logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.LogOut().then(() => {
          this.isLogin = false
          this.getNav()
          this.topLoadin = false
          this.loginObj = {}
          setTimeout(() => {
            this.topLoadin = true
            this.$router.push({ path: '/login' })
          }, 10)
        })
      })
    },
    getUser() {
      if (!this.isLogin) return
      this.GetInfo().then((response) => {
        this.dialogVisible = !this.currentUser.isBind
        this.topLoadin = false
        setTimeout(() => {
          this.topLoadin = true
        }, 10)
      })
    },
    userTo() {
      //跳转至个人中心
      if (this.isLogin && !this.currentUser.isBind) {
        this.dialogVisible = true
        this.$message.error('请先完善信息！')
        return
      }
      const pcRouter = this.navList.find((r) => r.path == '/user')
      if (pcRouter) this.to(pcRouter)
    },
    to(url) {
      console.log('will go to', url)
      auth.removeMenuTab()
      auth.removeMenuList()
      if (this.isLogin && this.currentUser.isBind) {
        if (url == '/login') {
          window.location.reload()
          return
        }
        if (
          url ==
          '/index?type=http://8.134.76.179/index.php?m=login&token=94c750ea0f7f41d7753327792e937589'
        ) {
          window.open(
            'http://8.134.76.179/index.php?m=login&token=' +
            this.currentUser.code
          )
        } else if (url == '/user/profile') {
          this.$router.push({
            path: url
          })
        } else {
          this.handleClick(url)
        }
      } else if (this.isLogin && this.currentUser.isBind) {
        this.dialogVisible = true
        this.$message.error('请先完善信息！')
      } else {
        this.$message.error('请先登陆！')
      }
    },
    handleForgetPwd() {
      this.forgetDialogVisiable = true
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.Login(this.loginForm)
            .then(() => {
              this.isLogin = true
              this.loading = false
              this.getUser()
              this.getNav()
              // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    handleProfileCompleted() {
      this.dialogVisible = !this.currentUser.isBind
      this.getNav() //重新获取菜单
    }
  }
}
</script>

<style scoped>
.login-container {
  background-color: #F2F2F2;
}

/deep/ .el-dialog {
  background: url("../../assets/images/img_bg1.png") no-repeat;
  /* background-size: 100% 100%;
  height: 580px; */
  max-height: 520px;
  width: 800px;
}

@media screen and (min-width: 1440px) {
  .index-block {
    width: 1350px;
    overflow: hidden;
  }
}

@media screen and (max-width: 1439px) {
  .index-block {
    width: calc(100vw - 80px);
    overflow: hidden;
  }
}
</style>
