<template>
  <div class="login-container">
    <div class="login">
      <div class="header">
        <div class="logo"></div>
        <div class="app-name">
          <span>{{ $t("system.name") }}</span>
        </div>
        <button
          v-show="settings.scanLogin"
          class="scan-enter"
          :class="scanType ? 'normal' : 'scan'"
          @click="handleScan"
          :title="scanType ? $t('login.scan_return_title') : $t('login.scan_title')"
        ></button>
      </div>
      <template v-if="!showSelect">
        <div v-if="scanType" class="scan-area">
          <img :src="defaultScan" class="scan-code" />
          <div class="scan-message">
            <label>{{ $t("login.scan_message") }}</label>
          </div>
        </div>
        <div v-else class="tabs">
          <el-tabs v-model="activeName" :stretch="false" ref="tabs">
            <el-tab-pane
              v-if="settings.pwdLogin"
              :label="$t('login.password_login')"
              name="first"
            >
              <div class="tabsItem account">
                <span class="title">{{ $t("login.account") }}</span>
                <div class="inputBox iconfont icon-user">
                  <el-input
                    v-model="loginUser"
                    :placeholder="$t('login.account_placeholder')"
                    clearable
                    autofocus="autofocus"
                  ></el-input>
                </div>
              </div>
              <div class="tabsItem pwd">
                <span class="title">{{ $t("login.password") }}</span>
                <div class="inputBox iconfont icon-pwd">
                  <el-input
                    v-model="loginPwd"
                    show-password
                    :placeholder="$t('login.password_placeholder')"
                    clearable
                    @keyup.enter.native="handleEnter('pwd')"
                  ></el-input>
                </div>
              </div>
              <div class="buttonBox">
                <el-checkbox v-model="saveAccount">{{$t("login.save_account")}}</el-checkbox>
                <el-link v-if="settings.forgetPwd" type="primary" :href="forgetPassword"
                         target="_blank" >{{ $t("login.forget_password") }}</el-link >
              </div>
              <div class="buttonBox">
                <button v-if="settings.register" class="register">{{ $t("login.register") }}</button>
                <el-popover ref="popover" placement="top-end" trigger="manual" v-model="showCode" >
                  <ImageDrag :visible="showCode" :src="$store.state.api.user.getDynamicImage"
                             @success="handleLogin" @close="handleImageCodeClose">
                  </ImageDrag>
                </el-popover>
                <button class="loginBtn" @click="handleLogin" v-popover:popover>
                  {{ $t("login.password_login_btn") }}
                </button>
              </div>
            </el-tab-pane>
            <el-tab-pane
              v-if="settings.smsLogin"
              :label="$t('login.message_login')"
              name="second"
            >
              <div class="tabsItem phone">
                <span class="title">{{ $t("login.telephone") }}</span>
                <div class="inputBox iconfont icon-phone">
                  <el-input
                    v-model="telephone"
                    :placeholder="$t('login.telephone_placeholder')"
                    clearable
                    autofocus="autofocus"
                  ></el-input>
                </div>
              </div>
              <div class="tabsItem smscode">
                <span class="title">{{ $t("login.message_code") }}</span>
                <div class="inputBox iconfont icon-smscode">
                  <el-input
                    v-model="code"
                    :placeholder="$t('login.message_placeholder')"
                    clearable
                    @keyup.enter.native="handleEnter('sms')"
                  ></el-input>
                </div>
                <el-button v-if="!showCount" @click="getCode" class="getcode">{{
                  $t("login.message_get")
                }}</el-button>
                <div v-else class="code">{{ count }}s</div>
              </div>
              <div class="buttonBox">
                <el-checkbox v-model="savePhone">{{
                  $t("login.save_phone")
                }}</el-checkbox>
              </div>
              <div class="buttonBox">
                <button class="register">{{ $t("login.register") }}</button>
                <button class="loginBtn" @click="handleLogin">
                  {{ $t("login.message_login_btn") }}
                </button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template v-if="showSelect">
        <div class="selectUserLogin">
          <div class="title">{{ $t("login.choose_app") }}</div>
          <div class="apps">
            <div
              v-for="(item, index) in selectUserList"
              :key="index"
              @click="choseApp(item)"
            >
              <img :src="getLogo(item.logo)" alt="" />
              <span>{{ item.sname }}</span>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import ImageDrag from "../../components/CheckCode/index";
export default {
  name: "Login",
  components: {
    ImageDrag,
  },
  data() {
    return {
      loading: false,
      scanType: false, //扫码模式
      passwordType: true, //密码模式
      redirect: null, //是否需要重定向
      selectUserList: "",
      activeName: "first",
      showSelect: false,
      loginUser: "",
      loginPwd: "",
      defaultLogo: "/favicon.ico",
      defaultScan: require("../../assets/defaults/login/scancode.png"),
      showCount: false,
      count: 60,
      telephone: null,
      code: null,
      saveAccount: false,
      savePhone: false,
      forgetPassword: "",
      showCode: false,
    };
  },
  computed: {
    ...mapState(["settings", "user"]),
  },mounted(){
    document.title=this.$t("system.name");
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    if (this.user.saveAccount) {
      this.saveAccount = true;
      this.loginUser = this.user.account;
    }
    if (this.user.savePhone) {
      this.savePhone = true;
      this.telephone = this.user.phone;
    }
    if (!this.settings.pwdLogin) {
      this.activeName = "second";
    }
  },
  methods: {
    checkImageDrag() {
      return this.$store.state.settings.checkCode.enable &&
          this.$store.state.settings.checkCode.type === "imgDrag";
    },
    handleImageCodeClose(e) {
      console.log("handleImageCodeClose");
      this.showCode = false;
    },
    getLogo(logoSrc) {
      return logoSrc
          ? this.$store.state.api.axios.baseURL + logoSrc
          : this.defaultLogo;
    },
    handleScan() {
      this.scanType = !this.scanType;
    },
    handleEnter(type) {
      if (this.settings.enterForLogin) {
        this.handleLogin();
      }
    },
    handleLogin(e) {
      this.loading = true;
      if (this.activeName === "first") {
        if (!this.loginUser) {
          return;
        }
        if (!this.loginPwd) {
          this.$message({message:"密码不允许为空",type: "error"});
          return;
        }
        if (this.checkImageDrag()) {
          if (e !== true) {
            this.showCode = true;
            return;
          }
          this.showCode = false;
        }
        const loginForm = {
          loginUser: this.loginUser,
          loginPwd: this.loginPwd,
          saveAccount: this.saveAccount,
        };
        this.$store
            .dispatch("user/userLogin", loginForm)
            .then((res) => {
              let apps=res.apps;
              if (apps.length > 1) {
                this.selectUserList = apps;
                this.showSelect = true;
              } else if (apps.length === 1) {
                this.choseApp(apps[0]);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
      } else {
        const loginForm = {telephone: this.telephone,code: this.code,savePhone: this.savePhone};
        this.$store.dispatch("user/codeLogin", loginForm)
            .then((res) => {
              let apps=res.apps;
              if (apps.length > 1) {
                this.selectUserList = apps;
                this.showSelect = true;
              } else if (apps.length === 1) {
                this.choseApp(apps[0]);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
      }
    },
    choseApp(item) {
      const app = this.$core.merge({}, this.$store.state.app, item);
      this.$store.dispatch("app/updateApp", app);
      this.$store.dispatch("user/login", item)
          .then((res) => {
            if(res.code===0)
              this.$router.push("/");
            else
              this.$message({message:"您的账号未经授权登录！",type: "error"});
          })
          .catch((err) => {
            this.$core.debug().error(err);
          });
    },
    getCode() {
      this.showCount = true;
      const timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
          this.showCount = false;
          this.count = 60;
        }
      }, 1000);
      this.$http(this.$store.state.api.user.getSmsCode, {
        data: { telephone: this.telephone },
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getDynamicImage() {
      return (
        this.$store.state.api.axios.baseURL +
        this.$store.state.api.user.getDynamicImage
      );
    },
  },
};
</script>
<style lang="scss">
@import "../../assets/defaults/login";

.el-popper {
  .sliding-pictures {
    width: 240px;
    height: 260px; //实际图片的高度+80px
  }
}
</style>
