<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { httpSystemList } from "/@/api/user";
import { setSystemVer } from "/@/api/user2";
import { useUserStoreHook } from "/@/store/modules/user";
import { resType } from "/@/store/modules/types";
import dayjs from "dayjs";
const { updateUserVersion } = useUserStoreHook();
const visible = ref(false);
const num = ref(0);
const timer = ref(null);
const id_arr = ["58", "78", "125"];
const user_info = ref(null);
const versionList = ref([]);
const systemInfo = ref({});
const hasSet = ref(true);

async function requsetSystemInfo() {
  versionList.value = useUserStoreHook().system_version;
  user_info.value = useUserStoreHook().info;
  const { data, code } = await httpSystemList({ page: 1, size: 2 });
  if (Number(code) === 0) {
    const { list } = data;
    if (list.length === 1) {
      systemInfo.value = list[0];
    } else if (list.length === 2) {
      if (
        list[0].sys_type === "VER" &&
        new Date(list[0].addtime).valueOf() > new Date().valueOf()
      ) {
        systemInfo.value = list[1];
      } else {
        systemInfo.value = list[0];
      }
    }
    if (list.length === 0) {
      hasSet.value = false;
    } else {
      const index = versionList.value.findIndex(
        si => si === systemInfo.value.version
      );
      hasSet.value = index === -1;
    }
  } else {
    throw new Error();
  }
}
onMounted(async () => {
  await requsetSystemInfo();
  const { sys_type } = systemInfo.value;
  if (sys_type === "MSG") return systemMsg();
  if (sys_type === "VER") return systemVer();
});

const UPDATE_KEY = "update";

async function dialogClose() {
  if (num.value !== 0) {
    return;
  }
  if (hasSet.value) {
    const { version } = systemInfo.value;
    const { id } = useUserStoreHook().info;
    setSystemVer({
      account_id: id,
      plat_code: "st",
      system_version: version
    }).then(async (res: resType) => {
      const { code, message, data } = res;
      if (code === 0) {
        updateUserVersion();
      }
    });
  }
  visible.value = false;
}
function setUpdateCache(updateTime: string) {
  let _update = localStorage.getItem(UPDATE_KEY);
  const update: any = JSON.parse(_update || "[]");
  if (update.includes(updateTime)) return;
  update.push(updateTime);
  localStorage.setItem(UPDATE_KEY, JSON.stringify(update));
}

function isCacheUpdate(updateTime) {
  let _update: any = localStorage.getItem(UPDATE_KEY);
  const update: any = JSON.parse(_update || "[]");
  return update.includes(updateTime);
}

function systemVer() {
  const { addtime } = systemInfo.value;
  if (isCacheUpdate(addtime)) return;
  const updateTime = dayjs(addtime).format("YYYY-MM-DD");
  const diff = dayjs(new Date()).diff(updateTime, "day");
  //小于七天的提示示更新
  if (diff < 7 && !(diff < 0)) {
    visible.value = true;
  }
}

function systemMsg() {
  const { addtime } = systemInfo.value;
  if (isCacheUpdate(addtime)) return;
  const updateTime = dayjs(addtime).format("YYYY-MM-DD");
  const diff = dayjs(new Date()).diff(updateTime, "day");
  //前七天开始提醒更新
  if (diff > -7 && !(diff > 0)) {
    visible.value = true;
  }
}

// watch(
//   () => systemInfo.value,
//   ({ sys_type }) => {
//     if (sys_type === "MSG") return systemMsg();
//     if (sys_type === "VER") return systemVer();
//   },
//   { immediate: true }
// );
watch(
  () => visible.value,
  async () => {
    if (visible.value === true) {
      await requsetSystemInfo();
      const { id } = user_info.value;
      const index = id_arr.findIndex(e => e === id + "");
      console.log(index);
      if (hasSet.value) {
        num.value = 10;
        timer.value = setInterval(() => {
          if (num.value > 0) {
            num.value--;
          } else {
            if (timer.value) {
              clearInterval(timer.value);
            }
          }
        }, 1000);
      }
      console.log(systemInfo.value);
    }
  },
  { immediate: true }
);

defineExpose({
  onDisplay: () => {
    visible.value = true;
  }
});
</script>

<template>
  <ElDialog
    v-model="visible"
    title="系统公告"
    center
    width="700px"
    :before-close="dialogClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <ElAlert type="success" center :closable="false">
      <h1 class="font-bold text-center w-full" style="font-size: 16px">
        {{ systemInfo.module }}
      </h1>
    </ElAlert>

    <div class="my-[20px] p-[10px]">
      <ElRow>
        <ElCol :span="12" style="display: flex">
          <p class="font-bold mr-5 mb-5">版本编码:</p>
          <p>{{ systemInfo.version }}</p>
        </ElCol>
        <ElCol :span="12" style="display: flex">
          <p class="font-bold mr-5">
            {{ systemInfo.sys_type === "VER" ? "更新" : "预计" }}时间:
          </p>
          <p>{{ systemInfo.addtime }}</p>
        </ElCol>
        <ElCol :span="24" style="display: flex">
          <p class="font-bold mr-5">更新内容:</p>
          <p v-html="systemInfo.system" />
        </ElCol>
      </ElRow>
    </div>

    <ElRow>
      <ElCheckbox
        label="我已知晓,后续不再提醒"
        :checked="isCacheUpdate(systemInfo.addtime)"
        @click="() => setUpdateCache(systemInfo.addtime)"
      />
      <div
        style="width: 200px; text-align: right; height: 33px; line-height: 33px"
        v-if="num !== 0"
      >
        {{ num }}秒后，可关闭
      </div>
    </ElRow>
  </ElDialog>
</template>
