<template>
  <div class="login-container">
    <div class="all">
      <div class="login_logo">
        <a href="#" target="_self" title="功道云-积分系统用户登录"><img src="static/images/login-logo_20200603.png"></a>
      </div>
      <div>
        <img src="static/images/src=http___dingyue.nosdn.127.net_SM=WIGOFt0qHbUErqhHznlIUUXEp6vq=5nrCxFOZ3YjCO1506947851488.gif&refer=http___dingyue.nosdn.127.gif" style="" alt="">
      </div>
      <div class="login_box" style="display:none">
        <div class="flex-box">
          <div class="login_ad">
            <div class="left-box">
            </div>
          </div>
          <div class="login_input" v-if="!login_icon_show">
            <el-form class="login-form" autocomplete="on" :model="loginForm" :rules="loginRules" ref="loginForm"
              label-position="left">
              <div class="title-container">用户登录</div>
              <div class="form-box-login">
                <el-form-item prop="tel" class="login_tel">
                  <span class="label">+86</span>
                  <el-input class="input_tel" clearable name="tel" type="text" oninput="value=value.replace(/[^\d]/g,'')"
                    v-model="loginForm.tel" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item prop="password" class="login_pwd">
                  <el-input clearable name="password" :type="passwordType"  v-model="loginForm.password"
                    placeholder="请输入功道云登录密码" />
                  <span class="show-pwd" @click="showPwd">
                    <svg-icon v-if="passwordType == 'password'" icon-class="eye" />
                    <svg-icon v-else icon-class="eyeOpen" />
                  </span>
                </el-form-item>

                <div class="login_keeppwd">
                  <template>
                    <el-checkbox v-model="checked">记住密码</el-checkbox>
                  </template>
                </div>

                <el-button class="login_forgepwd" type="text" @click="$router.push({name:'forgetPwd'})" style="float:right">{{$t('login.forget')}}
                </el-button>

                <el-button type="primary" style="width:100%; font-size: 16px; padding:15px 20px; margin-bottom:20px;"
                  :loading="loading" :disabled="login_disabled" @click.native.prevent="handleLogin">{{$t('login.logIn')}}
                </el-button>

            <!-- <el-button class="login_forgepwd" type="text" @keyup.enter.native="$router.push({name:'forgetPwd'})" style="float:right">{{$t('login.forget')}}</el-button> -->
            <!-- <el-button
              type="primary"
              style="width:100%; font-size: 16px; padding:15px 20px; margin-bottom:20px;"
              :loading="loading"
              @click.native.prevent="handleLogin"
            >{{$t('login.logIn')}}
            </el-button> -->
            <div class="login_reg">
              <el-button type="text" @click="$router.push({name:'reg'})" style="float:right">
                <span style="color:#909399">还没账号？</span>
                <span>免费注册体验</span>
              </el-button>
            </div>
                <!--<span @click="$router.push({name:'invite_new_company'})">邀请</span>-->

                <div style="padding:8px;"></div>
              </div>
            </el-form>
          </div>
        </div>


        <div class="login_type_icon">
          <div class="login_code" style="display: none" v-if="!login_icon_show" @click="switchbtn"></div>
          <div class="login_default" v-if="login_icon_show" @click="login_icon_show = !login_icon_show"></div>
        </div>
        <div v-if="login_icon_show" class="login_code_box">
          <span class="title">扫码登录</span>
          <div class="code">
            <div class="mack" v-show="code_overdue" @click="get_code()">
              <div style="margin-bottom: 10px;"><i class="el-icon-refresh"></i></div>
              <span>请重新获取二维码</span>
            </div>
            <div id="qrcode"></div>
          </div>
          <span>打开 功道云 App</span>
          <span>在「消息」页面右上角打开扫一扫</span>

          <!--<div class="social_soft">-->
          <!--<span class="title">社交账号登录</span>-->
          <!--<svg-icon icon-class="wechat_green"/>-->
          <!--<div class="download_app">-->
          <!--<img src="static/images/logo.png">-->
          <!--<span>下载功道云 App</span></div>-->
          <!--</div>-->

        </div>
        <el-dialog :title="$t('login.dialogVisible')" :visible.sync="dialogVisible" append-to-body width="400">
          <el-button style="margin:5px 0; width:100%;" @click="loginBySite(item.site.id)" v-for="(item,index) in site_list"
            :key="index" size="medium">{{item.site.name}}
          </el-button>
        </el-dialog>
        <pastDue></pastDue>
        <!-- <el-dialog :visible.sync="$store.state.user.pastDue" width="400px" append-to-body class="pastDue" @close="pastDueclose">
            <p style="font-size:21px;">系统已到期</p>
            <p style="margin:0;">请在功道云积分服务群中联系专属客服或微信扫码添加功道云客服进行续费</p>
            <img src="static/images/statistics_NO1.png" style="width:100%">
            <p style="font-size:20px;">电话咨询：400-6877-880</p>
        </el-dialog> -->
      </div>
      <div class="footer_copyright">
        <!-- <span class=""><img src="static/images/little_line.png">积分制管理 · 员工精细化管理<img src="static/images/little_line.png"></span> -->
        <span class="copyright">Copyright © 2020 广东功道云数字科技有限公司 All Rights Reserved</span>
      </div>
    </div>
  </div>



</template>

<script>
 import pastDue from "@/views/common/pastDue.vue"
  import QRCode  from "qrcodejs2"
  import {isvalidUsername} from '@/utils/validate'
  import {getToken, setToken, getUser, getPasw, setUser, setPasw,} from '@/utils/auth' // getToken from cookie
  import requests from '@/utils/request-user'
  import { constants } from 'fs'
  import { timestamps } from '@/utils/index'

  export default {
    data() {
      const validateUsername = (rule, value, callback) => {
        if (value == '') {
          callback(new Error("请输入有效的手机号码"))
        } else if(!(/^1[0123456789]\d{9}$/.test(value))){
          callback(new Error('手机号格式错误!'));
        }else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error(this.$t("login.validatePassword")))
        } else {
          callback()
        }
      }
      return {
        checked: true,
        login_icon_show: false,
        login_type:false,
        dialogVisible: false,
        tel5: '',
        site_list: [],
        loginForm: {
          tel: '',
          password: ''
        },
        loginRules: {
          tel: [
            {required: true, trigger: 'blur', validator: validateUsername}
          ],
          password: [
            {required: true, trigger: 'blur', validator: validatePassword}
          ]
        },
        passwordType: 'password',
        loading: false,
        showDialog: false,
        code_loading: false,
        code_overdue: false,
        login_code: '',
        login_disabled: true,
        token: ''
      }
    },
    components:{QRCode,pastDue},
    methods: {
      // pastDueclose(){
      //   this.$store.dispatch('LogOut');
      //   this.$store.state.user.pastDue = false;
      // },
      loginBySite(sid) {
        let self = this
        requests({
          url: '/api/employee-login',
          method: 'post',
          data: {site_id: sid}
        }).then((res) => {
          if (res.data.code == 1) {
            setToken(res.data.data.token)
            self.$store.commit('SET_TOKEN', res.data.data.token)
            let manager = res.data.data.user.employee_detail.role_list.findIndex((item) => {
              return item.name == "creator" || item.name == "admin" || item.name == "point_manager" || item.name == "dept_manager"
            })
            if(manager >= 0){
              self.$router.push({path: '/'})
            }else{
              this.$confirm('电脑版暂未开放【员工】的使用，请使用功道云APP', '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              }).then(() => {
                this.logout()
              }).catch(() => {
                this.logout()
              });
            }
          }else{

          }
        })
      },
      loginExperience() {//进入体验站点
        let self = this
        let num = 112//112是其中一个体验公司
        let jurisdiction = "creator"
        requests({
          url: '/api/try/employees',
          method: 'get',
          params: {site_id: num}
        }).then((res) => {
          if (res.data.code == 1) {
            let login_index = ''
            for(let i in res.data.data){//筛选需要的角色
              let role_list = res.data.data[i].role_list
              for (let j in role_list) {
                if (jurisdiction == role_list[j].name) {
                  login_index = i
                }
              }
            }
            if (login_index != '') {
              setToken(res.data.data[login_index].token)
              localStorage.setItem('ExperienceOne_none',true)
              localStorage.setItem('Experience_data',JSON.stringify({if:true,name:jurisdiction}))
              self.$store.commit('SET_TOKEN', res.data.data[login_index].token)
              // localStorage.setItem('site_list_temp', JSON.stringify(data.data.account_site))
            }
            self.$router.push({path: '/'})
          } else {
            // self.$message.error(res.data.data.msg)
          }
        })
      },
      // 登出
      logout() {
        const self = this
        self.$http_user({
          url: '/api/logout',
          method: 'post',
        }).then((res) => {
          if (res.data.code == 1) {
            self.$store.dispatch('LogOut');
          }
        }).finally(() => {
          self.loading = false
        })
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = 'text'
        } else {
          this.passwordType = 'password'
        }
      },
      // 姓名登录
      handleLogin() {
        const self = this
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch('LoginByUsername', this.loginForm).then(ret => {
              if(ret.code == 1){
                if (this.checked) {
                  // 转成DB5并保持在Cookies
                  let user = window.btoa(this.random(5)+this.loginForm.tel+this.random(5))
                  let password = window.btoa(this.random(5)+this.loginForm.password)
                  setUser(user)
                  setPasw(password)
                }
                requests.defaults.headers.common['A-TOKEN'] = ret.data.token;
                self.site_list = ret.data.account_site
                if (self.site_list!==null && self.site_list.length == 0) { //无企业--情况
                  this.loginExperience()//无企业进入体验账号
                  // self.$router.push({ path: '/create_company' })
                  // this.$confirm('暂未加入企业，请先在功道云APP上创建/加入团队', '提示', {
                  //   confirmButtonText: '确定',
                  //   type: 'warning'
                  // }).then(() => {
                  // }).catch(() => {
                  //   localStorage.removeItem('user_token_temp')
                  // });
                } else if(self.site_list.length == 1){
                  localStorage.setItem('Experience_data',JSON.stringify({if:false,name:''}))
                  self.loginBySite(self.site_list[0].site.id)
                }else {
                  localStorage.setItem('Experience_data',JSON.stringify({if:false,name:''}))
                  self.dialogVisible = true
                }
              }else{
              }
            }).finally(err => {
                this.loading = false
            })
          } else {
            return false
          }
        })
      },
      random(num) {
        let name = []
        for (let i = 0; i < num; i++) {
            name.push(Math.floor(Math.random()*10))
        }
        return name.join('')
      },
      switchbtn(){
        this.login_icon_show = !this.login_icon_show
        localStorage.setItem('login_code','1')
        this.login_code = localStorage.getItem('login_code')
      },
      get_code(){
        let self = this
        self.code_loading = true
        self.code_overdue = false
        this.$http('post','/api/generate/qrcode',).then((res) => {
          if (res.data.code == 1) {
            self.token = res.data.data.token
            self.$nextTick (function () {
              self.qrcode();
            })
            self.get_code_info()
          } else{
            self.$message.error(res.data.msg)
          }
        }).catch((e) => {self.$message.error(e.data.msg)}).finally(() => {
          self.code_loading = false
        })
      },
      get_code_info(){
        let self = this
        this.$http('get','/api/scan/info', {params: {token: self.token}}).then((res) => {
          if (res.data.code == 1) {
            switch(res.data.data.code) {
              case 400:
                this.code_overdue = true
                this.$message.error(res.data.data.code_remark);
                break;
              case 1200:
                setTimeout(() => {
                  this.get_code_info()
                }, 600);
                break;
              case 1201:
                this.code_overdue = true
                break;
              case 1202:
                setTimeout(() => {
                  this.get_code_info()
                }, 600);
                break;
              case 1203:
                setTimeout(() => {
                  this.get_code_info()
                }, 600);
                break;
              case 1204:
                this.code_overdue = true
                break;
              default:
                alert('')
            }
          }
        }).catch((e) => {self.$message.error(e.data.msg)}).finally(() => {
          self.code_loading = false
        })
      },

      //  生成二维码
      qrcode () {
        let self = this
        let code = process.env.BASE_API+'/#/login_token?'+self.token
        let qrcode = new QRCode('qrcode', {
          width: 200,
          height: 200,        // 高度
          text:  code,   // 二维码内容
          // render: 'canvas' ,   // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
          // background: '#f0f',   // 背景色
          // foreground: '#ff0'    // 前景色
        })
      },
      clearData(){
        localStorage.clear()
        sessionStorage.clear()
        // localStorage.removeItem('ExperienceOne_none')
        // localStorage.removeItem('Experience_data')
        // localStorage.removeItem('SET_EMPLOYEE_MAP')
        // localStorage.removeItem('site_list_temp')
        // localStorage.removeItem('site_info')
        // localStorage.removeItem('dept_tree')
        // localStorage.removeItem('user_token_temp')
        // localStorage.removeItem('creatorJurisdiction')
        // self.$store.dispatch('LogOut');
        // sessionStorage.removeItem('current_time');
      }
    },
    watch:{
      'login_code'(val){
        if (val == '1') {
          this.get_code()
        }
      },
      'loginForm':{
        handler(newV,oldV){
          if(newV.tel != '' && newV.tel != ''){
            this.login_disabled = false
          }else{
            this.login_disabled = true
          }
        },
        immediate: true,
        deep:true,
      }
    },
    created() {
      if(!this.$store.state.user.pastDue){
        //进入登录界面判断 VueX里是否遗留数据，有就刷新一次页面，清空vuex
        if (this.$store.getters.addRouters.length > 0) { // 判断是否已经刷新
          return window.location.reload()
        }
      }
      this.clearData()//进入登录界面，清除本地缓存，主要是避免用户意外清除cookies后造成本地缓存依然存在，重新登陆后显示上次的缓存,或特殊情况本地缓存未清空又登录别的账号。
      var lett = this;
      document.onkeydown = function(e) {
        var key = window.event.keyCode;
        if (key == 13) {
          lett.handleLogin();
        }
      }
      document.title = this.$t("login.title_gongdaoyun")
      this.$store.dispatch('setLanguage', 'zh')
      localStorage.setItem('login_code','0')
    },
    mounted(){
      if (getUser()) {
        let getuser = window.atob(getUser())
        this.loginForm.tel = getuser.substr(5,11)
      }
      if (getPasw()) {
        let getpasw = window.atob(getPasw())
        this.loginForm.password = getpasw.slice(5)
      }
    },
    destroyed() {
      localStorage.setItem('login_code','0')
    }
  }
</script>

<style rel="stylesheet/css" type="text/css" scoped>
  .left-box {
    position: relative;
    top: 50%;
    margin-top: -25%;
  }

  .all {
    width: 1000px;
    /* height: 675px; */
    margin: 0 auto;
    position: relative;
    top: 50%;
    margin-top: -325px;
  }

  .login-container {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: auto;
    cursor: default;
    background-color: #f5f6f9;
  }

  .login-container .login_logo {
    position: relative;
    width: 100%;
    max-width: 1000px;
    overflow: hidden;
  }
  .login-container .login_logo a{
    display: inline-block;
  }
  .login-container .login_logo img {
    width: 100%;
    vertical-align: middle;
  }

  .login-container .login_box {
    position: relative;
    display: block;
    top: 0;
    width: 100%;
    /* height: 530px; */
    max-width: 1000px;
    box-shadow: 0px 4px 22px #efefef;
    background: #fff;
  }

  .login-container .login_box .login_ad {
    width: 482px;
    height: 552px;
    background: url(/images/login_bg_20200603.png) no-repeat;
    background-size: cover;
  }

  .login-container .login_box .login_ad img {
    width: 360px;
    margin: auto;
    height: 200px;
  }

  .login-container .login_box .login_ad span {
    font-family: "Microsoft YaHei";
    display: block;
    text-align: center;
    font-size: 28px;
    letter-spacing: 2px;
    font-weight: bold;
    color: #fff;
  }

  .login-container .login_box .login_type_icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 94px;
    height: 94px;
    overflow: hidden;
    z-index: 10;
  }

  .login-container .login_box .login_type_icon .login_default {
    width: 96px;
    height: 96px;
    background: url(/images/login_default.jpg) no-repeat;
    background-size: cover;
  }

  .login-container .login_box .login_type_icon .login_code {
    width: 96px;
    height: 96px;
    background: url(/images/login_code.jpg) no-repeat;
    background-size: cover;
  }

  .login-container .login_box .login_input {
    position: relative;
    display: inline-block;
    text-align: center;
    width: 508px;
    height: 552px;
    background: #FFF;
    overflow: hidden;
  }

  .login-container .login_box .login-form {
    width: 320px;
    margin: 0 auto;
    margin-top: 75px;
  }

  .login-container .login_box .login-form /deep/ input:-webkit-autofill{
    -webkit-box-shadow:0 0 0 1000px white inset !important;
  }

  .title-container {
    font-size: 22px;
    font-weight: bold;
    padding: 30px 0;
    text-align: left;
  }

  .title-container img {
    margin-top: 38px;
    width: 100%;
    height: auto;
  }

  .login-container .login_box .login-form .login_tel {
    display: block;
    margin-bottom: 24px;
    border: none;
    border-bottom: 1px solid #C0C4CC;
  }

  .login-container .login_box .login-form .login_tel .label {
    display: inline-block;
    text-align: left;
    width: 12%;
    font-size: 18px;
    color: #303133;
    line-height: 26px;
    padding: 0;
    margin: 12px 0;
    float: left;
  }

  .login-container .login_box .login-form .login_tel .input_tel {
    display: inline-block;
    width: 88%;
    margin: 12px auto;
    height: 24px;
    line-height: 24px;
    border-left: 1px #efefef solid;
    float: right;
  }

  .login-container .login_box .login-form .login_tel .input_tel /deep/ input {
    padding: 0 0% 0 4%;
    margin: 0;
    font-size: 18px;
    height: 24px;
    line-height: 24px;
    border: none !important;
  }

  .login-container .login_box .login-form .login_tel /deep/ .el-input__suffix {
    top: -6px;
    right: 0px;
  }

  .login-container .login_box .login-form .login_pwd {
    border: none;
    border-bottom: 1px solid #C0C4CC;
  }

  .login-container .login_box .login-form .login_pwd .el-input /deep/ input {
    padding: 0;
    margin: 0;
    font-size: 18px;
    height: 24px;
    line-height: 24px;
    border: none;
  }

  .login-container .login_box .login-form .login_pwd .show-pwd {
    position: absolute;
    right: 0;
    top: 0;
  }

  .login-container .login_box .login-form .login_pwd /deep/ .el-input__suffix {
    right: 20px;
  }

  /*.login-container .login_box .login-form:hover .login_tel{*/
  /*border-bottom: 1px solid #409EFF;*/
  /*}*/
  /*.login-container .login_box .login-form:active .login_tel{*/
  /*border-bottom: 1px solid #409EFF;*/
  /*}*/
  .login-container .login_box .login-form /deep/ input::-webkit-input-placeholder {
    color: #909399;
    letter-spacing: 1px;
  }

  .login-container .login_box .login-form /deep/ input:focus::-webkit-input-placeholder {
    color: #409EFF;
  }

  .login-container .login_box .login-form .el-form-item__error {
    margin: 2px auto;
  }

  .login-container .login_box .login_keeppwd {
    float: left;
  }

  .login-container .login_box .login_keeppwd .el-checkbox__inner {
    width: 20px;
    height: 20px;
    background: #fff;
  }

  .login-container .login_box .login_keeppwd .el-checkbox__inner::after {
    height: 12px;
    left: 6px;
    border: 2px solid #409EFF;
    border-top: none;
    border-left: none;
  }

  .login-container .login_box .login_keeppwd .el-checkbox__label {
    padding-left: 8px;
    font-size: 16px;
    color: #909399;
  }

  .login-container .login_box .login_forgepwd {
    float: right;
  }

  .login-container .login_box .login_forgepwd span {
    font-size: 16px;
    color: #909399;
  }

  .login-container .login_box .login_code_box {
    position: relative;
    display: inline-block;
    text-align: center;
    width: 582px;
    height: 614px;
    float: right;
    overflow: hidden;
  }

  .login-container .login_box .login_code_box .title {
    display: block;
    font-size: 24px;
    color: #1a1a1a;
    line-height: 33px;
    margin: 100px auto 30px;
  }

  .login-container .login_box .login_code_box span {
    display: block;
    font-size: 16px;
    line-height: 32px;
  }

  .login-container .login_box .login_code_box .code {
    display: inline-block;
    width: 200px;
    height: 200px;
    margin-bottom: 20px;
    overflow: hidden;
    position: relative;
  }

  .login-container .login_box .login_code_box .code .mack {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: #98989891;
    padding-top: 60px;
  }

  .mack i.el-icon-refresh {
    font-size: 26px
  }

  .login-container .login_box .login_code_box .code .mack span {
    line-height: 100%;
    color: #fff;
    background: #000;
    display: inline-block;
  }

  .login-container .login_box .login_code_box .code img {
    width: 100%;
    height: auto;
  }

  .login-container .login_box .login_code_box .social_soft {
    display: inline-block;
    width: 260px;
    margin: 30px auto;
    padding: 16px 0;
    border-top: 1px #efefef dashed;
  }

  .login-container .login_box .login_code_box .social_soft .title {
    display: inline-block;
    vertical-align: top;
    text-align: left;
    width: 80%;
    margin: 0 auto;
    font-size: 16px;
  }

  .login-container .login_box .login_code_box .social_soft .svg-icon {
    display: inline-block;
    vertical-align: top;
    width: 18%;
    font-size: 36px;
  }

  .login-container .login_box .login_code_box .social_soft .download_app {
    width: 260px;
    margin: 30px auto;
    padding: 16px 0;
    border: 1px red solid;
    background: red;
    border-radius: 8px;
  }

  .login-container .login_box .login_code_box .social_soft .download_app img {
    width: 40px;
  }

  .login-container .login_box button {
    margin: 0 auto 32px;
    padding: 0;
  }

  .login-container .login_box .login_reg {
    display: inline-block;
    overflow: hidden;
  }

  .login-container .login_box .login_reg span {
    font-size: 16px;
    letter-spacing: 1px;
  }

  .footer_copyright {
    text-align: center;
    margin: 20px 0;
  }

  .footer_copyright span {
    display: block;
    text-align: center;
    font-size: 14px;
    line-height: 18px;
    color: #606266;
  }

  .footer_copyright span img {
    display: inline-block;
    vertical-align: top;
    margin-top: 8px;
    padding: 0 20px;
  }

  .login-container::-webkit-scrollbar {
    width: 4px;
    height: 1px;
  }

  .login-container::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #535353;
  }

  .login-container::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background: transparent;
  }
</style>
