<style>
.login {
  background: url("../assets/img/login-bg.jpg");
  background-size: cover;
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.login-box-pc {
  width: 436px;
  padding: 30px 40px;
  margin: 100px auto;
  position: absolute;
  right: 360px;
  background-clip: padding-box;
  background: #ffffff;
  border-radius: 18px;
}
.login-box {
  max-width: 436px;
  padding: 30px 40px;
  background-clip: padding-box;
  background: #ffffff;
}

.login-box .tw_logo {
  margin: 0 auto 20px;
  display: block;
  height: 45px;
  width: auto;
}

.login-box .tip-text {
  font-size: 16px;
  margin-bottom: 15px;
  color: #999;
  text-align: center;
}

.login-box .tip-text a {
  color: #00afff;
}

.login_row {
  width: 100%;
}

.form-group {
  position: relative;
  margin-bottom: 15px;
}

.login_labelName {
  margin-top: 34px;
  font-size: 16px;
  margin-bottom: 16px;
}

.form-group i {
  position: absolute;
  right: 6px;
  bottom: 0;
  z-index: 2;
  width: 46px;
  height: 46px;
  text-align: center;
  line-height: 46px;
  color: #999;
  font-size: 28px;
  cursor: pointer;
}

.login-box .q-field__control {
  height: 46px;
}
.type-item {
  width: 50px;
  height: 50px;
  background: #f5f5f5;
  border-radius: 25px;
}
.type-item img {
  width: 28px;
  height: 28px;
}
</style>
<template>
  <div :class="$q.platform.is.desktop ? 'login' : 'full-width'">
    <div
      class="login-box"
      :class="$q.platform.is.desktop ? 'login-box-pc' : ''"
    >
      <!-- <img :src="logo" class="tw_logo" /> -->
      <!-- <p class="tip-text">
        還沒有帳號嗎？立即<a style="cursor:pointer;" @click="CommonJump('/register',{})">免費加入</a>
      </p> -->
      <q-form ref="loginForm" v-if="loginType !== 'wechat'">
        <div class="row items-center justify-between">
          <div class="f34 bold">
            {{
              loginType === "bindEmail" ? "立即绑定" : isLogin ? "登錄" : "註冊"
            }}
          </div>
          <div
            class="text-subtitle2 cursor-pointer"
            v-if="loginType !== 'bindEmail'"
            @click="loginToRegister"
          >
            {{ isLogin ? "註冊賬號" : "返回登錄" }}
          </div>
        </div>
        <div class="login_row">
          <q-input
            filled
            v-model="loginMsg.Mailbox"
            class="q-mt-xl"
            label="輸入郵箱"
            style="ime-mode: disabled"
            aria-autocomplete="off"
            :rules="[
              (val) =>
                /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(
                  val
                ) || '請輸入正確的郵箱地址',
            ]"
          >
            <template
              v-if="loginType === 'MailCode' || loginType === 'bindEmail'"
              v-slot:after
            >
              <q-btn
                unelevated
                color="text-white bg-secondary"
                :disable="
                  !/^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(
                    loginMsg.Mailbox
                  ) || cutDown > 0
                "
                style="height: 46px; margin-top: -10px"
                filled
                :loading="inSending"
                :label="
                  !isSend
                    ? '发送验证码'
                    : cutDown > 0
                    ? cutDown + '秒'
                    : '重新發送'
                "
                @click="sendVerify"
              />
            </template>
          </q-input>
          <div
            class="q-mt-md"
            v-if="loginType === 'MailCode' || loginType === 'bindEmail'"
          >
            <verify-code
              :digit="6"
              hint="請輸入正確的驗證碼"
              ref="verify"
              v-model="loginMsg.MailCode"
            ></verify-code>
          </div>
          <div
            v-if="
              loginType === 'PassWord' ||
              (!isLogin && loginType !== 'bindEmail')
            "
            class="q-mt-md"
          >
            <div class="text-right">
              <span
                class="text-grey-6 f12 cursor-pointer"
                v-if="loginType === 'PassWord'"
                @click="resetPassword"
                >忘記密碼</span
              >
            </div>
            <q-input
              standout
              v-model="loginMsg.PassWord"
              type="PassWord"
              autocomplete="off"
              placeholder="請輸入密碼"
              :rules="[(val) => !!val || '請輸入密碼']"
              ref="pwd"
            />
          </div>
          <div class="text-right f12 text-dark" v-if="isLogin">
            <span class="cursor-pointer" @click="changeLoginType">{{
              loginType === "PassWord" ? "使用郵箱驗證登陸" : "使用賬號密碼登陸"
            }}</span>
          </div>
          <div class="q-mb-xl">
            <q-btn
              color="primary"
              unelevated
              style="width: 100%; height: 50px; margin-top: 20px"
              filled
              :label="mylabel"
              :loading="loading"
              @click="login"
            />
          </div>
          <div class="flex flex-center">
            <div
              class="text-center text-grey-6 q-px-lg inline-block bg-white"
              style="z-index: 1; margin: 0 auto"
            >
              更多登录方式
            </div>
          </div>
          <q-separator style="margin-top: -10px" />
          <div class="flex flex-center q-mt-lg q-mb-xl">
            <div
              @click="useWechatLogin"
              class="type-item flex flex-center cursor-pointer"
              v-for="item in typeList"
              :key="item"
            >
              <img :src="require(`src/assets/img/${item}.png`)" />
            </div>
          </div>
          <div class="flex items-start no-wrap">
            <div><q-checkbox v-model="isAgree"></q-checkbox></div>
            <span
              >在使用和平的产品和服务前，我已阅读 理解并同意和平的<a
                href="http://www.oytour.com/#/customer/15"
                target="_blank"
                class="text-primary"
                >《隐私政策》</a
              >和<a
                href="http://www.oytour.com/#/customer/13"
                target="_blank"
                class="text-primary"
                >《使用条款》</a
              ></span
            >
          </div>
        </div>
      </q-form>
      <!-- 微信扫码页面 -->
      <div v-show="loginType === 'wechat'">
        <div class="bold f34">微信登錄</div>
        <!-- <qrcode-vue></qrcode-vue> -->
        <div id="login_container"></div>
      </div>
    </div>
  </div>
</template>

<script>
import QrcodeVue from "qrcode.vue";
import verifyCode from "src/components/auth/verifyCode.vue";
export default {
  name: "Login",
  components: {
    QrcodeVue,
    verifyCode,
  },
  data() {
    return {
      isSend: false,
      tips: false,
      cutDown: 0,
      loginType: "PassWord", // PassWord 邮箱密码，verify，邮箱验证码，wechat微信登录 微信登录没有绑定邮箱时跳转绑定邮箱业务逻辑
      isAgree: false,
      isLogin: true,
      loginMsg: {
        RB_Group_Id: 0,
        Mailbox: "",
        PassWord: "",
        MailCode: "",
      },
      // , 'google', 'facebook', 'apple'
      typeList: ["wechat"],
      logo: "",
      flag: 2,
      mylabel: "登入",
      loading: false,
      inSending:false
    };
  },
  created() {},
  mounted() {
    const { code, state, path } = this.$route.query;
    this.path = path;
    
    try {
      if (code) {
        this.fetchLoginInfo(code, state);
        this.isLogin = false;
        this.loginType = "bindEmail";
        this.mylabel = "立即绑定";
      } else if(this.$q.platform.is.mobile && location.href.indexOf('?code=')!=-1){
        let params = location.href.split('?')[1].split('#/')[0].split('&')
        this.fetchLoginInfo(params[0].split('=')[1], params[1].split('=')[1]);
      }
    } catch (error) {
      console.log(error.message)
    }
    this.getOpenInfo();
    var jObj = JSON.parse(localStorage.getItem("groupinfo"));
    this.loginMsg.RB_Group_Id = jObj.GroupId;
    //获取网站基础配置
    if (localStorage.baseifo) {
      var jObj = JSON.parse(window.localStorage.getItem("baseifo"));
      this.logo = jObj.Config.Logo;
    }
    this.isLogin = !this.$route.query.t || this.$route.query.t != 1;
  },
  watch: {
    loginType: function () {
      this.resetInfo();
    },
  },
  methods: {
    async formValidateHandler(formName) {
      let temp = this.$refs[formName];
      let formObj = temp instanceof Array ? temp[0] : temp;
      return formObj.validate();
    },
    fetchLoginInfo(code, state) {
      this.apipost(
        "getWXToken_post",
        {
          code,
          state,
          platform:this.$q.platform.is.desktop?'':'mobile'
        },
        (res) => {
          if (res.data.resultCode == 1) {
            const { type, unoinid } = res.data.data;
            if (type === 1) {
              
              window.localStorage.setItem(
                "b2bUser",
                JSON.stringify(res.data.data)
              );
              if (this.path) {
                this.CommonJump(this.path, {});
              } else {
                this.CommonJump("/index", {});
              }
            } else {
              this.isLogin = false;
              // 绑定邮箱
              this.loginType = "bindEmail";
              this.userId = unoinid;
            }
          } else {
            this.$message.error(res.data.message);
          }
        },
        (err) => {}
      );
    },
    getOpenInfo() {
      this.apipost(
        "GetOpenInfo_post",
        {},
        (r) => {
          if (r.data.resultCode == 1) {
            this.openInfo = r.data.data;
          } else {
            this.$message.error(res.data.message);
          }
        },
        null
      );
    },
    setWechatCode() {
      const { AppID, State, OpenRedirectUri } = this.openInfo;
      const obj = new WxLogin({
        self_redirect: false,
        id: "login_container",
        appid: AppID,
        scope: "snsapi_login",
        redirect_uri: OpenRedirectUri, // 是	重定向地址，需要进行UrlEncode
        state: State,
        style: "",
        href: "",
      });
    },
    loginToRegister() {
      this.isLogin = !this.isLogin;
      if (!this.isLogin) {
        this.mylabel = "注册";
        this.loginType = "MailCode";
      } else {
        this.mylabel = "登录";
      }
    },
    reSend() {
      if (this.cutDown) {
        return;
      }
      this.inSending = false;
      this.sendVerify();
    },
    sendVerify() {
      if (this.inSending) return;
      this.inSending = true;

      if (!this.userId && this.loginType === "bindEmail") {
        this.$message.error("微信登录出错,请重新登录");
        return;
      }
      let SendType = this.userId ? 3 : this.isLogin ? 1 : 0;
      this.apipost(
        "directCustomer_post_SendMail",
        {
          Mailbox: this.loginMsg.Mailbox,
          SendType: SendType,
          Id: this.userId,
        },
        (res) => {
          this.inSending = false;
          if (res.data.resultCode == 1) {
            this.isSend = true;
            this.cutDown = 60;
            this.startCutDown();
          } else {
            this.$message.error(res.data.message);
          }
        },
        null
      );
    },
    startCutDown() {
      this.timer = setTimeout(() => {
        this.cutDown--;
        if (this.cutDown > 0) {
          this.startCutDown();
        } else {
          clearTimeout(this.timer);
          this.timer = null;
        }
      }, 1000);
    },
    resetInfo() {
      this.isSend = false;
      this.tips = false;
      this.loginMsg = {
        RB_Group_Id: 0,
        Mailbox: "",
        PassWord: "",
        MailCode: "",
      };
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.cutDown = 0;
    },
    changeLoginType() {
      if (this.loginType === "PassWord") {
        this.loginType = "MailCode";
      } else {
        this.loginType = "PassWord";
      }
    },
    useWechatLogin() {
      // this.loginType = "wechat";
      // this.setWechatCode()
      const { AppID, State, OpenRedirectUri } = this.openInfo;
        let redirect_uri = OpenRedirectUri;
      if(this.$q.platform.is.desktop){
        const url = `https://open.weixin.qq.com/connect/qrconnect?appid=${AppID}&redirect_uri=${encodeURIComponent('http://www.oytour.com/#/login')}&response_type=code&scope=snsapi_login&state=${State}&wechat_redirect=${redirect_uri}`;
        window.location.href = url;
      }else{
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx44c35529819fc345&redirect_uri=${encodeURIComponent('http://www.oytour.com/#/login')}&response_type=code&scope=snsapi_userinfo&state=${State}&&connect_redirect=1#wechat_redirect`;
        window.location.href = url;
      }
      
    },
    async login() {
      if (this.loading) {
        return;
      }
      if (await this.formValidateHandler("loginForm")) {
        if (this.loginType === "MailCode" || this.loginType === "bindEmail") {
          if (!this.isSend) {
            this.$message.error("請發送驗證碼");
            return;
          }
          if (!this.$refs.verify.validate()) return;
        }
        if (!this.isAgree) {
          this.$message.warn("请先同意平台使用协议");
          return;
        }
        let params = { ...this.loginMsg };
        let url = "MailboxPwdLogin_post"; // 密码登录
        if (!this.isLogin) {
          url = "directCustomer_post_MailRegister";
        } else if (this.loginType === "MailCode") {
          url = "MailboxLogin_post";
        }
        if (this.loginType === "bindEmail") {
          url = "BindMailByOpenId_post";
          params.Unoinid = this.userId;
        }
        this.loading = true;
        this.apipost(
          url,
          params,
          (res) => {
            if (res.data.resultCode == 1) {
              window.localStorage.setItem(
                "b2bUser",
                JSON.stringify(res.data.data)
              );
              if (this.path) {
                this.CommonJump(this.path, {});
              } else {
                this.CommonJump("/index", {});
              }
            } else {
              this.$message.error(res.data.message);
            }
            this.loading = false;
          },
          (err) => {
            this.loading = false;
          }
        );
      }
    },
    resetPassword() {
      this.CommonJump("/resetPassword", {});
    },
  },
};
</script>
