<template>
  <el-container style="height: 100%" direction="vertical">
    <el-header style="height: 88px" id="headerS">
      <div class="headerLogin">
        <img class="header-img" src="@/assets/images/u8.png" alt="" />
        <span class="header-text">中储粮标准化管理云平台</span>
      </div>
    </el-header>
    <el-main>
      <div class="content">
        <div class="main-left">
          <img class="main-left-img" src="@/assets/images/z.png" alt="" />
        </div>
        <div class="main-right">
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            autocomplete="on"
            label-position="left"
          >
            <div class="title-container">
              <h3 class="title">用户密码登录</h3>
            </div>

            <el-form-item prop="username">
              <span class="svg-container">
                <svg-icon icon-class="user" />
              </span>
              <el-input
                ref="username"
                v-model="loginForm.username"
                placeholder="用户名"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </el-form-item>

            <el-tooltip
              v-model="capsTooltip"
              content="Caps lock is On"
              placement="right"
              manual
            >
              <el-form-item prop="password">
                <span class="svg-container">
                  <svg-icon icon-class="password" />
                </span>
                <el-input
                  class="myInput2"
                  :key="passwordType"
                  ref="password"
                  v-model="loginForm.password"
                  :type="passwordType"
                  placeholder="密码"
                  name="password"
                  tabindex="2"
                  autocomplete="off"
                  @keyup.native="checkCapslock"
                  @blur="capsTooltip = false"
                  @keyup.enter.native="handleLogin"
                />
                <span class="show-pwd" @click="showPwd">
                  <svg-icon
                    :icon-class="
                      passwordType === 'password' ? 'eye' : 'eye-open'
                    "
                  />
                </span>
              </el-form-item>
            </el-tooltip>

            <!-- <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button> -->

            <el-button
              :loading="loading"
              type="primary"
              style="width: 100%; margin-top: 40px"
              @click="handleLogin()"
              >登录</el-button
            >

            <!--             <div style="position: relative">
              <div class="tips">
                <span>Username : admin</span>
                <span>Password : any</span>
              </div>
              <div class="tips">
                <span style="margin-right: 18px">Username : editor</span>
                <span>Password : any</span>
              </div>
              <el-button
                class="thirdparty-button"
                type="primary"
                @click="showDialog = true"
              >
                Or connect with
              </el-button>
            </div> -->
          </el-form>
        </div>
      </div>
    </el-main>
    <el-footer style="height: 15px">
      <i>C</i>
      2020 中储粮-标准化管理云平台 版权所有
    </el-footer>
  </el-container>
</template>

<script>
import { validUsername } from "@/utils/validate"
import SocialSign from "./components/SocialSignin"
import { login, deportDic, hourseDic, personDic, departDic } from "@/api/user"
import {
  getToken,
  setToken,
  removeToken,
  getUser,
  setUser,
  removeUser,
} from "@/utils/auth"

export default {
  name: "Login",
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入用户名"))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位"))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: "wsm1",
        password: "123456",
      },
      loginRules: {
        username: [{ required: true, trigger: "blur" }],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      // disabled:true,
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus()
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z"
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = ""
      } else {
        this.passwordType = "password"
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let loginInfo = {
            uName: this.loginForm.username,
            uPassword: this.loginForm.password,
          }
          login(loginInfo)
            .then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: "登录成功",
                  type: "success",
                })
                var Authorization =
                  res.data.tokenInfo.token_type +
                  " " +
                  res.data.tokenInfo.access_token
                setToken(Authorization)
                setUser(res.data.user)
                this.depotId = res.data.user.depotId

                this.getDeportDic()
                this.getHourseDic()
                this.getPersonDic()
                this.getDepartDic()
                //把用户信息存入缓存
                // console.log(res.data.user.depotId, "5665564433224556533")
                console.log(
                  res.data.user.homeType,
                  "查看用户类型，1-分公司首页，2-库及以上领导首页，3-员工首页"
                )
                localStorage.setItem("userInfo", JSON.stringify(res.data.user))
                if (res.data.user.homeType == 1) {
                  // 跳转分公司首页
                  this.$router.push({ path: "/dashboard" })
                  // this.$router.push({path:'daiban'})
                  // this.$router.push({ path: "/" })
                } else if (res.data.user.homeType == 2) {
                  // 跳转库及以上领导首页
                  this.$router.push({ path: "/" })
                } else {
                  // 跳转员工首页（当前员工首页未定，暂跳转待办页）
                  this.$router.push({ path: "daiban" })
                }

                /* if (res.data.user.depotId == 1) {
                  this.$router.push({ path: "/dashboard" })
                } else {
                  this.$router.push({ path: "/" })
                } */
                this.loading = false
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                })
              }
            })
            .catch((err) => {
              console.log(err)
              this.loading = false
            })
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },

    //库字典
    getDeportDic() {
      deportDic()
        .then((res) => {
          console.log(res, "mmmmmmm")
          if (res.code == 200) {
            // this.deportDic=res.data;
            localStorage.setItem("deportDic", JSON.stringify(res.data))
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //仓房字典
    getHourseDic() {
      hourseDic()
        .then((res) => {
          console.log(res, "仓房")
          if (res.code == 200) {
            // this.deportDic=res.data;
            localStorage.setItem("hourseDic", JSON.stringify(res.data))
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //人员字典

    getPersonDic() {
      var params = {
        depotId: this.depotId,
      }
      personDic(params)
        .then((res) => {
          console.log(res, "人员")
          if (res.code == 200) {
            // this.deportDic=res.data;
            localStorage.setItem("perList", JSON.stringify(res.data))
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //部门字典
    getDepartDic() {
      departDic()
        .then((res) => {
          console.log(res, "mmmmmmm")
          if (res.code == 200) {
            // this.deportDic=res.data;
            localStorage.setItem("departDic", JSON.stringify(res.data))
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  },
}
</script>
<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
.el-form-item__error {
  left: 33px;
}
</style>

<style lang="scss" scoped>
#headerS {
  line-height: 88px;
  background-color: rgba(0, 128, 0, 1);
  .headerLogin {
    position: relative;
    height: 45px;
    font-size: 28px;
    font-family: "PingFangSC-Medium", "PingFang SC Medium", "PingFang SC";
    color: #fff;
    .header-img {
      width: 44px;
      height: 47px;
      position: absolute;
      left: 25px;
      top: 21px;
    }
    .header-text {
      position: absolute;
      left: 75px;
      top: 2px;
    }
  }
}
.el-container .el-main {
  // width: 1363px;
  height: 980px;
  margin: 0;
  padding: 0;
  background-color: rgba(255, 255, 255, 1);
  background-image: url("~@/assets/images/bj.png");
  background-repeat: no-repeat;
  position: relative;
  .content {
    height: 370px;
    position: absolute;
    left: 53px;
    top: 100px;
    // margin: 35px 20px 40px 20px;
    background-color: rgb(99, 92, 92);
    .main-left {
      position: absolute;
      // background-color:#f2f2f2;
      .main-left-img {
        width: 300px;
        position: absolute;
        left: 200px;
        top: 100px;
      }
    }
    .main-right {
      width: 476px;
      height: 368px;
      background-color: rgba(255, 255, 255, 1);
      // background-color: #dcf0e5;
      border: 1px solid rgba(204, 204, 204, 1);
      box-sizing: border-box;
      border-radius: 8px;
      position: absolute;
      left: 700px;

      .login-form {
        position: relative;
        width: 520px;
        max-width: 100%;
        padding: 12px 35px 0;
        margin: 0 auto;
        overflow: hidden;

        .el-form-item {
          border: 1px solid rgba(255, 255, 255, 0.1);
          // background: rgba(0, 0, 0, 0.1);
          // border-radius: 5px;
          color: #454545;
          .el-input {
            display: inline-block;
            height: 47px;
            width: 85%;

            input {
              background: transparent;
              border: 0px;
              -webkit-appearance: none;
              border-radius: 0px;
              padding: 12px 5px 12px 15px;
              // color: $light_gray;
              height: 47px;
              // caret-color: $cursor;

              /*  &:-webkit-autofill {
            box-shadow: 0 0 0px 1000px $bg inset !important;
            -webkit-text-fill-color: $cursor !important;
          } */
            }
          }
        }

        .el-button {
          background-color: #43b943;
          height: 45px;
          border-color: #43b943;
        }
      }
    }
  }
}

.tips {
  font-size: 14px;
  color: #fff;
  margin-bottom: 10px;

  span {
    &:first-of-type {
      margin-right: 16px;
    }
  }
}

.svg-container {
  padding: 6px 5px 6px 15px;
  // color: $dark_gray;
  vertical-align: middle;
  width: 30px;
  display: inline-block;
}

.title-container {
  position: relative;

  /*     .title {
      font-size: 26px;
      // color: $light_gray;
      // margin: 0px auto 40px auto;
      // text-align: center;
      font-weight: bold;
    } */
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  // color: $dark_gray;
  cursor: pointer;
  user-select: none;
}

.thirdparty-button {
  position: absolute;
  right: 0;
  bottom: 6px;
}

.el-footer {
  background-color: #f0f2f5;
  font-size: 12px;
  color: #333;
  text-align: center;
  line-height: 16px;
  i {
    display: inline-block;
    width: 15px;
    height: 15px;
    border-radius: 7.5px;
    background-color: #007b3a;
    color: #fff;
  }
}
@media only screen and (max-width: 470px) {
  .main-right {
    display: none;
  }
}
</style>
