<template>
    <div>
        <form-data :item="config" ref="form" @keyUpEnter="handleLogin">
            <!-- <template slot="verification">
                <img v-if="showVerify" class="imgCode" :src="verificationCodeSrc" title="获取验证码" @click="fetchGetVerificationCode" />
            </template> -->
            <template slot="default">
                <v-btn
                    :loading="loading"
                    color="primary"
                    style="width: 100%; margin-bottom: 30px;"
                    @click.native.prevent="handleLogin"
                >
                    登 录
                </v-btn>
            </template>
        </form-data>
    </div>
</template>

<script>

import FormData from '@/components/Form'
// import {
// getSettingInfo
// setBurialPoint
// } from '@/api/system'
import { mapMutations } from 'vuex'

export default {
  name: 'login-page',
  components: { FormData },
  data () {
    return {
      loading: false,
      config: {
        options: [
          {
            label: '登录账号',
            type: 'text',
            key: 'username',
            value: '',
            outlined: true,
            class: 'mt-5',
            autofocus: true,
            prependInnerIcon: 'mdi-account',
            autocomplete: 'username',
            rules: [v => !!v || '请填写登录账号'],
            keyupEnterNative: this.handleLogin,
            change: this.handleChange
          },
          {
            label: '密码',
            type: 'password',
            key: 'password',
            value: '',
            outlined: true,
            prependInnerIcon: 'mdi-lock',
            rules: [v => !!v || '请填写密码'],
            appendIcon: 'mdi-eye-off-outline',
            autocomplete: 'current-password',
            keyupEnterNative: this.handleLogin,
            clickAppend: this.clickAppendPasswordType,
            change: this.handleChange
          }
          // {
          //   label: '验证码',
          //   type: 'text',
          //   key: 'verificationCode',
          //   slotName: 'verification',
          //   rules: [v => !!v || '请填写验证码'],
          //   hide: true,
          //   value: '',
          //   outlined: true,
          //   prependInnerIcon: 'mdi-email',
          //   keyupEnterNative: this.handleLogin,
          //   change: this.handleChange
          // }
        ]
      },
      queryForm: {
        username: '',
        password: ''
        // verificationCode: ''
      },
      passwordType: false,
      errorCount: 0,
      errorCountTop: 3,
      showVerify: false,
      // verificationCodeSrc: '',
      query: '1'
    }
  },
  // watch: {
  //   error (val) {
  //     if (val) {
  //       this.open()
  //     }
  //   }
  // },
  methods: {
    ...mapMutations('system', ['SET_SYSTEM_INFO']),
    // open () {
    //   this.config.options.find(e => e.key === 'verificationCode').hide = false
    //   this.fetchGetVerificationCode()
    //   this.showVerify = true
    // },
    handleChange (v) {
      Object.assign(this.queryForm, v)
    },
    async handleLogin () {
      if (this.$refs.form.$refs.form.validate()) {
        this.loading = true
        try {
          const query = Object.assign(this.queryForm, {
            query: this.query
          })
          await this.$store.dispatch('user/login', query)
          const routes = await this.$store.dispatch('menu/getMenu2')
          if (!routes.length) {
            this.$snackbar.error('没有访问权限')
            return
          }
          this.$snackbar.success('登录成功')
          // const { data } = await getSettingInfo({ path: '', hostName: '' })
          // this.SET_SYSTEM_INFO(this.flattenObject(data))
          if (this.$route.query?.redirect) {
            this.$router.push(this.$route.query.redirect)
            return
          }
          // 登录成功记录访问 + 1
          // this.handleBurialPoint()
          this.$router.push('/')
        } catch (error) {
          // if (typeof error === 'object' && error?.code) {
          //   this.$snackbar.error(error.msg || error)
          //   this.open()
          //   return
          // }
          // // 生成验证码
          // this.fetchGetVerificationCode()
          this.$snackbar.error(error)
        } finally {
          this.loading = false
        }
      }
    },
    // async handleBurialPoint () {
    //   try {
    //     await setBurialPoint({ accessRecordIndex: 'home' })
    //   } catch (error) {
    //     console.log('访问新增失败')
    //   }
    // },
    // fetchGetVerificationCode () {
    //   const api = this.$api
    //   const rand = Math.ceil(Math.random() * 10)
    //   this.query = Math.ceil(Math.random() * 1000)
    //   this.verificationCodeSrc = `${api}/authentication/get/verificationCode?type=login&rand=${rand}&query=${this.query}`
    // },
    clickAppendPasswordType () {
      this.passwordType = !this.passwordType
      if (this.passwordType) {
        this.config.options[1].type = 'text'
        this.config.options[1].appendIcon = 'mdi-eye-outline'
        return
      }
      this.config.options[1].type = 'password'
      this.config.options[1].appendIcon = 'mdi-eye-off-outline'
    },
    // 获取个性化配置信息
    flattenObject (obj) {
      let result = {}
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          const value = obj[key]
          if (typeof value === 'object' && value !== null) {
            result = { ...result, ...this.flattenObject(value, key) }
          } else {
            result[key] = value || null
          }
        }
      }
      return result
    }
    // async getInfo () {
    //   try {
    //     const { data } = await getSettingInfo({ path: '', hostName: '' })
    //     this.SET_SYSTEM_INFO(this.flattenObject(data))
    //   } catch (error) {
    //     this.$snackbar.error(error)
    //   }
    // }
  }
}
</script>
<style lang="scss" scoped>
.imgCode {
  position: absolute;
  width: 100px;
  height: 40px;
  top: 8px;
  right: 10px;
}
</style>
