<template>
  <el-form
    ref="principal"
    :model="principal"
    :rules="rules"
    class="login-form"
  >
    <el-form-item prop="account">
      <el-input
        v-model="principal.account"
        clearable
        placeholder="您的账号"
        prefix-icon="el-icon-user"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="principal.password"
        auto-complete="new-password"
        clearable
        placeholder="您的密码"
        prefix-icon="el-icon-lock"
        show-password
        @focus="inputGetFocus"
        @keyup.enter.native="submitForm('principal')"
      ></el-input>
    </el-form-item>
    <el-form-item class="btns">
      <el-button
        :loading="loading"
        class="login-btn"
        size="medium"
        style="width: 100%"
        type="primary"
        @click="submitForm('principal')"
        @focus="inputGetFocus"
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import portal from '@/api/portal.js'

export default {
  name: 'AccountLogin',
  props: ['tenant', 'systemInformation'],
  computed: {
    language() {
      return localStorage.getItem('lang') || 'zh-CN'
    }
  },
  data() {
    var checkAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入账号'))
      }
      if (/^[a-zA-Z0-9_-]{2,20}$/.test(value)) {
        return callback()
      } else {
        return callback(new Error('账号格式不符合规范'))
      }
    }
    return {
      fullscreenLoading: true,
      hasMask: true,
      codeUrl: `${window.location.origin}/mobilevue`,
      frontBase: `${window.location.origin}`,
      logo: '',
      name: 'EDP',
      showTenant: false,
      showLogo: false,
      companyName: '',
      tenantName: '',
      principal: {
        account: '',
        password: ''
      },
      rules: {
        account: [{validator: checkAccount, trigger: 'blur'}],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      responseError: '',
      loading: false,

      totemStyle: {
        // backgroundColor: '#fff',
        // background: `url(${require('@/assets/img/loginImg.jpg')}) no-repeat center / 100% 100%`
        // background: `#1975FF url(${require("@/assets/img/totem.png")}) center / 100% auto no-repeat`
        // background: `transparent url(${require("@/assets/img/totem1.png")}) no-repeat center 30% / 100% 70% `
      }
    }
  },
  mounted() {
    window.webSocket && window.webSocket.close()
    this.clearUser()
    this.sysSetting()
  },
  methods: {
    //获取系统默认配置 系统Logo、名称
    sysSetting() {
      const _this = this
      let url =
        window.context.portal +
        '/sys/sysProperties/v1/getDecryptBySysSetting'
      this.$http.get(url).then((response) => {
        if (response && response.data && response.data.value) {
          _this.showTenant = true
          let sysSettingData = JSON.parse(response.data.value)
          if (sysSettingData.frontName == '') {
            _this.companyName = _this.name
          } else {
            _this.companyName = sysSettingData.frontName
          }
          if (sysSettingData.ico.length > 0) {
            let ico = sysSettingData.ico
            _this.showLogo = true
            _this.logo =
              window.context.portal +
              '/system/file/v1/downloadFile?fileId=' +
              ico[0].id
          }
        }
      })
    },
    querySearch(queryString, cb) {
      if (!queryString) {
        cb([])
        return
      }
      let queryFilter = {}
      queryFilter.pageBean = {
        page: 1,
        pageSize: 20,
        total: 0,
        showTotal: true
      }
      let query = {
        property: 'name_',
        value: queryString,
        group: 'main',
        operation: 'LIKE',
        relation: 'AND'
      }
      if (!queryFilter.querys) {
        queryFilter.querys = []
      }
      queryFilter.querys.push(query)

      this.$http
        .post(
          `${window.context.uc}/uc/tenantManage/v1/listJson`,
          queryFilter
        )
        .then((res) => {
          // 调用 callback 返回建议列表的数据
          cb(res.data.rows)
        })
    },
    handleSelect(item) {
      this.tenantName = item.name
      this.principal.tenantId = item.id
    },
    setRouterPath() {
      this.$store.dispatch(
        'login/actionLoginAccount',
        this.principal.account
      )
      localStorage.setItem(
        this.principal.account + 'loginRoutePath',
        this.$route.path
      )
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.inputGetFocus()
          this.setRouterPath()
          this.loading = true
          sessionStorage.clear()
          this.$store
            .dispatch('login/loginByPrincipal', this.principal)
            .then((loginStatus) => {
              if (!!loginStatus) {
                this.$store.dispatch(
                  'menu/getCurrentUserMethodAuth'
                )
                this.getAllDict()
                //获取前台页面所有菜单
                this.$store
                  .dispatch('menu/actionFrontMenus')
                  .then((res) => {
                    if (!res || !res.length) {
                      this.clearUser()
                      this.$message.warning(
                        '抱歉！您尚无可访问页面，请联系管理员添加！'
                      )
                    } else {
                      // 此段逻辑为调整中屏页面
                      /*let dataArr = res && res.filter(item => item.alias === 'bigScreen')
                          console.warn(res, dataArr, `/${dataArr[0].children[0].alias}`)
                          // 如果用户有大屏菜单进去大屏页面
                          if (dataArr && dataArr.length !== 0) {
                          if (dataArr[0].children.length !== 0) {
                              this.$router.push({
                              path: `/${dataArr[0].children[0].alias}`
                              })
                          }
                          } else {
                          // 如果用户没有大屏菜单 则根据第一角色查菜单
                          this.getRoleMenus()
                      }*/

                      // 此段逻辑为调整工作台页面
                      // 递归查询菜单树形结构中children第一项的最底层的调整路径

                      this.$store
                        .dispatch(
                          'login/checkUserInfoState'
                        )
                        .then((isFinishUserInfo) => {
                          if (!isFinishUserInfo) {
                            this.$router.push(
                              '/platLayout/personalInfo'
                            )
                          } else {
                            let {children} =
                            res &&
                            res.find(
                              (i) =>
                                i.alias ===
                                'normal'
                            )
                            const getPath = (
                              treeData,
                              path = ''
                            ) => {
                              // if (
                              //     Array.isArray(
                              //         treeData[0]
                              //             .children
                              //     ) &&
                              //     treeData[0]
                              //         .children
                              //         .length
                              // ) {
                              //     path += `/${treeData[0].alias}`
                              //     return getPath(
                              //         treeData[0]
                              //             .children,
                              //         path
                              //     )
                              // } else {
                              return (
                                path +
                                `/${treeData[0].alias}`
                              )
                              // }
                            }

                            this.$router.push(
                              getPath(
                                children,
                                '/platLayout'
                              )
                            )
                          }
                        })
                    }
                    this.loading = false
                  })
                // 连接websocket
                this.$bus.$emit('login')
                sessionStorage.setItem('isLogin', true)
              } else if (loginStatus === false) {
                this.$router.push({
                  name: 'resetPwdView',
                  query: {type: 'login'}
                })
              }
            })
            .catch((msg) => {
              this.loading = false
              console.log(msg, 'msg')
              if (
                msg.indexOf &&
                msg.indexOf('timeout of') !== -1
              ) {
                msg = '登录超时'
              }
              this.responseError = msg
            })
        } else {
          return false
        }
      })
    },
    loadRoleMenus(RoleCode) {
      return new Promise((resovle, reject) => {
        this.$store
          .dispatch('menu/actionsRoleMenu', RoleCode)
          .then((res) => {
            if (res.length) {
              let dataMenus =
                res &&
                res.filter((item) => item.alias === 'normal')
              if (dataMenus && dataMenus.length !== 0) {
                if (
                  dataMenus[0].children.length !== 0 &&
                  dataMenus[0].children[0].children.length
                ) {
                  this.$router.push({
                    path: `/platLayout/${dataMenus[0].children[0].children[0].alias}`
                  })
                } else {
                  this.$router.push({
                    path: `/platLayout/${dataMenus[0].children[0].alias}`
                  })
                }
              }
              resovle('enter')
            } else {
              resovle('nextRole')
            }
          })
      })
    },
    clearUser() {
      this.$store.dispatch('menu/clearMenus')
      this.$store.dispatch('user/clearUser')
      this.$store.dispatch('menu/setCopyMenus', [])
      this.$store.dispatch('login/logoutAndCleanUp')
    },
    async getRoleMenus() {
      let UserDetail = JSON.parse(
        sessionStorage.getItem('currentUserDetail')
      )
      let roleList = UserDetail.roleList
      console.log(roleList, 'roleList')
      // 多角色 找到第一个有菜单的角色
      for (let i = 0; i < roleList.length; i++) {
        console.log(roleList[i], 'resovle')
        let res = await this.loadRoleMenus(roleList[i].roleCode)
        console.log(res)
        if (res == 'enter') {
          // 设置当前角色
          let defaultRoleCode = roleList[i].roleCode
          sessionStorage.setItem('currentRoleCode', defaultRoleCode)
          break
        }
      }
    },
    getAllDict() {
      portal
        .getSysDict()
        .then((data) => {
          if (data) {
            sessionStorage.setItem(
              'dict_data',
              JSON.stringify(data)
            )
          }
        })
        .catch((err) => {
          console.log(err, '字典err')
        })
    },
    inputGetFocus() {
      this.responseError = ''
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../css/publicStyle.scss';

</style>
