<template>
  <div
    class="login"
    v-loading="loginLoading"
    element-loading-text="登录中"
    element-loading-spinner="el-icon-loading"
  >
    <!-- <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"> -->4
    <div class="login-box">
      <h3 class="title">湘商全渠道运营平台</h3>
      <div
        id="login_container"
        class="login_container"
        v-show="loginType == 'codeLogin'"
      ></div>
      <el-form
        ref="loginForm"
        class="login-form"
        v-show="loginType == 'passWordLogin'"
        :model="loginForm"
        :rules="loginRules"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.phone"
            type="text"
            auto-complete="off"
            placeholder="请输入手机号(11位数字)"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <!-- <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item> -->
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="请输入短信验证码"
            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">
            <!-- <img :src="codeUrl" @click="getCode" class="login-code-img" /> -->
            <el-button
              :disabled="yzCodeloading"
              type="primary"
              style="width: 100%"
              @click.native.prevent="sendCode"
            >
              {{ codeText }}
            </el-button>
          </div>
        </el-form-item>
        <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px"
          >记住密码</el-checkbox
        > -->
        <el-form-item style="width: 100%; margin-top: 65px">
          <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>
          <div style="float: right" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
      <div class="login-img-box">
        <img
          src="../assets/images/codeLogin.png"
          class="codeLogin"
          v-show="loginType == 'passWordLogin'"
          @click="changeLoginType"
        />
        <img
          src="../assets/images/passWordLogin.png"
          class="codeLogin"
          v-show="loginType == 'codeLogin'"
          @click="changeLoginType"
        />
      </div>
      <!--  底部  -->
      <div class="el-login-footer">
        <span>Copyright © 2018-2023 ruoyi.vip All Rights Reserved.</span>
      </div>
    </div>
  </div>
</template>

<script>
import { feishuCaptcha, feishuLogin } from "@/api/gpt";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginLoading: false,
      loginForm: {
        // username: "",
        // password: "",
        // rememberMe: false,
        phone: "",
        code: "",
        // uuid: "",
      },
      loginType: "codeLogin",
      loginRules: {
        phone: [{ required: true, trigger: "blur", message: "请输入您的手机号" }],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      codeText: "获取验证码",
      yzCodeloading: false,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
        if (route.query && route.query.code) {
          this.feishuCallbackFunt(route.query.code);
        }
      },
      immediate: true,
    },
  },
  created() {
    // this.getCode();
    this.getCookie();
  },
  mounted() {
    console.log(window.location);
    let redirect_uri = "";
    if (window.location.hostname == "oco.xsbuy.cn") {
      redirect_uri =
        "https://oco.xsbuy.cn/login?redirect=%2Findex&response_type=code&state=STATE";
    } else {
      redirect_uri =
        "http://47.123.5.73/login?redirect=%2Findex&response_type=code&state=STATE";
    }
    const goto =
      "https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=cli_a47b0e9807fa500b&redirect_uri=" +
      redirect_uri;
    var QRLoginObj = QRLogin({
      id: "login_container",
      goto,
      width: "500",
      height: "500",
      style: "width:300px;height:300px", //可选的，二维码html标签的style属性
    });

    var handleMessage = function (event) {
      // 使用 matchOrigin 和 matchData 方法来判断 message 和来自的页面 url 是否合法
      if (QRLoginObj.matchOrigin(event.origin) && QRLoginObj.matchData(event.data)) {
        var loginTmpCode = event.data.tmp_code;
        console.log(loginTmpCode);
        // _this.feishuCallbackFunt(loginTmpCode);
        // 在授权页面地址上拼接上参数 tmp_code，并跳转
        window.location.href = `${goto}&tmp_code=${loginTmpCode}`;
      }
    };
    if (typeof window.addEventListener != "undefined") {
      window.addEventListener("message", handleMessage, false);
    } else if (typeof window.attachEvent != "undefined") {
      window.attachEvent("onmessage", handleMessage);
    }

    this.fsApiAuth();
  },
  methods: {
    feishuCallbackFunt(code) {
      this.loginLoading = true;
      this.$store
        .dispatch("fsLogin", { code: code })
        .then(() => {
          this.loginLoading = false;
          this.$router.push({ path: this.redirect || "/" }).catch(() => {});
        })
        .catch(() => {
          this.loginLoading = false;
          this.loading = false;
          // if (this.captchaEnabled) {
          //   this.getCode();
          // }
        });
    },
    changeLoginType() {
      this.loginType == "codeLogin"
        ? (this.loginType = "passWordLogin")
        : (this.loginType = "codeLogin");
    },
    fsApiAuth() {
      if (!window.h5sdk) {
        console.log("invalid h5sdk");
        // alert('please open in feishu')
        return;
      }

      // 通过error接口处理API验证失败后的回调
      window.h5sdk.error((err) => {
        throw ("h5sdk error:", JSON.stringify(err));
      });
      this.loginLoading = true;
      const _this = this;
      // 通过ready接口确认环境准备就绪后才能调用API
      window.h5sdk.ready(() => {
        console.log("window.h5sdk.ready");
        console.log("url:", window.location.href);
        // 调用JSAPI tt.requestAccess 获取 authorization code
        tt.requestAuthCode({
          appId: "cli_a47b0e9807fa500b",
          // scopeList: [],
          // 获取成功后的回调
          success(res) {
            console.log("getAuthCode succeed");
            //authorization code 存储在 res.code
            // 此处通过fetch把code传递给接入方服务端Route: callback，并获得user_info
            // 服务端Route: callback的具体内容请参阅服务端模块server.py的callback()函数
            console.log(res.code);
            _this.$store
              .dispatch("fsLogin", { code: res.code })
              .then(() => {
                _this.loginLoading = false;
                console.log(_this.$route.query.type);
                if (_this.$route.query.type == "chart") {
                  _this.$router.push({ path: "/wl/app" }).catch(() => {});
                } else if (_this.$route.query.type == "gpt") {
                  _this.$router.push({ path: "/gpt" }).catch(() => {});
                } else {
                  _this.$router.push({ path: "/index" }).catch(() => {});
                }
              })
              .catch(() => {
                _this.loginLoading = false;
              });
          },
          // 获取失败后的回调
          fail(err) {
            console.log(`getAuthCode failed, err:`, JSON.stringify(err));
          },
        });
      });
    },
    sendCode() {
      const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
      if (!reg.test(this.loginForm.phone)) {
        this.$message.warning("请输入正确手机号");
        return false;
      }
      this.yzCodeloading = true;
      feishuCaptcha({ phone: this.loginForm.phone })
        .then((res) => {
          if (res.status == "200") {
            this.$message.success("短信验证码发送成功");
            let seconds = 60;
            const myVar = setInterval(() => {
              if (seconds === 0) {
                seconds = 60;
                this.yzCodeloading = false;
                this.codeText = "获取验证码";
                clearInterval(myVar);
              } else {
                seconds = seconds - 1;
                this.codeText = seconds + "s后重试";
              }
            }, 1000);
          } else {
            this.yzCodeloading = false;
          }
        })
        .catch((err) => {
          this.yzCodeloading = false;
        });
    },
    // getCode() {
    //   getCodeImg().then((res) => {
    //     this.captchaEnabled =
    //       res.captchaEnabled === undefined ? true : res.captchaEnabled;
    //     if (this.captchaEnabled) {
    //       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 : decrypt(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", encrypt(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.$router.push({ path: this.redirect || "/" }).catch(() => {});
              const _this = this;
              if (_this.$route.query.type == "chart") {
                _this.$router.push({ path: "/wl/app" }).catch(() => {});
              } else if (_this.$route.query.type == "gpt") {
                _this.$router.push({ path: "/gpt" }).catch(() => {});
              } else {
                _this.$router.push({ path: this.redirect || "/" }).catch(() => {});
              }
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 26px auto;
  text-align: center;
  color: #707070;
  font-size: 18px;
  font-weight: bold;
}
.login-box {
  width: 400px;
  padding-top: 25px;
  border-radius: 6px;
  background: #ffffff;
}
.login-form {
  height: 300px;
  padding: 35px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .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;
}
.login_container {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  iframe {
    border: none;
  }
}
.login-img-box {
  height: 84px;
  cursor: pointer;
}
</style>
