<template>
  <syCommonDialog
    :visible="visible"
    type="element"
    :elementDialogProps="{
      title: getTitle(),
    }"
    showMask
    @closePopup="$emit('update:visible', false)"
  >
    <div v-if="visible">
      <CollectEmail
        v-if="currentStep === eStep.emailInput"
        :mode="mode"
        :email="globalState.userInfos.email"
        @collect="emailStatus = $event"
      ></CollectEmail>
      <CollectVerificationCode
        v-if="currentStep === eStep.oldEmailVerifyInput"
        ref="oldCodeRef"
        :target="globalState.userInfos.email || globalState.userInfos.phone"
        :fn-send-verification-code="
          () => {
            if (globalState.userInfos.email !== '') {
              return sendEmail({
                email: globalState.userInfos.email,
                template_id: 4,
              });
            } else {
              return sendSms({
                phone: globalState.userInfos.phone,
                template_id: 4,
              });
            }
          }
        "
        @collect="oldCodeStatus = $event"
      ></CollectVerificationCode>
      <CollectVerificationCode
        v-if="currentStep === eStep.newEmailVerifyInput"
        ref="newCodeRef"
        :target="emailStatus.value"
        :fn-send-verification-code="
          () => {
            return sendEmail({
              email: emailStatus.value,
              template_id: 4,
            });
          }
        "
        @collect="newCodeStatus = $event"
      ></CollectVerificationCode>

      <syButton
        mode="elementBtn"
        type="primary"
        :disabled="getDisableStatus"
        style="width: 100%; margin-top: 38px"
        @click="handleClickConfirm"
        >下一步</syButton
      >
    </div>
  </syCommonDialog>
</template>

<script setup lang="ts">
import { syCommonDialog, syButton } from "cqk-sy-ui";
import CollectVerificationCode from "@/components/Form/Collect/CollectVerificationCode.vue";
import { computed, ref } from "vue";
import { globalState } from "@/store/state";
import {
  checkEmail,
  checkOldPhone,
  editEmail,
  editPhone,
  sendSms,
  sendEmail,
} from "@/service/Api.service";
import { ElMessage } from "element-plus";
import CollectEmail from "@/components/Form/Collect/CollectEmail.vue";

const props = defineProps<{
  visible: boolean;
}>();
const emit = defineEmits(["update:visible", "update"]);
const mode = computed(() => {
  if (globalState.userInfos.email === "") {
    return "set";
  } else {
    return "change";
  }
});
enum eStep {
  emailInput,
  oldEmailVerifyInput,
  newEmailVerifyInput,
}

const oldCodeRef = ref<InstanceType<typeof CollectVerificationCode>>();
const newCodeRef = ref<InstanceType<typeof CollectVerificationCode>>();

const currentStep = ref(eStep.emailInput);
const emailStatus = ref({
  isValid: false,
  value: "",
});
const oldCodeStatus = ref({
  isValid: false,
  value: "",
});
const newCodeStatus = ref({
  isValid: false,
  value: "",
});
const random_token = ref("");

const getDisableStatus = computed(() => {
  if (currentStep.value === eStep.emailInput) {
    return !emailStatus.value.isValid;
  } else if (currentStep.value === eStep.oldEmailVerifyInput) {
    return !oldCodeStatus.value.isValid;
  } else if (currentStep.value === eStep.newEmailVerifyInput) {
    return !newCodeStatus.value.isValid;
  }
});

const handleClickConfirm = async () => {
  if (currentStep.value === eStep.emailInput) {
    currentStep.value = eStep.oldEmailVerifyInput;
  } else if (currentStep.value === eStep.oldEmailVerifyInput) {
    const res = await checkEmail({
      code: oldCodeStatus.value.value,
      code_type: globalState.userInfos.email !== "" ? 1 : 0,
      email: globalState.userInfos.email,
      phone: globalState.userInfos.phone,
    });
    if (res?.code === 200) {
      random_token.value = res.data.random_token;
      currentStep.value = eStep.newEmailVerifyInput;
    } else {
      oldCodeRef.value?.setError(res?.msg!);
    }
  } else if (currentStep.value === eStep.newEmailVerifyInput) {
    const res = await editEmail({
      code: newCodeStatus.value.value,
      new_email: emailStatus.value.value,
      random_token: random_token.value,
    });
    if (res?.code === 200) {
      emit("update:visible", false);
      emit("update");
      ElMessage.success("修改成功");
    } else {
      newCodeRef.value?.setError(res?.msg!);
    }
  }
};

const getTitle = () => {
  if (currentStep.value === eStep.emailInput) {
    if (mode.value === "set") {
      return "绑定邮箱";
    } else {
      return "修改邮箱";
    }
  } else if (currentStep.value === eStep.oldEmailVerifyInput) {
    return "输入验证码";
  } else if (currentStep.value === eStep.newEmailVerifyInput) {
    return "输入验证码";
  }
};
</script>

<style></style>
