<script lang="ts" setup>
import dayjs from "dayjs";
import { onUpdated, watch } from "vue";
import { onMounted, ref } from "vue";
import { useConfig } from "@/store/modules/asideConfig";
import { useFinal } from '@/store/modules/final'

const configUseStore = useConfig();

configUseStore.$subscribe(() => {
  if (isLoadValue.value) {
    isLoadValue.value = false;
    return;
  }
  let asideValue = configUseStore.getAsideValue;
  if (asideValue["izyear"]) {
    time.value = asideValue["izyear"];
  } else {
    time.value = null;
  }
});

const finalStore = useFinal()
finalStore.$subscribe(() => {
  if (isLoadValue.value) {
    isLoadValue.value = false;
    return;
  }
  let asideValue = finalStore.getAsideValue;
  console.log("asideValue izyear", asideValue);
  if (asideValue && asideValue["izyear"]) {
    time.value = asideValue["izyear"];
  } else {
    time.value = null;
  }
});


const props = defineProps<{
  value: [number, number] | null;
  label: string;
}>();

const emit = defineEmits<{
  (e: "update:value", value: number[]): void;
}>();

const time = ref<[number, number] | null>(props.value);
const isLoadValue = ref(false);
function onChange(value: [number, number]) {
  isLoadValue.value = true;
  emit("update:value", value);
}
onMounted(() => {
  if (!props.value) {
    // 获取当前日期
    const currentDate = dayjs();
    // 计算前三个月的起始日期和结束日期
    const endDate = currentDate.toDate();
    const startDate = currentDate.subtract(3, "month").toDate();
    // 设置默认日期范围为前三个月的起始日期到三个月前的今天
    time.value = [startDate.getTime(), endDate.getTime()];
    console.log("time init", startDate.getTime(), endDate.getTime());
    setTimeout(() => {
      emit("update:value", [startDate.getTime(), endDate.getTime()]);
    }, 300);
  }
});
</script>

<template>
  <div class="wrapper">
    <n-collapse :default-expanded-names="['1']" arrow-placement="right">
      <n-collapse-item :title="label" name="1">
        <n-space>
          <n-date-picker
            v-model:value="time"
            type="daterange"
            :clearable="false"
            @update:value="onChange"
            placeholder="请选择"
          >
            <template #separator> 至 </template>
          </n-date-picker>
        </n-space>
      </n-collapse-item>
    </n-collapse>
  </div>
</template>

<style lang="less" scoped>
.wrapper {
  padding: 10px;
}

::v-deep(.n-collapse-item-arrow) {
  color: #999999 !important;
}

::v-deep(.n-input__separator) {
  color: #999999 !important;
}
::v-deep(.n-collapse
    .n-collapse-item:not(.n-collapse-item--disabled).n-collapse-item--trigger-area-main
    .n-collapse-item__header
    .n-collapse-item__header-main) {
  margin-left: 10px;
}
::v-deep(.n-collapse
    .n-collapse-item:not(.n-collapse-item--disabled).n-collapse-item--trigger-area-main
    .n-collapse-item__header
    .n-collapse-item__header-main::before) {
  content: "*";
  position: absolute;
  left: 0;
  top: 2px;
  color: red;
}
</style>
