<template>
  <div
    class="login-container"
    @keyup.enter.native="handleLogin">
    <div class="login-weaper animated bounceInDown">

      <div class="login-left">
        <span>目标</span>
        <el-divider/>
        <span>为了提高粮食贸易周转速度及粮食承运的效率 ，契合当下传统粮食贸易行业向互联网模式转变的市场方向。方便管理员和操作员的一些实时管理操作，解决业务人工处理时所带来的低效率、易出错和难管理等问题。我们致力于开发一款结合线上采销信息公布、物流线上操作、行情信息分析展示等等粮食贸易行业全业务链、全方位的线上服务平台，以解决行业痛点，发展行业E+经营模式为目标。</span>

        <el-divider/>
        <span>易粮易运APP技术支持</span>
        <el-divider/>
        <span>联系方式：微信 ccjgmwz </span>
        <span>手机 18241771147</span>
        <span>QQ 841968545</span>
        <span>邮箱 ccjgmwz@foxmail.com</span>
        <span>联系地址：辽宁省营口市鲅鱼圈区</span>
        <span>联系人：程长江</span>
      </div>
      <div class="login-border">
        <div class="login-main">
          <!-- <img
            class="img"
            src="@/assets/LOGO.png"
            alt=""> -->
          <h4 class="login-title">
            易粮易运
          </h4>
          <el-form
            ref="loginForm"
            :rules="loginRules"
            :model="loginForm"
            class="login-form"
            status-icon
            label-width="0">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="small"
                auto-complete="off"
                @keyup.enter.native="handleLogin">
                <i
                  slot="prefix"
                  class="icon-yonghu"/>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :type="passwordType"
                v-model="loginForm.password"
                placeholder="请输入密码"
                size="small"
                auto-complete="off"
                @keyup.enter.native="handleLogin">
                <i
                  slot="suffix"
                  class="el-icon-view el-input__icon"
                  @click="showPwd"/>
                <i
                  slot="prefix"
                  class="icon-mima"/>
              </el-input>
            </el-form-item>
            <!-- <el-form-item prop="code">
              <el-input
                v-model="loginForm.verifyCode"
                placeholder="输入验证码"
                size="small"
                auto-complete="off"
                @keyup.enter.native="handleLogin">
                <i
                  slot="prefix"
                  class="icon-yanzhengma"
                  style="margin-top:6px;"/>
                <template slot="append">
                  <span
                    :class="[{display:!show}]"
                    class="msg-text"
                    @click="sendShortMsg">{{ show ? '验证码' : count }}</span>
                </template>
              </el-input>
            </el-form-item> -->
            <el-form-item>
              <el-button
                type="primary"
                size="small"
                class="login-submit"
                @click.native.prevent="handleLogin">登录</el-button>
            </el-form-item>
          </el-form>

          <div class="login-menu">
            <el-link :underline="false" href="https://taohaoliang.oss-cn-beijing.aliyuncs.com/app/%E6%98%93%E7%B2%AE%E6%98%93%E8%BF%901.1.apk" target="_blank" >
              <el-button class="filter-item" type="primary" size="mini" icon="el-icon-download">下载APP</el-button>
            </el-link>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import { sendMsg, getAdminId } from '@/api/login'
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (validateUsername == null) {
        callback(new Error('请输入正确的管理员用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('管理员密码长度应大于6'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        verifyCode: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        verifyCode: [
          { required: false, trigger: 'blur', message: '验证码不能为空' }
        ]
      },
      passwordType: 'password',
      loading: false,
      verifyLoading: false,
      show: true,
      count: '',
      timer: null
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan)
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  },
  methods: {
    sendShortMsg() {
      if (!this.show) {
        this.$notify.error({
          title: '失败',
          message: '请等待60s后重试'
        })
        return
      }
      if (this.loginForm.username == null || this.loginForm.username === '' || this.loginForm.password == null || this.loginForm.password === '') {
        this.$notify.error({
          title: '失败',
          message: '请先填写用户名和密码'
        })
        return false
      }
      this.verifyLoading = true
      sendMsg(this.loginForm)
        .then(response => {
          this.verifyLoading = false
          this.$notify.success({
            title: '成功',
            message: '信息发送成功'
          })
          const TIME_COUNT = 60
          if (!this.timer) {
            this.count = TIME_COUNT
            this.show = false
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
              } else {
                this.show = true
                clearInterval(this.timer)
                this.timer = null
              }
            }, 1000)
          }
        })
        .catch(response => {
          this.verifyLoading = false
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
          this.verifyLoading = false
        })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    initWebSocket () {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage
      // 连接成功
      this.websocket.onopen = this.setOnopenMessage

      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage

      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage () {
      console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
    },
    setOnopenMessage () {
      console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)
    },
    setOnmessageMessage (event) {
      // 根据服务器推送的消息做自己的业务处理
      console.log('服务端返回：' + event.data)
      var msg = event.data.split('$')
      var that = this
      this.$notify.warning({
        title: '新消息提醒',
        message: msg[0],
        duration: 0,
        onClick() {
          that.$router.push({
            path: msg[1] }) // 你要跳转的路由 还可以传参 当然也可以通过其他方式跳转
        }
      })
      var currentPage = that.$router.history.current.path
      that.$router.push({ path: '/' })
      that.$router.push({ path: currentPage })
    },
    setOncloseMessage () {
      console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        this.loginForm.verifyCode = '666666'
        if (valid && !this.loading) {
          this.loading = true
          this.$store
            .dispatch('LoginByUsername', this.loginForm)
            .then(() => {
              getAdminId().then(response => {
                this.loading = false
                // WebSocket
                this.$store.dispatch('setAdminId', response.data.data)
                if ('WebSocket' in window) {
                  if (process.env.NODE_ENV === 'production') {
                    this.websocket = new WebSocket('wss://www.zthymaoyi.com/wss/websocket/' + response.data.data)
                  }
                  else {
                    this.websocket = new WebSocket('ws://localhost:8080/websocket/' + response.data.data)
                  }
                  this.initWebSocket()
                } else {
                  alert('当前浏览器不支持websocket')
                }
              })
              this.$router.push({ path: '/' })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.loading = false
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style>
.msg-text {
  display: block;
  width: 60px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
}
.msg-text.display {
  color: #ccc;
}
</style>

<style lang="scss">
@import "@/styles/login.scss";
</style>
