<template>
  <div class="login">
    <!-- <div v-if="!token"> -->
    <div v-if="companyList.length <= 1">
      <div class="tabs">
        <div :class="signInType === 'pwd' ? 'select' : ''" @click="changeSignIn('pwd')">账密</div>
        <div :class="signInType === 'ding' ? 'select' : ''" @click="changeSignIn('ding')">钉钉</div>
      </div>
      <div v-if="signInType === 'ding'">
        <h3 class="title">趣程后台管理系统</h3>
        <div id='login_container' />
      </div>

      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" v-if="signInType === 'pwd'" id="login_main">
        <h3 class="title">趣程后台管理系统</h3>
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号码">
            <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="loginForm.code" auto-complete="on" placeholder="验证码" :maxlength="4" style="width: 63%"
            @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <el-button style="width: 115px" :disabled="!loginForm.phone || getCodeBtText !== '获取验证码'"
              @click="getCodeHandle(loginForm.phone)">{{ getCodeBtText }}</el-button>
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住手机号</el-checkbox>
        <div style="display: flex;justify-content: center; margin-bottom: 18px;">
          <el-radio-group v-model="msgType">
            <el-radio label="ding">钉钉验证码</el-radio>
            <el-radio label="phone">手机验证码</el-radio>
          </el-radio-group>
        </div>
        <el-form-item style="width:100%;" class="login-main-button">
          <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
            @click.native.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>

      </el-form>
    </div>
    <div v-else-if="companyList.length > 1" style="margin-bottom: 160px">
      <h2 class="account-title">趣程后台管理系统</h2>
      <div class="login-form company-account">
        <h3>请选择公司账户登录</h3>
        <div class="choose-tableBlock">
          <div class="ac-tableLine" v-for="item in companyList" :key="item.companyId"
            @click="setCompanyHandle(item.companyId)">
            <div class="actname">{{ item.companyInfo.companyName }}</div>
            <div class="right">
              <span>{{ item.powerLevel === 999 ? '超级管理员' : item.powerLevel === 100 ? '公司超管' : item.powerLevel === 99 ?
                '管理员' : '普通用户' }}</span>
              <i class="el-icon-right"></i>
            </div>
          </div>
        </div>
      </div>
      <el-button type="text" size="medium" @click="logout">更换账户</el-button>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2020 quchen.</span>
    </div>
  </div>
</template>

<script>
import { getNoteCode, getCode, getDingKey } from "@/api/login";
import Cookies from "js-cookie";
import { mapState } from 'vuex'
export default {
  name: "Login",
  data() {
    let validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'));
      } else if (value.length === 4) {
        callback()
      } else {
        callback(new Error('验证码长度4位'));
      }
    };
    // 验证手机号
    let validatorPhone = (rule, value, callback) => {
      // if (value === '') {
      //   callback(new Error('手机号不能为空'))
      // } else if (!/^1\d{10}$/.test(value)) {
      //   callback(new Error('手机号格式错误'))
      // } else {
      //   callback()
      // }
      callback()
    };
    return {
      msgType: 'ding',
      signInType: 'pwd',  // 登录类型
      APPID: process.env.VUE_APP_DDAPPID, // dingdsfuoevmawlyyrjx
      REDIRECT_URI: encodeURIComponent(process.env.VUE_APP_BASE_URL), //encodeURIComponent(location.href),
      state: '',
      dingdingLoginForm: {
        code: '',
        state: '',
        stateKey: ''
      },
      loginForm: {},
      getCodeBtText: '获取验证码',
      loginRules: {
        phone: [
          { required: true, validator: validatorPhone, trigger: 'blur' }
        ],
        code: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ]
      },
      loading: false,
      redirect: undefined,
      timer: null
    };
  },
  destroyed() {
    this.clearTimer()
  },
  computed: {
    ...mapState({
      companyList: state => state.user.companyList,
      token: state => state.user.token
    })
  },
  watch: {
    $route: {
      handler(route) {
        const { code, state, token } = route.query;
        if (code) {
          this.dingdingLogin(code, state)
        } else if (token) {
          this.$store.dispatch("SetToken", decodeURIComponent(token)).then(res => {
            this.$router.push({ path: `/login?redirect=${this.redirect || '/index'}` });
          })
        }
      },
      immediate: true
    },
    signInType: {
      handler(val) {
        if (val === 'ding') {
          this.dingdingHandle()
        }
      },
      deep: true
    }
  },
  created() {
    const { redirect } = this.$route.query;
    this.redirect = redirect ? decodeURIComponent(redirect) : '/';
    if (!this.token) {
      this.getCookie();
      if (this.signInType === 'ding') {
        this.dingdingHandle()
      }
    } else {
      this.$store.dispatch('GetInfo').then(res => {
        this.setCompanyHandle(res.data.companyRelationInfo[0].companyId)
      });
    }
  },
  methods: {
    /** 设置公司 */
    setCompanyHandle(companyId) {
      const loading = this.$loading({
        lock: true,
        text: '拼命加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.5)'
      })
      this.$store.dispatch("SelectCom", companyId).then(() => {
        this.$router.push({ path: this.redirect || '/index' });
        loading.close();
      }).catch(() => {
        loading.close();
      })
    },
    changeSignIn(type) {
      this.signInType = type
    },
    // 获取钉钉登录相关
    async dingdingHandle() {
      if (this.signInType === 'ding') {
        let res = await getDingKey()
        let strArr = res.data.split('_')
        sessionStorage.setItem('DDK', strArr[0])
        this.state = strArr[1]
        window.DDLogin({
          id: "login_container",
          goto: encodeURIComponent(`https://oapi.dingtalk.com/connect/qrconnect?appid=${this.APPID}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.REDIRECT_URI}`),
          style: "border:none;padding:0 0 20px 0;background-color:rgba(255,255,255,0.7);",
          width: "100%",
          height: "400"
        });
        // 监听iframe的消息
        if (typeof window.addEventListener != 'undefined') {
          window.addEventListener('message', this.handleMessage, false);
        } else if (typeof window.attachEvent != 'undefined') {
          window.attachEvent('onmessage', this.handleMessage);
        }
      }
    },
    // 钉钉登录
    dingdingLogin(code, state) {
      if (!this.token) {
        this.loading = true;
        this.$store.dispatch("DingDingLogin", { code, state, stateKey: sessionStorage.getItem('DDK') }).then(res => {
          if (res) {
            this.setCompanyHandle(res)
          } else {
            this.$router.push({ path: `/login?redirect=${this.redirect || '/index'}` });
          }
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      } else {
        this.$router.push({ path: `/login?redirect=${this.redirect || '/index'}` });
      }
    },
    handleMessage(event) {
      // 获取loginTempCode
      const loginTempCode = event.data;
      // 获取消息来源
      const origin = event.origin;
      // 拼接 url
      const url = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.APPID}&response_type=code&scope=snsapi_login&state=${encodeURIComponent(this.state)}&redirect_uri=${this.REDIRECT_URI}&loginTmpCode=${loginTempCode}`
      // 如果来源为https://login.dingtalk.com，则在当前窗口打开回调链接
      if (origin === 'https://login.dingtalk.com') {
        window.open(encodeURI(url), '_parent')
      }
    },
    getCodeHandle(phone) {
      // if(!/^1\d{10}$/.test(phone)) {
      //   this.$message.error('请输入正确的手机号');
      //   return
      // }
      this.getCodeBtText = 30
      if (this.msgType === 'ding') {
        getCode(phone).then(res => {
          if (res.data) {
            this.$message.success('发送成功，请到钉钉查看')
            let time = 30
            this.timer = setInterval(() => {
              time--
              this.getCodeBtText = time
              if (time <= 0) {
                this.getCodeBtText = '获取验证码'
                clearInterval(this.timer)
              }
            }, 1000)
          }
        }).catch(() => this.getCodeBtText = '获取验证码');
      } else {
        getNoteCode(phone).then(res => {
          if (res.data) {
            this.$message.success('发送成功，请到手机查看')
            let time = 30
            this.timer = setInterval(() => {
              time--
              this.getCodeBtText = time
              if (time <= 0) {
                this.getCodeBtText = '获取验证码'
                clearInterval(this.timer)
              }
            }, 1000)
          }
        }).catch(() => this.getCodeBtText = '获取验证码');
      }
    },
    getCookie() {
      const rememberMe = Cookies.get('rememberMe')
      const phone = Cookies.get("phone");
      this.loginForm = {
        phone: phone === undefined ? this.loginForm.phone : phone,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
      console.log(rememberMe, {
        phone: phone === undefined ? this.loginForm.phone : phone,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("phone", this.loginForm.phone, { expires: 30 });
            Cookies.set("rememberMe", this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("phone");
            Cookies.remove("rememberMe");
          }
          this.$store.dispatch("Login", this.loginForm).then(res => {
            if (res) {
              this.setCompanyHandle(res)
            } else {
              // this.$router.push({ path: this.redirect });
              // this.$router.go(0);
            }
            this.clearTimer()
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          });
        }
      });
    },
    clearTimer() {
      this.timer && clearInterval(this.timer)
      this.getCodeBtText = '获取验证码'
    },
    logout() {
      this.$store.dispatch('LogOut').then(() => {
        this.signInType = 'pwd'
      })
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/image/login-background.jpg");
  background-size: cover;

  &>div {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #2e2e2e;
}

.login-form {
  border-radius: 8px;
  background: rgba(255, 255, 255, .8);
  width: 400px;
  padding: 25px 25px 5px 25px;
  margin-bottom: 80px;

  .el-input {
    height: 38px;

    input {
      background: rgba(255, 255, 255, .2);
      border-color: #5a5a5a;
      height: 38px;
    }

    .el-input__prefix {
      color: #5a5a5a;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.tabs {
  display: flex;
  margin: 0 20px 30px;
  width: 300px;

  &>div {
    width: 50%;
    text-align: center;
    // color: rgb(36, 219, 149);
    color: #000000;
    cursor: pointer;
    font-size: 28px;

    &.select {
      color: #1890ff;
    }
  }
}

.account-title {
  color: #FFFFFF;
  margin-bottom: 40px;
}

.company-account {
  box-shadow: 0 4px 20px 0 rgba(0, 60, 179, 0.12);
  margin-bottom: 10px;
  width: 500px;
  padding: 48px 36px;

  &>h3 {
    margin: 0;
    font-size: 20px;
  }

  &>.choose-tableBlock {
    margin-top: 20px;
    border-top: 1px solid rgba(181, 181, 181, .4);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", Helvetica, Arial, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", "Source Han Sans CN", sans-serif;
    max-height: 250px;
    overflow-y: auto;
    padding: 0 10px;

    .ac-tableLine {
      padding: 16px 14px;
      display: flex;
      align-items: center;
      font-size: 14px;
      cursor: pointer;
      color: #68779c;
      justify-content: space-between;
      border: 2px solid transparent;
      position: relative;
      border-radius: 4px;

      .actname {
        width: 250px;
        color: #0b1531;
        font-size: 16px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }

      .right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        font-size: 13px;

        &>span {
          margin-right: 10px;
        }
      }

      i {
        color: #1890ff;
        font-size: 20px;
      }

      &:hover {
        border: 2px solid #296aef;
        z-index: 5;
        transition: all .2s;
        box-shadow: 0 0 12px rgba(0, 60, 179, 0.12);

        .right {
          color: #296aef;
        }

        i {
          color: #296aef;
        }
      }

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        background-color: rgba(181, 181, 181, .4);
        height: 1px;
        width: 100%;
      }
    }
  }
}
</style>