<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2018-10-10 14:44:45
 * @LastEditors  : 无尘
 * @LastEditTime : 2020-02-26 19:11:31
 -->
<template>
  <div class="login-wrap">
    <section>
      <div class="login-body-top">
        <div class="login-body-head">
          <div class="login-body-head_inner border-box flex">
            <img class="login-body-logo" src="../../assets/logo.png" alt="logo" />
            <span class="login-body-title p-l-7">好办管理后台</span>
          </div>
        </div>
        <div class="login-body-qrcode">
          <div class="login-qrcode-inner border-box">
            <div class="qrcode-title font-18 color-303133 m-b-20">企业微信扫码登录</div>
            <div id="qrcode" title=""></div>
            <div class="qrcode-refresh m-t-20">
              <el-button class="font-12" type="text" @click="refreshCode">刷新 <span class="color-2f54eb iconfont iconshuaxin"></span></el-button>
            </div>
          </div>
        </div>
        <div class="bg-dot"></div>
        <div class="bg-dot-center"></div>
      </div>
      <div class="login-body-bottom"></div>
    </section>
    <footer class="p-t-35">
      <vue-gic-footer></vue-gic-footer>
    </footer>
  </div>
</template>
<script>
import { _debounce } from '@/common/js/public';
import QRCode from 'qrcodejs2';
import errMsg from '@/common/js/error';
import { postRequest } from '@/api/api';

export default {
  name: 'login',
  data() {
    return {
      qrcodeCase: '', // 二维码实例
      qrcodeNum: '', // 二维码数据
      enterpriseId: '', // 当前选择的 企业 id
      expiredFlag: false, // 二维码过期标志
      canSelectFlag: false, // 能否选择企业标志
      userId: '', // 返回的 userId
      ajaxTime: null,
      chooseTab: 'qrcode',
      // 企业列表
      enterpriseList: [
        /*{
                                                                        enterpriseId  : '1231',
                                                                        logoUrl: require("../../assets/logo.png"),
                                                                        enterpriseName: '达摩网络'
                                                                      },*/
      ],

      // 登录
      numberCode: ''
    };
  },
  computed: {},
  methods: {
    /**
     * 处理路由跳转
     */
    toRouterView(val) {
      const that = this;
      // 模拟检查数据,有两个参数
      that.$router.push({
        path: val.path
      });
    },
    /**
     * 选择登陆
     *
     */
    chooseLogin(e, flag) {
      const that = this;
      that.chooseTab = flag;
      // 如果密码登录，清空定时器
      document.getElementById('qrcode').innerHTML = '';
      that.qrcodeCase.clear(); // 先清除原有的
      clearInterval(that.ajaxTime);
      if (flag != 'pass') {
        that.getQrcode();
        that.expiredFlag = false; //隐藏过期遮罩层
      } else {
        // 修改登录参数
        that.qrcodeNum = '';
      }
      document.getElementById('line-active').style.width = e.target.offsetWidth + 'px';
      document.getElementById('line-active').style.left = e.target.offsetLeft + 'px';
    },

    /**
     *  折叠事件
     */
    collapseTag(val) {
      const that = this;
      that.collapseFlag = val;
    },

    /**
     *  生成二维码
     */
    qrcode(text) {
      const that = this;
      let qrObj = {
        type: 'web-login',
        data: text || '123456789'
      };
      that.qrcodeCase = new QRCode('qrcode', {
        width: 190,
        height: 190, // 高度
        text: JSON.stringify(qrObj) // 二维码内容 //
        //render: 'canvas', // 设置渲染方式（有两种方式 table和canvas，默认是canvas） //
        //background: '#f0f',
        //foreground: '#ff0'
      });

      document.getElementById('qrcode').title = '';
    },

    /**
     *  刷新二维码
     */
    refreshCode: _debounce(function() {
      const that = this;
      if (!!that.qrcodeCase) {
        document.getElementById('qrcode').innerHTML = '';
        that.qrcodeCase.clear(); // 先清除原有的
      }
      that.getQrcode();
      that.expiredFlag = false; //隐藏过期遮罩层
    }, 500),

    /**
     *  登录
     */
    toIndex: _debounce(function() {
      const that = this;
      that.toLogin();
    }, 500),

    /**
     *  登录 --- api
     */
    toLogin: _debounce(function() {
      const that = this;
      // if (!that.enterpriseId) {
      //   that.$message.error({
      //     duration: 1000,
      //     message: '请选择企业'
      //   });
      //   return false;
      // }
      let para = {
        qrcode: that.qrcodeNum || 'debug',
        enterpriseId: that.enterpriseId,
        userId: that.userId
      };
      postRequest('/haoban-manage3-web/login_local', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            localStorage.removeItem('userInfo');
            localStorage.setItem('userInfo', JSON.stringify(resData.result));
            // that.$router.push('/index');
            return;
          }
          if (resData.errorCode == 30004) {
            that.canSelectFlag = false;
            if (that.chooseTab == 'qrcode') {
              // that.getQrcode();
              that.expiredFlag = false; //隐藏过期遮罩层
            }
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }, 500),

    /**
     *  查询登录 --- api
     */
    checkLogin() {
      const that = this;
      let para = {
        qrcode: that.qrcodeNum
      };
      postRequest('/haoban-manage3-web/login-check', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && !!resData.result.enterpriseList && !!resData.result.enterpriseList.length) {
              that.enterpriseList = resData.result.enterpriseList;
              that.enterpriseId = that.enterpriseList[0].enterpriseId;
              that.userId = resData.result.userId;
              document.getElementById('qrcode').innerHTML = '';
              that.qrcodeCase.clear(); // 先清除原有的
              // that.ajaxTime = null;
              clearInterval(that.ajaxTime);
              // 如果只有一个企业
              if (resData.result.enterpriseList.length == 1) {
                that.toLogin();
                return false;
              }
              // 清空二维码，取消轮询
              that.canSelectFlag = true;
            }
            return;
          }
          if (resData.errorCode == 30002) {
            // 二维码失效
            that.expiredFlag = true;
          }
          errMsg.errorMsg(resData);
          // that.ajaxTime = null;
          clearInterval(that.ajaxTime);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    checkScan() {
      const that = this;
      clearInterval(that.ajaxTime);
      that.ajaxTime = null;
      that.ajaxTime = setInterval(function() {
        that.checkLogin();
      }, 3000);
    },

    /**
     *  登录---获取二维码字符串 API
     */
    getQrcode() {
      const that = this;
      postRequest('/haoban-manage3-web/get-login-qrcode', {})
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.qrcodeNum = resData.result;
            // that.qrcode(that.qrcodeNum);
            // that.checkScan();
            window.location.href = `${resData.result}`;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 密码登录
     */
    changeCode(val) {
      const that = this;
      that.numberCode = val;
    }
  },
  mounted() {
    const that = this;
    that.getQrcode();
    // that.toLogin();
    if (!!localStorage.getItem('userInfo')) {
      localStorage.removeItem('userInfo');
    }
  },
  components: {}
};
</script>
<style lang="less" scoped>
.login-wrap {
  width: 100%;
  min-height: 100vh;
  .p-l-7 {
    padding-left: 7px;
  }
  .login-body-top {
    position: relative;
    width: 100%;
    height: 431px;
    background-image: url('../../assets/login/bg.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
    background-color: #2f54eb;
    .login-body-head {
      width: 100%;
      .login-body-head_inner {
        width: 100%;
        padding: 22px 0 0 24px;
        img {
          width: 25px;
        }
        .login-body-title {
          font-weight: 600;
          color: #fff;
          font-size: 18px;
          padding-top: 5px;
        }
      }
    }
    .bg-dot {
      position: absolute;
      left: 50%;
      bottom: -93px;
      margin-left: -500px;
      width: 87px;
      height: 142px;
      background-image: url('../../assets/login/bg-dot.png');
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center center;
    }
    .bg-dot-center {
      position: absolute;
      left: 50%;
      bottom: -233px;
      margin-left: -71px;
      width: 142px;
      height: 87px;
      background-image: url('../../assets/login/bg-dot-center.png');
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center center;
    }
    .login-body-qrcode {
      position: absolute;
      left: 50%;
      bottom: -173px;
      margin-left: -183px;
      width: 366px;
      height: 343px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 6px 8px 0px rgba(208, 213, 232, 0.27);
      border-radius: 5px;
      z-index: 1;
      .login-qrcode-inner {
        width: 100%;
        padding: 40px 88px 25px 88px;
        text-align: center;
        #qrcode {
          width: 190px;
          height: 190px;
        }
      }
    }
  }
  .login-body-bottom {
    width: 100%;
    height: 300px;
    background: #fff;
  }
}
</style>
