<template>
  <Theme>
    <view class="wrap">
      <Navbar autoBack fixed @leftClick="leftClick" />
      <view class="content">
        <view class="logo">
          <image
            class="logo_img"
            src="@/static/login/login_logo.png"
            mode="widthFix"
          ></image>
        </view>

        <!-- Tab 切换栏 -->
        <view class="tab-bar">
          <view
            class="tab-item"
            :class="{ active: loginType === 'phone' }"
            @click="changeTab('phone')"
          >
            <trans _t="手机登录" />
          </view>
          <view
            class="tab-item"
            :class="{ active: loginType === 'email' }"
            @click="changeTab('email')"
          >
            <trans _t="邮箱登录" />
          </view>
        </view>
        <up-form
          labelPosition="left"
          :model="form"
          :rules="getRules()"
          ref="formRef"
          labelWidth="0"
        >
          <up-form-item prop="userphone">
            <up-input
              type="text"
              shape="circle"
              :placeholder="t(loginType === 'phone' ? '手机号' : '电子邮件')"
              v-model="form.userphone"
            >
              <template #prefix>
                <view
                  @click="areaClick"
                  v-if="useSystem.getCountryCodes.length > 0"
                >
                  <Area
                    codeNum
                    v-model="areacode"
                    ref="areaRef"
                    @confirm="areaConfirm"
                    v-show="loginType === 'phone'"
                  />
                </view>
                <view class="prefix">
                  <image
                    src="@/static/login/email.png"
                    class="img"
                    mode="widthFix"
                    v-show="loginType === 'email'"
                  ></image>
                </view>
              </template>
            </up-input>
          </up-form-item>
          <up-form-item prop="userpass">
            <up-input
              type="password"
              shape="circle"
              :placeholder="t('密码')"
              v-model="form.userpass"
            >
              <template #prefix>
                <view class="prefix">
                  <image
                    src="@/static/login/password.png"
                    class="img"
                    mode="widthFix"
                  ></image>
                </view>
              </template>
            </up-input>
          </up-form-item>
        </up-form>
        <view class="confirm_box">
          <up-checkbox
            activeColor="var(--black)"
            labelSize="14"
            labelColor="#676969"
            iconSize="16"
            name="agree"
            usedAlone
            v-model:checked="selectAllChecked"
            class="right-check"
          >
            <template #label>
              <trans class="text" _t="我已阅读并同意" />
              <trans
                _t="用户协议"
                class="agent"
                @click.stop="openAgent('agree')"
              />
              <trans _t="和" />
              <trans
                _t="隐私协议"
                class="agent"
                @click.stop="openAgent('private')"
              />
            </template>
          </up-checkbox>
        </view>
        <view class="label_texts" @click="goTo('/pages/login/forget')">
          <trans _t="忘记密码" />
        </view>
        <up-button
          :text="t('登录')"
          class="btn"
          color="var(--light)"
          @click="submit"
        ></up-button>
        <view class="tips">
          <view class="line"></view>
          <trans class="tips_text" _t="或者" />
          <view class="line"></view>
        </view>
        <template v-if="!isAppIOS">
          <view class="tip_text">
            <trans _t="tips_text" />
          </view>
          <view class="btns">
            <FacebookLogin @success="facebookLoginSuccess" />
            <!-- #ifdef H5 -->
            <GoogleLogin @success="handleGoogleSuccess" />
            <!-- #endif -->
          </view>
        </template>
        <view class="labels">
          <view class="label_text" @click="goTo('/pages/login/register')">
            <trans _t="没有账号" />
            <trans class="register" _t="注册" />
          </view>
        </view>
      </view>
    </view>

    <SimpleAgreementModal ref="agreementModal" />
  </Theme>
</template>
<script setup>
import { reactive, ref, onMounted, computed } from "vue";
import { t } from "@/locale";
import Navbar from "@/components/navbar";
import plaCard from "@/components/placard";
import Area from "@/components/area";
import { useUserStore, useSystemStore, useTabbarStore } from "@/store";
import { USERS_THIRD_LOGIN } from "@/api";
import { Toast, setStorage, removeStorage, getStorage } from "@/utils";
import verConfig from "@/ver.config";
import { getCurrentInstance } from "vue";
import FacebookLogin from "./components/facebook-login.vue";
import GoogleLogin from "./components/google-login.vue";
import SimpleAgreementModal from "@/components/simpleAgreementModal";

const { proxy } = getCurrentInstance();
const adjustPosition = proxy.$adjustPosition;
const isAppIOS = ref(false);

const useUser = useUserStore();
const useSystem = useSystemStore();
const useTabbar = useTabbarStore();
const formRef = ref(null);
const selectAllChecked = ref(false);
const agreementModal = ref(null);
const loginType = ref("phone");

const areaRef = ref(null);
const areacode = ref("");

const areaClick = () => {
  areaRef.value && areaRef.value.open();
};

const form = reactive({
  userphone: "",
  userpass: "",
});

const areaConfirm = (item) => {
  // console.log(item, areacode.value, "areaConfirm");
};
const getRules = () => ({
  userphone: {
    required: true,
    message: t(
      loginType.value === "phone" ? "手机号为必填项" : "电子邮件为必填项"
    ),
    trigger: ["change"],
  },
  userpass: {
    required: true,
    message: t("密码是必需的"),
    trigger: ["change"],
  },
});
const handleGoogleSuccess = (userInfo) => {
  getUserInfo(userInfo, "google");
};

const facebookLoginSuccess = (userInfo) => {
  getUserInfo(userInfo, "facebook");
};
const getUserInfo = async (info, platform) => {
  try {
    let para = {
      platform: platform,
    };
    if (platform === "facebook") {
      para.accessToken = info.accessToken;
      para.userID = info.userID;
    } else if (platform === "google") {
      para.id_token = info.credential;
    }

    const res = await USERS_THIRD_LOGIN(para);
    setStorage(verConfig.tokenName, res.data.token);
    setStorage(verConfig.infoName, res.data);

    Toast(res.msg, 1000).then(() => {
      let timer = setTimeout(() => {
        const backUrl = getStorage("beforeLoginPage");
        if (backUrl) {
          removeStorage("beforeLoginPage");
          const arr = [
            "/pages/index/index",
            "/pages/shop/cart",
            "/pages/community/index",
            "/pages/order/index",
            "/pages/user/index",
            "/pages/chat/index",
          ];
          const hasAny = arr.some((s) => backUrl.includes(s));
          if (hasAny) {
            uni.switchTab({ url: backUrl });
          } else {
            uni.redirectTo({ url: backUrl });
          }
        } else {
          uni.switchTab({ url: "/pages/index/index" });
          useTabbar.getPageCur("index");
        }
        clearTimeout(timer);
      }, 1000);
    });
  } catch (error) {
    Toast(error.msg);
    close();
  }
};

const openAgent = (type) => {
  agreementModal.value && agreementModal.value.open(type);
};

const leftClick = () => {
  uni.switchTab({ url: "/pages/index/index" });
  useTabbar.getPageCur("index");
};

const changeTab = (type) => {
  loginType.value = type;
  form.userphone = "";
  formRef.value.clearValidate();
};

onMounted(() => {
  // #ifdef APP-PLUS
  const sys = uni.getSystemInfoSync();
  isAppIOS.value = sys.platform === "ios";
  // #endif
  useUser.loginOut(true);
  // initGoogleSignIn()
});
const service = () => {
  useSystem.service();
};

const goTo = (url) => {
  uni.navigateTo({ url });
};

const submit = () => {
  formRef.value
    .validate()
    .then((valid) => {
      if (!selectAllChecked.value) {
        return Toast(t("请阅读并同意"));
      }
      const para = JSON.parse(JSON.stringify(form));
      if (loginType.value == "phone") {
        para.userphone = areacode.value + para.userphone;
      }
      useUser.login(para);
    })
    .catch(() => {});
};
</script>
<style lang="less" scoped>
@import url("@/style.less");

@cut-size: 24rpx;

.wrap {
  min-height: 100vh;
  background: var(--light);

  .content {
    padding: 40rpx 60rpx;

    .logo {
      .flex_center();
      padding-bottom: 48rpx;

      &_img {
        width: 284rpx;
      }
    }

    .login_title {
      color: var(--black);
      .size();
      position: relative;
      width: fit-content;
      line-height: 44rpx;
      padding-bottom: 10rpx;

      &::before {
        position: absolute;
        content: "";
        left: 0;
        bottom: 0;
        width: 75%;
        height: 2px;
        background-color: var(--black);
      }
    }

    .tab-bar {
      display: flex;
      margin-bottom: 48rpx;

      .tab-item {
        position: relative;
        width: 50%;
        height: 100rpx;
        line-height: 100rpx;
        text-align: center;
        font-size: 28rpx;
        color: var(--black);
        background: url("@/static/login/left.png");
        background-size: 100% 100%;
        &.active {
          background: url("@/static/login/left_active.png");
          background-size: 100% 100%;
          color: #fff;
        }
        &:not(:first-child) {
          background: url("@/static/login/right.png");
          background-size: 100% 100%;
          &.active {
            background: url("@/static/login/right_active.png");
            background-size: 100% 100%;
            color: #fff;
          }
        }
      }
    }

    /deep/ .u-form {
      margin-top: 16px;
    }

    /deep/ .u-form-item {
      padding-bottom: 10px;

      .u-form-item__body {
        padding: 0;
      }

      .u-form-item__body__right__message {
        margin-top: 10rpx;
      }

      .u-form-item__body__right__content {
        .u-input {
          padding: 16rpx 24rpx 16rpx !important;
          // border-radius: 16rpx !important;
          background-color: var(--bg);
          border-color: #d8d8d8 !important;

          // &:hover {
          //   box-shadow: 0 0 0 1px var(--primary) inset;
          // }
        }

        .u-input__content__field-wrapper__field {
          height: 32px;
          line-height: 32px;

          .uni-input-input {
            font-size: 28rpx !important;
          }

          .input-placeholder {
            color: var(--text-01) !important;
            font-size: 24rpx;
          }
        }
      }
    }
    .phone_box {
      display: flex;
      align-items: center;
      margin-right: 18rpx;
    }
    .prefix {
      display: flex;
      align-items: center;
      width: 40rpx;
      margin-right: 18rpx;

      .img {
        width: inherit;
        display: block;
      }
    }

    .btn {
      color: var(--light);
      background-color: var(--black) !important;
      border: 1px solid var(--black) !important;
      padding: 16rpx 30rpx;
      height: 100rpx;
      border-radius: 100px;
      margin-bottom: 24rpx;
      color: var(--light);

      /deep/ .u-button__text {
        font-size: 32rpx !important;
        font-weight: 700;
      }
    }

    .label_texts {
      text-align: right;
      padding: 4px 0 14px;
      font-size: 24rpx;
      line-height: 44rpx;
      color: var(--text-01);
    }
    .confirm_box {
      display: flex;
      .agent {
        margin: 0 6rpx;
        color: var(--red);
        text-decoration: underline;
      }
    }

    .tips {
      display: flex;
      align-items: center;

      .line {
        flex: 1;
        border: 1px solid #d8d8d8;
      }

      .tips_text {
        .size(24rpx);
        font-weight: 500;
        color: #d8d8d8;
        margin: 0 10rpx;
        line-height: 44rpx;
      }
    }

    .tip_text {
      color: var(--text-01);
      .size(20rpx);
      line-height: 44rpx;
      text-align: center;
    }

    .btns {
      .ver();
      flex-direction: column;

      &_item {
        width: 400rpx;
        border: 1px solid var(--black);
        border-radius: 100px;
        padding: 14rpx 52rpx;
        margin-top: 18rpx;
        .ver();
        color: var(--text-02);
        .size(24rpx);

        .btn_icon {
          width: 48rpx;
          margin-right: 52rpx;

          .img {
            width: inherit;
            display: block;
          }
        }
      }
    }

    .labels {
      margin-top: 24rpx;
      padding-bottom: 40rpx;
      .flex_center();

      .label_text {
        cursor: pointer;
        color: var(--text-01);
        .size(24rpx);
        line-height: 44rpx;

        .register {
          .size(28rpx);
          color: var(--black);
        }
      }
    }
  }
}
</style>