<template>
  <div class="main">
    <div v-if="isShow" @click="dingding" class="change-img">
      <img src="~@/assets/login/qr-code.png" alt="" />
    </div>
    <div v-else @click="dingding" class="change-img">
      <img src="~@/assets/login/computer.png" alt="" />
    </div>
    <!-- <a-modal
      :visible="visible"
      :maskClosable='true'
      :bodyStyle='styles'
      :footer="null"
      :closable='false'
    >
       <a-spin />
    </a-modal> -->
    <div v-show="isShow">
      <span
        v-for="(item, index) in tagNacData"
        :key="index"
        @click="otherLogin(index)"
        :class="['login-tag', { active: activeClass === index }]"
      >{{ item }}</span
      >
      <a-form-model id="formLogin" ref="form" class="user-layout-login" :model="form" :rules="rules">
        <a-alert
          v-if="isLoginError"
          type="error"
          showIcon
          style="margin-bottom: 24px"
          :message="loginErrorInfo"
          closable
          :after-close="handleCloseLoginError"
        />
        <a-form-model-item prop="username" class="item">
          <div class="bg1"></div>
          <a-input v-model="form.username" size="large" placeholder="账户: ">
            <!-- <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/> -->
          </a-input>
        </a-form-model-item>
        <a-form-model-item prop="password" class="item">
          <div class="bg2"></div>
          <a-input-password v-model="form.password" size="large" placeholder="密码:">
            <!-- <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/> -->
          </a-input-password>
        </a-form-model-item>
        <!-- <a-row :gutter="16" v-if="captchaOnOff">
        <a-col class="gutter-row" :span="16">
          <a-form-model-item prop="code">
            <a-input v-model="form.code" size="large" type="text" autocomplete="off" placeholder="验证码">
              <a-icon slot="prefix" type="security-scan" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <img class="getCaptcha" :src="codeUrl" @click="getCode">
        </a-col>
      </a-row> -->
        <a-form-model-item prop="rememberMe" class="login-form-forget">
          <div class="remember-div">
            <a-checkbox class="remember" :checked="form.rememberMe" @change="rememberMe">记住密码
            </a-checkbox
            >
            <a @click="forgetPassword">忘记密码？</a>
          </div>
        </a-form-model-item>
        <a-form-item style="margin-top: 24px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="logining"
            :disabled="logining"
            @click="beforeSubmit"
          >登录
          </a-button
          >
        </a-form-item>
      </a-form-model>
    </div>
    <div v-show="!isShow" id="ding-login"></div>
    <div class="user-login-other">
      <!-- <a
        href="https://login.dingtalk.com/oauth2/challenge.htm?redirect_uri=http%3A%2F%2Fmanage.suntien.com:7926%2FCAS%2Fuser%2FsystemNavs&response_type=code&client_id=dingyenfym0ywhwta22o&scope=openid&state=dddd&prompt=consent"><img
          src="~@/assets/dingding.png"
          alt=""></a>
      <div>其他登录方式</div> -->
      <!-- <iframe src="https://login.dingtalk.com/oauth2/challenge.htm?redirect_uri=http%3A%2F%2Flocalhost:8000%2Fuser%2Flogin&response_type=code&client_id=dingyenfym0ywhwta22o&scope=openid&state=dddd&prompt=consent" frameborder="0" width="350px" height="600px"></iframe> -->
      <!--
          ruoyi后台不支持获取是否开启账户.
          故此处不做隐藏处理. 在ruoyi原前端中是在注册页面定义一个属性手动修改处理.
        -->
      <!-- <router-link class="register" :to="{ name: 'register' }">注册账户</router-link> -->
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { verificationLogin, DDLogins } from '@/api/login'
// import Cookies from 'js-cookie'
import { LOGIN_USERNAME, LOGIN_PASSWORD, LOGIN_REMEMBERME, ACCESS_TOKEN } from '@/store/mutation-types'
import { getInfoByIP } from '@/api/security/ip'
import { getAnonPolicyByType } from '@/api/security/policy'

import storage from 'store'
import qs from 'qs'
// 钉钉后台获取的appid和appSecret，appSecret没有用到扫码中
const appid = 'dingyenfym0ywhwta22o'
// 重定向地址，因为vue用的hash，所以网址后面是 #/
const redirect = encodeURIComponent(`http://localhost:8000/SSO/user/systemNavs`)
// 官网给的跳转连接格式
const http_url = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${redirect}`)
export default {
  components: {},
  data () {
    return {
      ip: '',
      code: qs.parse(window.location.hash.substring(3)).code, // 获取的临时登陆码
      tagNacData: ['欢迎您登录'],
      activeClass: 0,
      codeUrl: '',
      isLoginError: false,
      loginErrorInfo: '',
      form: {
        username: '',
        password: '',
        code: undefined,
        uuid: '',
        rememberMe: false
      },
      rules: {
        username: [{ required: true, message: '请输入帐户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      logining: false,
      captchaOnOff: true,
      isShow: true,
      appid: 'dingyenfym0ywhwta22o',
      url: encodeURIComponent('http://localhost:8000/'),
      visible: true,
      styles: {
        backgroundColor: 'rgba(0, 0, 0, 0.45)'
        // opacity:0.2
      },
      backAddr: null

    }
  },
  created () {
    this.getStorage()
    const { code, joinsysCode, BackAddr } = this.$route.query
    if (code) {
      /* 这里写登录方法 */
      this.handleCodeLogin(code)
    }
    // 判断系统回跳地址是否存在。
    if (BackAddr) {
      this.backAddr = BackAddr
      console.log('BackAddr', this.backAddr)
    }
    // if (joinsysCode) {
    //   this.verificationLogin(joinsysCode)
    // }

    // 获取到扫码结果，并且跳转获取临时登录码
    var handleMessage = function (event) {
      var origin = event.origin
      if (origin === 'https://login.dingtalk.com') { // 判断是否来自ddLogin扫码事件。
        // 拿到 loginTmpCode 后，跳转连接拿到临时登陆码，之后返回到跳转的地址，会携带临时登陆码
        var loginTmpCode = event.data
        const url = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${http_url}&loginTmpCode=${loginTmpCode}`
        // 这边直接打开拼接好的连接，去获取临时登录码，回来地址在下面
        location.href = url
      }
    }
    if (typeof window.addEventListener !== 'undefined') {
      window.addEventListener('message', handleMessage, false)
    } else if (typeof window.attachEvent !== 'undefined') {
      window.attachEvent('onmessage', handleMessage)
    }
    // this.getCode()
  },
  // watch: {
  //   // 如果 `isShow` 发生改变，这个函数就会运行
  //   isShow: function (newQuestion, oldQuestion) {
  //     if (!this.isShow) {
  //       this.ddInit()
  //     }
  //     console.log(`1`, 1)
  //   }
  // },
  mounted () {
    // const { authCode } = this.$route.query
    // console.log(`this.$route.query`, this.$route.query)
    // if (authCode) {
    //   // 登录接口
    //   this.handleCodeLogin(authCode)
    // } else {
    // }
    //   var obj = DDLogin({
    //   id: 'login_container', // 这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
    //   goto: encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingyenfym0ywhwta22o&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://localhost:8000'), // 请参考注释里的方式
    //    style: 'border:none;background-color:#FFFFFF;',
    //    width: '100%',
    //    height: '300'
    // })
  },
  methods: {
    // ddInit () {
    //   const goto = encodeURIComponent(
    //     `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.url}`
    //   )
    //   window.DDLogin({
    //     id: 'login_container',
    //     goto, // 请参考注释里的方式
    //     style: 'border:none;background-color:#FFFFFF;',
    //     width: '100%',
    //     height: '300'
    //   })

    //   const handleMessage = (event) => {
    //     const origin = event.origin
    //     console.log('origin', event.origin)
    //     if (origin === 'https://login.dingtalk.com') {
    //       // 判断是否来自ddLogin扫码事件。
    //       const loginTmpCode = event.data
    //       // 获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
    //       console.log('loginTmpCode', loginTmpCode)
    //       window.location.href = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.url}&loginTmpCode=${loginTmpCode}`
    //     }
    //   }
    //   if (typeof window.addEventListener !== 'undefined') {
    //     window.addEventListener('message', handleMessage, false)
    //   } else if (typeof window.attachEvent !== 'undefined') {
    //     window.attachEvent('onmessage', handleMessage)
    //   }
    // },
    // setCode () {
    //   window.DDLogin(
    //     {
    //       id: 'login_container',
    //       width: 300,
    //       height: 300
    //     },
    //     {
    //       redirect_uri: encodeURIComponent('http://localhost:8000/user/login'),
    //       client_id: 'dingyenfym0ywhwta22o',
    //       appid: 'dingyenfym0ywhwta22o',
    //       scope: 'openid',
    //       response_type: 'code',
    //       prompt: 'consent'
    //     },
    //     (loginResult) => {
    //       const { redirectUrl, authCode, state } = loginResult
    //       // 这里可以直接进行重定向
    //       window.location.href = redirectUrl
    //       // 也可以在不跳转页面的情况下，使用code进行授权
    //       console.log(authCode)
    //     },
    //     (errorMsg) => {
    //       // 这里一般需要展示登录失败的具体原因
    //       alert(`Login Error: ${errorMsg}`)
    //     }
    //   )
    // },
    // dingLogin () {
		// 	this.isShow = 'ding'
		// 	// 这边需要用 $nextTick() 方法来等DOM渲染完成后，才能获取到盒子容器（$nextTick 方法见另一篇文章）
		// 	this.$nextTick(() => {
		// 	// 钉钉登录，参数文档中那些其他项就不展示了，按照文档自己配置就可以
		// 		var obj = DDLogin({
		// 			id: 'ding-login',
		// 			goto: http_url,
		// 			style: 'border:none;background-color:#FFFFFF;'
		// 		})
		// 		// 重置扫码登录框的样式，让登录框居中
		// 	})
		// },
    dingding () {
      this.isShow = !this.isShow
      this.$nextTick(() => {
			// 钉钉登录，参数文档中那些其他项就不展示了，按照文档自己配置就可以
				var obj = DDLogin({
					id: 'ding-login',
					goto: http_url,
          style: 'border:none;background-color:#FFFFFF;',
          width: '100%',
          height: '300'
				})
				// 重置扫码登录框的样式，让登录框居中
			})
    },
    otherLogin (index) {
      this.activeClass = index
      index === 0 ? (this.loginFlag = false) : (this.loginFlag = true)
    },
    // getCode () {
    //   getCodeImg().then((res) => {
    //     this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff
    //     if (this.captchaOnOff) {
    //       this.codeUrl = 'data:image/gif;base64,' + res.img
    //       this.form.uuid = res.uuid
    //     }
    //   })
    // },
    getStorage () {
      const username = storage.get(LOGIN_USERNAME)
      const password = storage.get(LOGIN_PASSWORD)
      const rememberMe = storage.get(LOGIN_REMEMBERME)
      if (username) {
        this.form = {
          username: username,
          password: password,
          rememberMe: rememberMe
        }
      }
    },
    rememberMe (e) {
      this.form.rememberMe = e.target.checked
    },
    ...mapActions(['Login', 'Logout']),

    // 判断IP是否在黑名单中
    beforeSubmit () {
        // 策略类别(1.密码2.登录3.IP)
        getAnonPolicyByType('3').then(response => {
            if (response.data.status === 'true') {
              getInfoByIP().then(response => {
                if (response.data) {
                   this.$notification['error']({
                    message: '注意',
                    description: '您的IP不允许访问该程序!'
                  })
                } else {
                  this.handleSubmit()
                }
              })
            } else {
              this.handleSubmit()
            }
        })
    },
    handleSubmit () {
      this.logining = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.rememberMe) {
            storage.set(LOGIN_USERNAME, this.form.username)
            storage.set(LOGIN_PASSWORD, this.form.password)
            storage.set(LOGIN_REMEMBERME, this.form.rememberMe)
          } else {
            storage.remove(LOGIN_USERNAME)
            storage.remove(LOGIN_PASSWORD)
            storage.remove(LOGIN_REMEMBERME)
          }
          this.Login(this.form)
            .then((res) => {
              this.loginSuccess(this.form)
            })
            .catch((err) => this.requestFailed(err))
            .finally(() => {
              this.logining = false
            })
        } else {
          setTimeout(() => {
            this.logining = false
          }, 600)
        }
      })
    },
    loginSuccess (res) {
      sessionStorage.setItem('username', res.username)
      sessionStorage.setItem('password', res.password)
      // const { BackAddr } = this.$route.query
      // if (BackAddr) {

      // } else {
      // }
      if (this.backAddr != null) {
        // var url = decodeURIComponent(Cookies.get('BackAddr'))
        console.log('this.backAdd', this.backAddr)
        window.location.href = this.backAddr
      } else {
        this.$router.push({ path: 'systemNav' })
      }
      // this.$router.push({ path: 'systemNav' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.handleCloseLoginError()
    },
    requestFailed (err) {
      this.isLoginError = true
      this.loginErrorInfo = err
      this.form.code = undefined
      if (this.captchaOnOff) {
        // this.getCode()
      }
    },
    handleCloseLoginError () {
      this.isLoginError = false
      this.loginErrorInfo = ''
    },
    // 忘记密码
    forgetPassword () {
      this.$router.push('forgetPassword')
    },
    handleCodeLogin (code) {
      DDLogins(code)
        .then((res) => {
          if (res.token) {
            storage.set(ACCESS_TOKEN, res.token, 7 * 24 * 60 * 60 * 1000)
            this.$router.push({ path: '/user/systemNav' })
          }
        }).catch((err) => {
        console.log(`err`, err)
        this.$router.push({ path: '/user/login' })
      })
    },
    verificationLogin (joinsysCode) {
      // debugger
      if (joinsysCode !== null) {
        verificationLogin({ joinsysCode: joinsysCode }).then((res) => {
          console.log(res.msg)
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  margin-top: 20px;

  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 80%;
    height: 40px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }
}

.user-login-other {
  display: flex;
  justify-content: space-between;
  align-content: center;

  img {
    width: 35px;
  }
}

.login-tag {
  font-size: 30px;
  cursor: pointer;
  color: #4d81f6;
  margin-bottom: 200px;
}

.active {
  position: relative;
  // font-weight: bold;

  &::after {
    content: '';
    position: absolute;
    left: 0;
    bottom: -30%;
    width: 60%;
    height: 3px;
    background: #3b75f5;
  }
}

.bg1 {
  position: absolute;
  width: 25px;
  height: 25px;
  z-index: 2;
  margin: 7px 17px 0 7px;
  background: url('../../../public/own.png') no-repeat;
  background-size: 100% 100%;
}

.bg2 {
  position: absolute;
  z-index: 2;
  width: 25px;
  height: 25px;
  margin: 7px 17px 0 7px;
  background: url('../../../public/password.png') no-repeat;
  background-size: 100% 100%;
}

.item {
  position: relative;
  // background-color: #ffffff;
}

.item /deep/ .ant-form-item-children .ant-input {
  padding-left: 45px !important;
}

.login-form-forget {
  height: 15px;
}

/deep/ .ant-checkbox + span {
  font-size: 14px !important;
  color: #1890ff !important;
}

/deep/ .ant-form-item-control {
  line-height: 0px;
}

.remember-div {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
}

.change-img {
  position: absolute;
  top: 5%;
  right: 5%;

  img {
    width: 71px;
  }
}
</style>
