<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useUserStoreHook } from "/@/store/modules/user";
import dayjs from "dayjs";

const visible = ref(false);

const systemInfo = computed(() => useUserStoreHook().systemInfo);

const UPDATE_KEY = "update";

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 }
);

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

<template>
  <ElDialog
    v-model="visible"
    title="系统公告"
    center
    width="700px"
    :close-on-click-modal="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)"
      />
    </ElRow>
  </ElDialog>
</template>
