<template>
  <syCommonDialog
    :visible="visible"
    type="element"
    :elementDialogProps="{
      title: getTitle(),
    }"
    showMask
    @closePopup="$emit('update:visible', false)"
  >
    <div v-if="visible">
      <CollectPhone
        v-if="currentStep === eStep.phoneInput"
        :mode="mode"
        :phone="globalState.userInfos.phone"
        @collect="handlePhoneCollect"
      ></CollectPhone>
      <CollectVerificationCode
        v-if="currentStep === eStep.oldLogWayVerifyInput"
        ref="oldCodeRef"
        :target="globalState.userInfos.phone || globalState.userInfos.email"
        :fn-send-verification-code="
          () => {
            if (globalState.userInfos.phone) {
              return sendSms({
                phone: globalState.userInfos.phone,
                template_id: 3,
              });
            } else {
              return sendEmail({
                email: globalState.userInfos.email,
                template_id: 3,
              });
            }
          }
        "
        @collect="oldCodeStatus = $event"
      ></CollectVerificationCode>
      <CollectVerificationCode
        v-if="currentStep === eStep.newPhoneVerifyInput"
        ref="newCodeRef"
        :target="phoneStatus.value"
        :fn-send-verification-code="
          () => {
            return sendSms({
              phone: phoneStatus.value,
              template_id: 3,
            });
          }
        "
        @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 CollectPhone from "../../../../../components/Form/Collect/CollectPhone.vue";
import { globalState } from "@/store/state";
import {
  checkOldPhone,
  editPhone,
  sendSms,
  sendEmail,
} from "@/service/Api.service";
import { ElMessage } from "element-plus";

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

enum eStep {
  phoneInput,
  /**老的登录方式的校验，如果之前是用邮箱登录，则是邮箱。否则是手机。 */
  oldLogWayVerifyInput,
  newPhoneVerifyInput,
}

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

const currentStep = ref(eStep.phoneInput);
const phoneStatus = 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.phoneInput) {
    return !phoneStatus.value.isValid;
  } else if (currentStep.value === eStep.oldLogWayVerifyInput) {
    return !oldCodeStatus.value.isValid;
  } else if (currentStep.value === eStep.newPhoneVerifyInput) {
    return !newCodeStatus.value.isValid;
  }
});

const handleClickConfirm = async () => {
  if (currentStep.value === eStep.phoneInput) {
    currentStep.value = eStep.oldLogWayVerifyInput;
  } else if (currentStep.value === eStep.oldLogWayVerifyInput) {
    const res = await checkOldPhone({
      code: oldCodeStatus.value.value,
      code_type: globalState.userInfos.phone !== "" ? 0 : 1,
      phone: globalState.userInfos.phone,
      email: globalState.userInfos.email,
    });
    if (res?.code === 200) {
      random_token.value = res.data.random_token;
      currentStep.value = eStep.newPhoneVerifyInput;
    } else {
      oldCodeRef.value?.setError(res?.msg!);
    }
  } else if (currentStep.value === eStep.newPhoneVerifyInput) {
    const res = await editPhone({
      code: newCodeStatus.value.value,
      new_phone: phoneStatus.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.phoneInput) {
    if (mode.value === "set") {
      return "绑定手机";
    } else {
      return "修改手机";
    }
  } else if (currentStep.value === eStep.oldLogWayVerifyInput) {
    return "输入验证码";
  } else if (currentStep.value === eStep.newPhoneVerifyInput) {
    return "输入验证码";
  }
};

const handlePhoneCollect = (data: { value: string; isValid: boolean }) => {
  phoneStatus.value = data;
};
</script>

<style></style>
