<template>
  <div class="row full-height">
    <div class="col q-pa-xl fit row justify-center height">
      <div style="width: 450px" class="column justify-between content-between">
        <div class="row items-center">
          <div class="col">
            <q-btn round flat size="md" @click="goback">
              <svg-icon
                icon="Navigation/Arrow-left.svg"
                :size="24"
                tips="$t('newpwd.goback')"
              ></svg-icon>
            </q-btn>
          </div>
          <div class="text-grey-6 text-weight-bold text-right">
            <span>{{ $t("newpwd.notaccess") }}</span>
            <router-link
              :to="{ path: '/auth/login' }"
              class="text-primary pfb text-subtitle"
              >{{ $t("newpwd.registlink") }}</router-link
            >
          </div>
        </div>
        <div class="q-py-xxl full-width">
          <div class="text-h3 text-weight-bold">{{ $t("newpwd.title") }}</div>
          <div class="text-grey-6 q-mt-sm q-mb-lg">{{ $t("newpwd.subtitle") }}</div>
          <div class="form-box q-my-lg">
            <div class="q-mb-xl">
              <q-input
                :label="$t('newpwd.pass')"
                :hint="$t('newpwd.passTips')"
                type="password"
                standout
                v-model="password"
                dense
                ref="passwordRef"
                :rules="passRules"
              />
              <div class="row q-mt-sm">
                <div
                  class="col rounded-borders"
                  style="height: 8px"
                  :class="{
                    'bg-positive': level.indexOf('low') != -1,
                    'bg-grey-3': level.indexOf('low') == -1,
                  }"
                ></div>
                <div
                  class="col q-mx-md rounded-borders"
                  style="height: 8px"
                  :class="{
                    'bg-positive': level.indexOf('middle') != -1,
                    'bg-grey-3': level.indexOf('middle') == -1,
                  }"
                ></div>
                <div
                  class="col rounded-borders"
                  style="height: 8px"
                  :class="{
                    'bg-positive': level.indexOf('high') != -1,
                    'bg-grey-3': level.indexOf('high') == -1,
                  }"
                ></div>
              </div>
            </div>
            <div class="q-mb-lg">
              <q-input
                :label="$t('newpwd.repeatPass')"
                type="password"
                standout
                v-model="repeatPassWord"
                dense
                ref="repeatPassWordRef"
                :rules="[(val: any) => val == password || $t('newpwd.repeatPassvalidate')]"
              />
            </div>
          </div>
          <div
            class="row items-center"
            :class="{ row: $q.platform.is.desktop, column: $q.platform.is.mobile }"
          >
            <div class="col">
              <q-btn
                size="md"
                class="q-px-lg"
                color="primary"
                :loading="loading"
                @click="resetPassword"
                unelevated
                :label="$t('forget.submit')"
              />
            </div>
          </div>
        </div>
        <div>
          <q-select
            borderless
            v-model="currentLang"
            :options="langs"
            map-options
            option-value="langLocale"
            option-label="langName"
            style="width: 180px"
          >
            <template v-slot:selected>
              {{ $t("lanuage") }}：
              <q-chip
                dense
                square
                color="white"
                text-color="primary"
                class="q-my-none q-ml-xs q-mr-none"
              >
                {{ currentLang.langName }}
              </q-chip>
            </template>
          </q-select>
        </div>
      </div>
    </div>
    <div class="col right-bg full-height mobile-hide"></div>
  </div>
  <q-dialog no-esc-dismiss persistent v-model="successModel">
    <q-card
      :class="{ 'q-pa-xl': $q.platform.is.desktop, 'q-pa-lg': $q.platform.is.mobile }"
    >
      <q-card-section>
        <div class="text-center q-mb-md">
          <svg-icon icon="Code/Done-circle.svg" color="success" :size="80"></svg-icon>
        </div>
        <div>{{ $t("newpwd.updateResult") }}</div>
        <div class="text-center q-mt-xl">
          <q-btn
            color="primary"
            @click="goback"
            unelevated
            :label="$t('newpwd.resultBtn')"
          />
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import useMetaModule from "../../module/meta/metaModule";
import { useI18n } from "vue-i18n";
import { getLangs } from "../../utils/tools";
import { SitLang } from "../../@types";
import svgIcon from "../../components/global/svg-icon.vue";
import UserService from "../../api/user";
import message from "../../utils/message";
import { ApiResult } from "../../@types/enumHelper";
import { currentRouter } from "../../router";

export default defineComponent({
  components: { svgIcon },
  setup() {
    let { setTitle } = useMetaModule();

    const { locale, t } = useI18n();
    setTitle(t("newpwd.pageTitle"));
    const data = reactive({
      currentLang: {} as SitLang,
      langs: [] as SitLang[],
      password: "",
      loading: false,
      successModel: false,
      passwordRef: null,
      repeatPassWord: "",
      repeatPassWordRef: null,
      level: [] as string[],
      accountCertificate: "" as string | undefined,
      passRules: [
        (val: string | undefined) => (val && val.length >= 8) || t("newpwd.notEmptyPass"),
        (val: string | undefined) =>
          (val && val.length <= 16) || t("newpwd.maxLengthPass"),
        (val: string) => methods.checkPassword(val) || "",
      ],
    });
    data.accountCertificate = currentRouter.currentRoute.value.params.code?.toString();
    if (!data.accountCertificate) {
      //window.history.go(-1)
    }
    data.langs = getLangs();
    if (data.langs && data.langs.length > 0) {
      data.currentLang = data.langs.find((x) => x.langLocale == locale.value) ?? {};
    }

    let methods = {
      resetPassword() {
        if (data.loading) return;
        const passRefVal = data.passwordRef as any;
        const repassRefVal = data.repeatPassWordRef as any;
        passRefVal.validate();
        repassRefVal.validate();
        if (!passRefVal.hasError && !repassRefVal.hasError) {
          data.loading = true;
          //hasError
          UserService.resetPassword(data.accountCertificate as string, data.password)
            .then((r) => {
              data.loading = false;
              if (r.data.resultCode == ApiResult.SUCCESS) {
                data.successModel = true;
              } else {
                message.errorMsg(r.data.message);
              }
            })
            .catch((e) => {
              data.loading = false;
              message.errorMsg(e.message);
            });
        }
      },
      goback() {
        window.location.href = "/auth/login";
      },
      checkPassword(value: string): boolean {
        data.level = [];
        if (value && value.length >= 8 && value.length <= 16) {
          // 校验是数字
          const regex1 = /^\d+$/;
          // 校验字母
          const regex2 = /^[A-Za-z]+$/;
          // 校验符号
          const regex3 = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$/;
          if (regex1.test(value)) {
            data.level.push("low");
          } else if (regex2.test(value)) {
            data.level.push("low");
          } else if (regex3.test(value)) {
            data.level.push("low");
          } else if (/^[A-Za-z\d]+$/.test(value)) {
            data.level.push("low");
            data.level.push("middle");
          } else if (
            /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\d]+$/.test(
              value
            )
          ) {
            data.level.push("low");
            data.level.push("middle");
          } else if (
            /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z]+$/.test(
              value
            )
          ) {
            data.level.push("low");
            data.level.push("middle");
          } else if (
            /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z\d]+$/.test(
              value
            )
          ) {
            data.level.push("low");
            data.level.push("middle");
            data.level.push("high");
          }
          return true;
        }
        return false;
      },
    };

    return { ...toRefs(data), ...methods };
  },
});
</script>

<style>
.login-bg {
  background-image: url(../../assets/images/8.png);
  background-position-x: center;
  background-position-y: bottom;
  background-repeat: no-repeat;
  background-size: contain;
}
.w-450 {
  width: 450px;
  box-shadow: 0 0.5rem 1.5rem 0.5rem rgba(0, 0, 0, 0.075) !important;
  border-radius: 0.475rem !important;
}
.w-450-only {
  width: 450px;
}
.right-bg {
  background-image: url(../../assets/images/login-right-bg.png);
  background-position-x: left;
  background-position-y: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.top-bg {
  background-image: url(https://preview.keenthemes.com/metronic8/demo1/assets/media/auth/bg11.png);
  background-position-x: -100px;
  background-position-y: -85vh;
  background-repeat: no-repeat;
  background-size: cover;
}
</style>
