<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { ref, reactive } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { registerRules } from "../utils/rule";
import type { FormInstance, FormItemProp } from "element-plus";
import { useVerifyCode } from "../utils/verifyCode";
import { clone } from "@pureadmin/utils";
import { $t, transformI18n } from "@/plugins/i18n";
import { useUserStoreHook } from "@/store/modules/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Lock from "@iconify-icons/ri/lock-fill";
import Iphone from "@iconify-icons/ep/iphone";
import User from "@iconify-icons/ri/user-3-fill";
import UserName from "@iconify-icons/ri/user-4-line";
import Mail from "@iconify-icons/ri/mail-open-line";
import { postGetCodeAPI, postRegisterAPI } from "@/api/login";

const { t } = useI18n();
const checked = ref(false);
const loading = ref(false);
const timer = ref(null);
const ruleForm = reactive({
  username: "",
  phone: "",
  gender: 1,
  email: "",
  nickname: "",
  department_id: "",
  code: "",
  password: "",
  repeatPassword: ""
});
/**当前选项 */
const currentOption = ref<number>(1);
/**
 * 点击返回
 */
const clickBack = () => {
  if (currentOption.value >= 1) {
    currentOption.value--;
  } else {
    currentOption.value = 1;
  }
};
/**
 * 点击下一步
 */
const clickNext = async () => {
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (currentOption.value <= 2) {
        currentOption.value++;
      } else {
        currentOption.value = 2;
      }
    }
  });
};
const ruleFormRef = ref<FormInstance>();
const { isDisabled, text } = useVerifyCode();
const repeatPasswordRule = [
  {
    validator: (rule, value, callback) => {
      if (value === "") {
        callback(new Error(transformI18n($t("login:PassWordSureReg"))));
      } else if (ruleForm.password !== value) {
        callback(new Error(transformI18n($t("login:PassWordDifferentReg"))));
      } else {
        callback();
      }
    },
    trigger: "blur"
  }
];

const onUpdate = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (checked.value) {
        const res = await postRegisterAPI({
          username: ruleForm.username,
          password: ruleForm.password,
          gender: ruleForm.gender,
          email: ruleForm.email,
          nickname: ruleForm.nickname,
          phone: ruleForm.phone,
          code: ruleForm.code,
          department_id: ruleForm.department_id
        });
        if (res.code === 200) {
          message(transformI18n($t("login:RegisterSuccess")), {
            type: "success"
          });
          loading.value = false;
          useUserStoreHook().SET_CURRENTPAGE(0);
        } else {
          message(res.msg, {
            type: "error"
          });
        }
      } else {
        loading.value = false;
        message(transformI18n($t("login:TickPrivacy")), {
          type: "warning"
        });
      }
    } else {
      loading.value = false;
    }
  });
};
const start = async (
  formEl: FormInstance | undefined,
  props: FormItemProp,
  time = 120
) => {
  if (!formEl) return;
  const initTime = clone(time, true);
  await formEl.validateField(props, async isValid => {
    if (isValid) {
      const res = await postGetCodeAPI({
        username: ruleForm.username,
        title: "注册",
        mail: ruleForm.email
      });
      if (res.code === 200) {
        clearInterval(timer.value);
        isDisabled.value = true;
        text.value = `${time}`;
        timer.value = setInterval(() => {
          if (time > 0) {
            time -= 1;
            text.value = `${time}`;
          } else {
            text.value = "";
            isDisabled.value = false;
            clearInterval(timer.value);
            time = initTime;
          }
        }, 1000);
      } else {
        message(res.msg, { type: "error" });
      }
    }
  });
};
function onBack() {
  useUserStoreHook().SET_CURRENTPAGE(0);
}
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="registerRules"
    size="large"
  >
    <Motion v-if="currentOption === 1">
      <el-form-item
        :rules="[
          {
            required: true,
            message: transformI18n($t('login:UsernameReg')),
            trigger: 'blur'
          }
        ]"
        prop="username"
      >
        <el-input
          v-model="ruleForm.username"
          clearable
          :placeholder="t('login:Username')"
          :prefix-icon="
            useRenderIcon(UserName, {
              color: '#4380FF',
              width: 32,
              height: 32
            })
          "
        />
      </el-form-item>
    </Motion>
    <Motion v-if="currentOption === 1">
      <el-form-item
        :rules="[
          {
            required: true,
            message: transformI18n($t('login:NicknameReg')),
            trigger: 'blur'
          }
        ]"
        prop="nickname"
      >
        <el-input
          v-model="ruleForm.nickname"
          clearable
          :placeholder="t('login:Nickname')"
          :prefix-icon="
            useRenderIcon(User, {
              color: '#4380FF',
              width: 32,
              height: 32
            })
          "
        />
      </el-form-item>
    </Motion>

    <Motion v-if="currentOption === 1" :delay="100">
      <el-form-item prop="phone">
        <el-input
          v-model="ruleForm.phone"
          clearable
          :placeholder="t('login:Phone')"
          :prefix-icon="
            useRenderIcon(Iphone, {
              color: '#4380FF',
              width: 32,
              height: 32
            })
          "
        />
      </el-form-item>
    </Motion>
    <Motion v-if="currentOption === 2" :delay="100">
      <el-form-item prop="email">
        <el-input
          v-model="ruleForm.email"
          clearable
          :placeholder="t('login:Email')"
          :prefix-icon="
            useRenderIcon(Mail, {
              color: '#4380FF',
              width: 32,
              height: 32
            })
          "
        />
      </el-form-item>
    </Motion>

    <Motion v-if="currentOption === 2" :delay="150">
      <el-form-item prop="code">
        <div class="w-full flex justify-between">
          <el-input
            v-model="ruleForm.code"
            clearable
            :placeholder="t('login:EmailVerifyCode')"
            :prefix-icon="
              useRenderIcon('ri:shield-keyhole-line', {
                color: '#4380FF',
                width: 32,
                height: 32
              })
            "
          />
          <el-button
            :disabled="isDisabled"
            class="ml-2"
            @click="start(ruleFormRef, 'email')"
          >
            {{
              text.length > 0
                ? text + t("login:Info")
                : t("login:GetVerifyCode")
            }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>

    <Motion v-if="currentOption === 2" :delay="200">
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          clearable
          show-password
          :placeholder="t('login:Password')"
          :prefix-icon="
            useRenderIcon(Lock, {
              color: '#4380FF',
              width: 32,
              height: 32
            })
          "
        />
      </el-form-item>
    </Motion>

    <Motion v-if="currentOption === 2" :delay="250">
      <el-form-item :rules="repeatPasswordRule" prop="repeatPassword">
        <el-input
          v-model="ruleForm.repeatPassword"
          clearable
          show-password
          :placeholder="t('login:Sure')"
          :prefix-icon="
            useRenderIcon(Lock, {
              color: '#4380FF',
              width: 32,
              height: 32
            })
          "
        />
      </el-form-item>
    </Motion>
    <Motion v-if="currentOption === 1" :delay="100">
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="ruleForm.gender" class="ml-4">
          <el-radio :value="1" size="default">男</el-radio>
          <el-radio :value="0" size="default">女</el-radio>
        </el-radio-group>
      </el-form-item>
    </Motion>

    <Motion :delay="300">
      <el-form-item>
        <el-checkbox v-model="checked">
          {{ t("login:ReadAccept") }}
        </el-checkbox>
        <el-button link type="primary">
          {{ t("login:PrivacyPolicy") }}
        </el-button>
      </el-form-item>
    </Motion>
    <Motion v-if="currentOption !== 1" :delay="350">
      <el-form-item>
        <div class="w-full flex justify-center items-center">
          <el-button
            class="w-[75%]"
            size="default"
            round
            :loading="loading"
            @click="clickBack"
          >
            {{ t("login:Laststep") }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>
    <Motion v-if="currentOption !== 2" :delay="350">
      <el-form-item>
        <div class="w-full flex justify-center items-center">
          <el-button
            class="w-[75%]"
            size="default"
            type="primary"
            round
            :loading="loading"
            @click="clickNext"
          >
            {{ t("login:Nextstep") }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>
    <Motion v-if="currentOption === 2" :delay="350">
      <el-form-item>
        <div class="w-full flex justify-center items-center">
          <el-button
            class="w-[75%]"
            size="default"
            type="primary"
            round
            :loading="loading"
            @click="onUpdate(ruleFormRef)"
          >
            {{ t("login:Register") }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>

    <Motion :delay="400">
      <el-form-item>
        <div class="w-full flex justify-center items-center">
          <el-button class="w-[75%]" round size="default" @click="onBack">
            {{ t("login:Back") }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>
  </el-form>
</template>
