import { computed, ref } from "vue";
import { createGlobalState, useStorage } from "@vueuse/core";
import {
  competitionApply,
  competitionWorks,
  GToken,
  loginRegister,
  sendCode,
  uploadFile,
  voteAPI,
  workInfo,
} from "@/api/auth/index.js";
import { message } from "@/utils/message.js";
import { useRouter } from "vue-router";
import { showImagePreview } from "vant";

export const useAuth = createGlobalState(() => {
  console.log("useRouter", useRouter);
  const router = useRouter();
  const token = useStorage("token", "", localStorage);
  const workUid = useStorage("workUid", "", localStorage);
  const telNum = useStorage("telNum", "", localStorage);
  const code = ref("");
  const voteToken = useStorage(
    "voteToken",
    {
      authorization: "",
      expireTime: "",
    },
    localStorage
  );
  const workData = useStorage("workData", {}, localStorage);
  const countdown = ref(0);
  const isCountingDown = ref(false);
  const showTextCode = computed(() => {
    return isCountingDown.value ? `${countdown.value}s` : "获取验证码";
  });
  const resultType = useStorage("resultType", "", localStorage);

  const getVoteToken = async () => {
    const res = await GToken();
    if (res.status === 0) {
      const currentTimestamp = Date.now();
      const millisecondsIn48Hours = 48 * 60 * 60 * 1000;
      voteToken.value.expireTime = currentTimestamp + millisecondsIn48Hours;
      voteToken.value.authorization = res.data?.authorization;
      console.log("voteToken", voteToken.value);
    }
  };
  const sendVote = async () => {
    const res = await voteAPI({ workUid: workUid.value });
    if (res.status === 0) {
      message.success("投票成功");
      router.push({
        path: "/result",
        query: {
          type: "hasVoted",
        },
      });
    }
  };
  const isWechat = () => {
    const os = window.navigator.userAgent.toLowerCase();
    if (os.match(/micromessenger/i) == "micromessenger") {
      return true;
    } else {
      return false;
    }
  };
  const getWorkInfo = async () => {
    const res = await workInfo({ workUid: workUid.value });
    if (res.status === 0) {
      workData.value = res.data;
    }
  };
  const showText = computed(() => {
    if (["success"].includes(resultType.value)) {
      return "提交成功";
    } else if (["end"].includes(resultType.value)) {
      return "报名已结束";
    } else if (["hasVoted"].includes(resultType.value)) {
      return "您已投过票";
    }
  });
  const genderOptions = ref([
    { text: "男", value: "男" },
    { text: "女", value: "女" },
  ]);
  // 验证 formData 中的字段
  function validateFormData() {
    // 验证基本信息
    const baseFields = ["name", "age", "gender"];
    if (baseFields.some((field) => !Boolean(formData.value[field]))) {
      return false;
    }
    // 验证 works 数组中的每一个作品
    if (
      formData.value.works.some(
        (work) =>
          !Boolean(work.picUrl) ||
          !Boolean(work.workName) ||
          !Boolean(work.length) ||
          !Boolean(work.wide)
      )
    ) {
      return false;
    }
    return true;
  }

  const openMask = (src) => {
    showImagePreview({
      images: [src],
      closeable: true,
    });
  };
  const goBack = () => {
    router.back();
  };
  const detailData = useStorage("detailData", {}, localStorage);
  const formData = useStorage(
    "formData",
    {
      name: "",
      age: "",
      gender: undefined,
      works: [
        {
          imgList: [],
          picUrl: "", //作品图片url
          workName: "", //作品名称
          length: undefined, //长度
          wide: undefined, //宽度
        },
      ],
    },
    localStorage
  );
  const clickAddWorks = () => {
    if (formData.value.works?.length >= 5) {
      message.warning("最多上传5个作品");
      return;
    }
    formData.value.works.push({
      picUrl: "", //作品图片url
      workName: "", //作品名称
      length: undefined, //长度
      wide: undefined, //宽度
    });
  };
  const removeWorks = (index) => {
    formData.value.works.splice(index, 1);
  };
  const afterRead = async (file, item, e) => {
    const formData1 = new FormData();
    formData1.append("file", file.file);
    formData1.append("type", "image");
    const res = await uploadFile(formData1);
    if (res.status === 0) {
      item.picUrl = res.data;
      if (e.onFinish) {
        e.onFinish();
        item.imgList = [
          {
            status: "finished",
            url: item.picUrl,
          },
        ];
      }
    }
  };
  const deleteImg = (item) => {
    item.picUrl = "";
    item.imgList = [];
  };
  const viewDetails = async () => {
    await getDetail();
    router.push({
      path: "/details",
    });
  };
  const clickApply = async () => {
    const isValid = validateFormData();
    if (!isValid) {
      message.warning("作品信息不全，请补充");
      return;
    }
    const data = {
      ...formData.value,
    };
    const res = await competitionApply(data);
    if (res.status === 0) {
      message.success("报名成功");
      router.push({
        path: "/result",
        query: {
          type: "success",
        },
      });
    }
  };
  let timer = null;
  const getDetail = async () => {
    if (!telNum.value) {
      message.error("获取手机号失败");
      return;
    }
    const res = await competitionWorks({ telNum: telNum.value });
    if (res.status === 0) {
      detailData.value = res.data;
    }
  };
  const goConfirm = () => {
    const isValid = validateFormData();
    if (!isValid) {
      message.warning("作品信息不全，请补充");
      return;
    }
    router.push("/confirm");
  };
  const clickLogin = async () => {
    const data = {
      telNum: telNum.value,
      code: code.value,
    };
    const res = await loginRegister(data);
    if (res.status === 0) {
      token.value = res.data.token;
      if (res.data.status === 1) {
        message.warning("您已经报名");
        await getDetail();
        router.push({
          path: "/details",
        });
      } else {
        message.success("登录成功");
        router.push({
          path: "/signup",
        });
      }
    }
  };
  const clickSendCode = async () => {
    if (isCountingDown.value) return;
    if (!telNum.value) {
      message.warning("请输入手机号");
      return;
    }
    const data = {
      telNum: telNum.value,
    };
    const res = await sendCode(data);
    if (res.status === 0) {
      countdown.value = 60;
      isCountingDown.value = true;
      message.success("发送成功");
      timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value -= 1;
        } else {
          clearInterval(timer);
          isCountingDown.value = false;
        }
      }, 1000);
    }
  };

  const beforeUploadImage = (e) => {
    if (
      e.file.file?.type !== "image/png" &&
      e.file.file?.type !== "image/jpeg" &&
      e.file.file?.type !== "image/jpg" &&
      e.file.file?.type !== "image/gif" &&
      e.file.file?.type !== "image/bmp"
    ) {
      message.warning("请上传图片文件");
      return false;
    }
  };
  return {
    voteToken,
    isWechat,
    getVoteToken,
    beforeUploadImage,
    showText,
    resultType,
    sendVote,
    workData,
    workUid,
    getWorkInfo,
    viewDetails,
    goBack,

    deleteImg,
    afterRead,
    openMask,
    goConfirm,
    detailData,
    removeWorks,
    clickAddWorks,
    genderOptions,
    formData,
    clickApply,
    clickLogin,
    showTextCode,
    code,
    clickSendCode,
    telNum,
    token,
  };
});
