<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">医技预约管理系统V2.0</h3>
      <el-form-item prop="loginOrg">
        <el-select
          v-model="loginForm.loginOrg"
          placeholder="请选择机构"
          style="width: 100%"
          @change="orgChange"
        >
          <el-option
            v-for="item in orgList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="loginDept">
        <el-select
          v-model="loginForm.loginDept"
          filterable
          placeholder="请选择科室"
          style="width: 100%"
        >
          <el-option
            v-for="item in deptList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          auto-complete="off"
          placeholder="账号"
          type="text"
        >
          <svg-icon
            slot="prefix"
            class="el-input__icon input-icon"
            icon-class="user"
          />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          auto-complete="off"
          placeholder="密码"
          type="password"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon
            slot="prefix"
            class="el-input__icon input-icon"
            icon-class="password"
          />
        </el-input>
      </el-form-item>
      <el-checkbox
        v-model="loginForm.rememberMe"
        style="margin: 0px 0px 25px 0px"
        >记住密码
      </el-checkbox>
      <el-form-item style="width: 100%">
        <el-button
          ref="btn"
          :loading="loading"
          size="medium"
          style="width: 100%"
          type="primary"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2022 同步远方 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import request from "@/utils/request";
import StorageUtils from "@/utils/Storage";

export default {
  name: "Login",
  data() {
    return {
      paramValue: "",
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        token1: "",
        // 用于登录信息存储
        loginOrg: "",
        loginDept: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        loginOrg: [{ required: true, trigger: "blur", message: "请选择机构" }],
        loginDept: [{ required: true, trigger: "blur", message: "请选择科室" }],
      },
      loading: false,
      redirect: undefined,
      orgList: [], // 机构列表
      deptList: [], // 科室列表
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    var usr = this.urlVal("usr");
    var pwd = this.urlVal("pwd");
    if (usr != null && usr != "" && pwd != null && pwd != "") {
      this.getuserPwd(usr, pwd);
    }
    //debugger;
    this.getCode();
    this.initParamValue();
    this.getCookie();
    request({
      url: "/resource/open/orgList",
      method: "get",
    }).then((res) => {
      this.orgList = res.data.map((item) => {
        return {
          name: item.orgName,
          value: item.orgCode,
          label: `【${item.orgCode || ""}】${item.orgName}`,
        };
      });
      // 默认选择
      const { body: loginOrg } = StorageUtils.getWisLocal("loginOrg");
      if (loginOrg) {
        this.$set(this.loginForm, "loginOrg", loginOrg.id);
        request({
          url: "/resource/open/deptList",
          method: "get",
          params: {
            orgId: loginOrg.id,
          },
        }).then((res) => {
          this.deptList = res.data.map((item) => {
            return {
              name: item.deptName,
              value: item.deptId,
              label: `【${item.deptId || ""}】${item.deptName}`,
            };
          });
          // 默认选择
          const { body } = StorageUtils.getWisLocal("loginDept");
          if (body) {
            this.$set(this.loginForm, "loginDept", body.id);
          }
        });
      }
    });
  },
  methods: {
    orgChange(value) {
      this.$set(this.loginForm, "loginDept", "");
      request({
        url: "/resource/open/deptList",
        method: "get",
        params: {
          orgId: value,
        },
      }).then((res) => {
        this.deptList = res.data.map((item) => {
          return {
            name: item.deptName,
            value: item.deptId,
            label: `【${item.deptId || ""}】${item.deptName}`,
          };
        });
      });
    },
    initParamValue() {
      let paramCode = "PlatformName";
    },
    urlVal(paramName) {
      var paramValue = "",
        isFound = !1;
      if (
        location.search.indexOf("?") == 0 &&
        location.search.indexOf("=") > 1
      ) {
        var arrSource = unescape(location.search)
            .substring(1, location.search.length)
            .split("&"),
          i = 0;
        while (i < arrSource.length && !isFound)
          arrSource[i].indexOf("=") > 0 &&
            arrSource[i].split("=")[0].toLowerCase() ==
              paramName.toLowerCase() &&
            ((paramValue = arrSource[i].split("=")[1]), (isFound = !0)),
            i++;
      }
      return paramValue == "" && (paramValue = null), paramValue;
    },
    getuserPwd(usr, pwd) {
      this.loginForm.username = usr;
      this.loginForm.password = pwd;
      setTimeout(() => {
        this.handleLogin();
      }, 100);
    },
    getCode() {
      getCodeImg(this.token1).then((res) => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", this.loginForm.password, { expires: 30 });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.loading = false;
              StorageUtils.setWisLocal("loginOrg", {
                id: this.loginForm.loginOrg,
                name: this.orgList.find(
                  (item) => item.value === this.loginForm.loginOrg
                )?.name,
              });
              StorageUtils.setWisLocal("loginDept", {
                id: this.loginForm.loginDept,
                name: this.deptList.find(
                  (item) => item.value === this.loginForm.loginDept
                )?.name,
              });
              console.log(this.redirect);
              if (this.redirect) {
                this.$router.replace({ path: `${this.redirect}` });
              } else {
                this.$router.replace({ path: "/index" });
              }
            })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        }
      });
    },
  },
};
</script>

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

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: white;
  font-size: 26px;
}

.login-form {
  border-radius: 6px;
  width: 400px;
  padding: 40px 30px 30px 30px;
  margin-right: 150px;
  overflow: hidden;
  //background: url("../assets/images/login_form.png");
  background-size: 100% 100%;

  .el-form-item {
    padding-right: 0;
    margin: 20px 0;
    color: #454545;
    background: transparent;
    border: 1px solid transparent;
    border-radius: 2px;
  }

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .el-checkbox {
    color: white;
  }

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

  .el-select {
    width: 100%;
  }
}

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

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

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

.login-btn {
  width: 100%;
  display: inherit;
  height: 50px;
  margin-top: 5px;
  border: 0;
}

.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;
}
</style>
