<template>
  <section class="wh_container">
    <div class="wh_content_all">
      <!-- 顶部月份切换 -->
      <div class="wh_top_changge">
        <li @click="PreMonth(myDate, false)">
          <div class="wh_jiantou1"></div>上个月
        </li>
        <li class="wh_content_li">{{ dateTop }}</li>
        <li @click="NextMonth(myDate, false)">
          下个月<div class="wh_jiantou2"></div>
        </li>
      </div>

      <!-- 星期标题 -->
      <div class="wh_content">
        <div class="wh_content_item" v-for="tag in textTop" :key="tag">
          <div class="wh_top_tag">{{ tag }}</div>
        </div>
      </div>

      <!-- 日期格子 -->
      <div class="wh_content">
        <div class="wh_content_item" v-for="(item, index) in list" :key="index" @click="clickDay(item, index)">
          <div class="wh_item_date" :class="[
            { wh_other_dayhide: item.otherMonth !== 'nowMonth' },
            { wh_isToday: item.isToday },
            { wh_chose_day: item.chooseDay },
          ]" @click="handleGoToPage('/editPassword', '个人中心')" @contextmenu.prevent="handleGoToRight('右键')">
            {{ item.id }}

            <!-- 标识容器 -->
            <div v-if="item.markClassName" class="point">
              <!-- 未完成：小红点 -->
              <span v-if="item.markClassName === 'calendar-todo'" class="todo-dot"></span>

              <!-- 已完成 / 无任务：SVG ✔ -->
              <svg v-else class="done-svg" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
                <path fill="#fff"
                  d="M7.629 13.314l-3.29-3.29a1 1 0 011.414-1.415l2.29 2.29 5.294-5.293a1 1 0 111.414 1.414l-6.707 6.707a1 1 0 01-1.415 0z" />
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, watch, onMounted, defineExpose } from "vue";
import timeUtil from "./calendar";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
const router = useRouter();
const store = useStore();
const props = defineProps({
  markDateMore: { type: Array, default: () => [] },
  textTop: { type: Array, default: () => ["一", "二", "三", "四", "五", "六", "日"] },
  sundayStart: { type: Boolean, default: () => false },
  agoDayHide: { type: String, default: `0` },
  futureDayHide: { type: String, default: `2554387200` },
});

const emit = defineEmits(["changeMonth", "choseDay"]);

const myDate = ref(new Date());
const list = ref([]);
const dateTop = ref("");
const historyChose = ref([]);

const intStart = () => {
  timeUtil.sundayStart = props.sundayStart;
};

// 点击日期
const clickDay = (item) => {
  if (item.otherMonth === "nowMonth" && !item.dayHide) {
    getList(myDate.value, item.date);
  }
  if (item.otherMonth !== "nowMonth") {
    item.otherMonth === "preMonth" ? PreMonth(item.date) : NextMonth(item.date);
  }
};
// 跳转应用
const handleGoToPage = (_url, _title) => {
  if (_url) {
    store.commit(
      "app/addTagsViewList",
      {
        fullPath: _url,
        meta: {
          meta: {
            title: _title
          }
        },
        name: _url,
        params: {},
        path: _url,
        query: {},
        title: _title
      },
      {
        immediate: true
      }
    );
    router.push(_url)
  }
}
const handleGoToRight = (row) => {
  console.log(row)
}
// 上一月
const PreMonth = (date, isChosedDay = true) => {
  myDate.value = timeUtil.getOtherMonth(myDate.value, "preMonth");
  emit("changeMonth", timeUtil.dateFormat(myDate.value));
  getList(myDate.value, date, isChosedDay);
};

// 下一月
const NextMonth = (date, isChosedDay = true) => {
  myDate.value = timeUtil.getOtherMonth(myDate.value, "nextMonth");
  emit("changeMonth", timeUtil.dateFormat(myDate.value));
  getList(myDate.value, date, isChosedDay);
};

// 核心生成列表逻辑
const getList = (date, chooseDay, isChosedDay = true) => {
  const markDateMore = props.markDateMore.map((k) => ({
    date: timeUtil.dateFormat(k.date),
    className: k.className || "",
  }));

  dateTop.value = `${date.getFullYear()}年${date.getMonth() + 1}月`;
  const arr = timeUtil.getMonthList(myDate.value);

  const todayStr = timeUtil.dateFormat(new Date());
  const todayTime = new Date(todayStr).getTime();

  for (let k of arr) {
    k.chooseDay = false;
    const nowTime = k.date;
    const t = new Date(nowTime).getTime();

    // 默认不显示标识
    k.markClassName = "";

    // 仅当前月 & 当前日期之前（含今天） 才考虑显示标识
    if (k.otherMonth === "nowMonth" && t <= todayTime) {
      const mark = markDateMore.find((m) => m.date === nowTime);
      if (mark) {
        k.markClassName = mark.className; // 有任务标识：done / todo
      } else {
        k.markClassName = "calendar-done"; // 没任务默认打勾
      }
    }

    // 超出时间范围则隐藏
    const seconds = t / 1000;
    k.dayHide = seconds < props.agoDayHide || seconds > props.futureDayHide;

    const flag = !k.dayHide && k.otherMonth === "nowMonth";

    //保留选中逻辑
    if (!chooseDay && todayStr === nowTime && flag) {
      k.chooseDay = true;
      emit("choseDay", todayStr, nowTime);
      historyChose.value.push(nowTime);
    } else if (chooseDay && chooseDay === nowTime && flag) {
      const nowTimeStrin = timeUtil.dateFormatStr(nowTime);
      emit("choseDay", nowTimeStrin, nowTime);
      historyChose.value.push(nowTime);
      k.chooseDay = true;
    } else if (
      historyChose.value[historyChose.value.length - 1] === nowTime &&
      !chooseDay &&
      flag
    ) {
      k.chooseDay = true;
    }
  }

  list.value = arr;
};

// 初始渲染
onMounted(() => {
  intStart();
  getList(myDate.value);
});

watch(() => props.markDateMore, () => getList(myDate.value), { deep: true });
defineExpose({ getList });
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}

.wh_container {
  max-width: 600px;
  margin: auto;
}

.wh_top_changge {
  display: flex;
}

.wh_top_changge li {
  cursor: pointer;
  display: flex;
  font-size: 18px;
  flex: 1;
  justify-content: center;
  align-items: center;
  height: 47px;
}

.wh_top_changge .wh_content_li {
  cursor: auto;
  flex: 2.5;
}

.wh_jiantou1 {
  width: 12px;
  height: 12px;
  border-top: 2px solid #333;
  border-left: 2px solid #333;
  transform: rotate(-45deg);
}

.wh_jiantou1:active,
.wh_jiantou2:active {
  border-color: #333;
}

.wh_jiantou2 {
  width: 12px;
  height: 12px;
  border-top: 2px solid #333;
  border-right: 2px solid #333;
  transform: rotate(45deg);
}

.wh_content_all {
  width: 100%;
  overflow: hidden;
  padding-bottom: 8px;
  color: #000;
  background: #ffffff;
  border-radius: 5px;
}

.wh_content {
  display: flex;
  flex-wrap: wrap;
  padding: 0 3%;
  width: 100%;
}

.wh_content_item {
  font-size: 15px;
  width: 13.4%;
  text-align: center;
  position: relative;
  height: 34px;
}

/* 日期核心 */
.wh_item_date {
  width: 38px;
  height: 38px;
  line-height: 38px;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  transition: all 0.2s ease-in-out;
  position: relative;
}

/* 悬停 */
.wh_item_date:hover {
  background-color: #f0f8f5;
  cursor: pointer;
}

/* 当前选中背景 */
.wh_chose_day {
  background-color: #a4e2a4 !important;
  color: #fff !important;
  font-weight: 600;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
}

/* 今天蓝色 */
.wh_isToday {
  color: #2a8ef7 !important;
  font-weight: 600;
}

/* 非当月灰色 */
.wh_other_dayhide {
  color: #d9d9d9 !important;
}

/* 标识容器 */
.point {
  position: absolute;
  top: 0px;
  right: -8px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 未完成任务红点 */
.todo-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff3b30;
  box-shadow: 0 0 3px #ff3b30;
}

/* 已完成 / 无任务 绿色钩 */
:deep(.done-svg) {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #00C853;
}
</style>
