<template>
  <Theme>
    <view class="wrap">
      <Navbar />
      <view class="content">
        <view class="logo">
          <image
            class="logo_img"
            src="@/static/login/login_logo.png"
            mode="widthFix"
          ></image>
        </view>
        <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="code" v-if="loginType === 'email'">
            <up-input
              :placeholder="t('验证码')"
              shape="circle"
              v-model="form.code"
              type="number"
              maxlength="6"
            >
              <template #prefix>
                <view class="prefix">
                  <image
                    src="@/static/login/code.png"
                    class="img"
                    mode="widthFix"
                  ></image>
                </view>
              </template>
              <template #suffix>
                <view
                  class="code_btn"
                  @click="getCode"
                  v-if="countdown == 60 || countdown == 0"
                >
                  <trans color="var(--light)" _t="发送" />
                  <template> </template>
                </view>
                <view class="code_btn" v-else> {{ countdown }}&nbsp;S </view>
              </template>
            </up-input>
          </up-form-item>
          <up-form-item prop="userpass">
            <up-input
              type="userpass"
              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-item prop="confirmpassword">
            <up-input
              type="userpass"
              shape="circle"
              :placeholder="t('确认密码')"
              v-model="form.confirmpassword"
            >
              <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-item prop="fromid">
            <up-input
              type="text"
              shape="circle"
              :placeholder="t('邀请码')"
              v-model="form.fromid"
            >
              <template #prefix>
                <view class="prefix">
                  <image
                    src="@/static/login/formId.png"
                    class="img"
                    mode="widthFix"
                  ></image>
                </view>
              </template>
            </up-input>
          </up-form-item>
        </up-form>
        <up-button
          :text="t('注册')"
          class="btn"
          color="var(--light)"
          @click="submit"
        ></up-button>
        <view class="labels">
          <view class="label_text" @click="login">
            <trans _t="已有账户" />
            <trans class="register" _t="登录" />
          </view>
        </view>
      </view>
    </view>

    <PinCodeModal
      :visible="showPinModal"
      @close="showPinModal = false"
      @complete="handlePinComplete"
      isHome
    />
  </Theme>
</template>
<script setup>
import {
  reactive,
  ref,
  onMounted,
  nextTick,
  computed,
  onBeforeUnmount,
} from "vue";
import { t } from "@/locale";
import Navbar from "@/components/navbar";
import plaCard from "@/components/placard";
import Area from "@/components/area";
import PinCodeModal from "@/components/PinCodeModal";
import { useUserStore, useSystemStore, useTabbarStore } from "@/store";
import { USERS_EMAIL_GET, USER_SMS, USER_EDIT_PAYPASS } from "@/api";
import { Toast, throttle } from "@/utils";
import { onLoad } from "@dcloudio/uni-app";

const useUser = useUserStore();
const formRef = ref(null);
const countdown = ref(60);
const timer = ref(null);
const loginType = ref("phone");

const useSystem = useSystemStore();
const useTabbar = useTabbarStore();
const areaRef = ref(null);
const areacode = ref("");
const showPinModal = ref(false);

const areaClick = () => {
  areaRef.value && areaRef.value.open();
};
const areaConfirm = (item) => {
  // console.log(item, areacode.value, "areaConfirm");
};

const form = reactive({
  userphone: "",
  userpass: "",
  confirmpassword: "",
  fromid: "",
  code: "",
});
const getRules = () => ({
  userphone: {
    required: true,
    message: t(
      loginType.value === "phone" ? "手机号为必填项" : "电子邮件为必填项"
    ),
    trigger: ["change"],
  },
  code: {
    required: true,
    message: t("验证码为必填项"),
    trigger: ["change"],
  },
  userpass: {
    required: true,
    message: t("密码是必需的"),
    trigger: ["change"],
  },
  confirmpassword: [
    {
      required: true,
      message: t("密码是必需的"),
      trigger: ["change"],
    },
    {
      validator: (rule, value, callback) => {
        if (value != form.userpass) {
          callback(new Error(t("两次密码不一致")));
        } else {
          callback();
        }
      },
    },
  ],
});
const handlePinComplete = async (pass) => {
  const res = await USER_EDIT_PAYPASS({
    newpass: pass,
  });
  Toast(res.msg, 1000).then(() => {
    showPinModal.value = false;
    uni.switchTab({ url: "/pages/index/index" });
    useTabbar.getPageCur("index");
  });
};
const changeTab = (type) => {
  loginType.value = type;
  form.userphone = "";
  formRef.value.clearValidate();
};

const getCode = throttle(async () => {
  clear();
  countdown.value = 60;
  if (!form.userphone)
    return Toast(
      t(loginType.value == "phone" ? "请输入手机号" : "请输入电子邮件")
    );
  try {
    let para = {
      must: 1,
    };
    if (loginType.value == "phone") {
      para.userphone = areacode.value + form.userphone;
    }
    const res =
      loginType.value == "phone"
        ? await USER_SMS(para)
        : await USERS_EMAIL_GET({ email: form.userphone });
    Toast(res.msg);
    timer.value = setInterval(() => {
      if (countdown.value == 0) {
        clear();
        return;
      }
      nextTick(() => {
        countdown.value--;
      });
    }, 1000);
  } catch (error) {
    Toast(error.msg);
  }
}, 6000);

onLoad((options) => {
  form.fromid = options.fromid || "";
});
onMounted(() => {
  // useUser.loginOut(true);
});
const clear = () => {
  clearInterval(timer.value);
  countdown.value = 60;
  timer.value = null;
};

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});

const goTo = (url) => {
  if (!url) return;
  uni.navigateTo({ url });
};
const login = () => {
  uni.reLaunch({ url: "/pages/login/login" });
};

const submit = throttle(() => {
  formRef.value
    .validate()
    .then(async (valid) => {
      const { confirmpassword, ...params } = form;
      if (loginType.value == "phone") {
        params.userphone = areacode.value + params.userphone;
        params.code = "112233";
      }
      try {
        const result = await useUser.login(params, true);
        console.log("登录成功", result);
        showPinModal.value = true;
      } catch (error) {
        console.log("登录失败", error);
      }
    })
    .catch(() => {});
}, 6000);
</script>
<style lang="less" scoped>
@import url("@/style.less");

.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 {
          .flex_center();
          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;
      }
    }

    .code_btn {
      background-color: var(--black);
      .size(28rpx);
      padding: 10rpx 36rpx;
      color: var(--light);
      border-radius: 10rpx;
    }

    .btn {
      color: var(--light);
      background-color: var(--black) !important;
      border: 1px solid var(--black) !important;
      padding: 16rpx 30rpx;
      height: 100rpx;
      margin-top: 60rpx;
      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);
    }

    .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>