<script lang="ts" setup>
import { computed, inject, provide, Ref, ref, onMounted, watch } from 'vue';
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
import emitter from '/@/utils/emitter';
import DateRangePicker from '/src/components/DateRangePicker/index.vue';

dayjs.extend(isoWeek);
import enLocale from 'element-plus/es/locale/lang/en';
import { storeToRefs } from 'pinia';
import { usePublicData } from '/src/stores/publicData';

const dateType = inject<Ref>('dateDimension');

//公共数据
//const publicData = usePublicData();
//const {dateRange} = storeToRefs(publicData);

const dateRange = ref( [
  dayjs().subtract(6, 'day').startOf('day').format('YYYY-MM-DD'),
  dayjs().subtract(1, 'day').endOf('day').format('YYYY-MM-DD')
]);

const startWeek = ref(null);
const endWeek = ref(null);
const weekStartDate = ref<string | null>(dayjs().locale('en').subtract(2, 'week').startOf('week').format('YYYY-MM-DD'));
const wEndDate = ref<string | null>(dayjs().locale('en').subtract(2, 'week').endOf('week').format('YYYY-MM-DD'));
const wStartDate = ref<string | null>(dayjs().locale('en').subtract(1, 'week').startOf('week').format('YYYY-MM-DD'));
const weekEndDate = ref<string | null>(dayjs().locale('en').subtract(1, 'week').endOf('week').format('YYYY-MM-DD'));
const sFormat = computed(() => `${ weekStartDate.value } to ${ wEndDate.value }`);
const wFormat = computed(() => `${ wStartDate.value } to ${ weekEndDate.value }`);

const currentYear = new Date().getFullYear();
const currentMonth = new Date().getMonth();
const monthlyDataTime = ref([
  new Date(currentYear, 0, 1),
  new Date(new Date().getFullYear(), currentMonth, 0),
]);

const startDate = ref(null);
const endDate = ref(null);

const emit = defineEmits(['dateChange']);
const dateChange = async () => {
  if (dateType.value === 'day') {
    emit('dateChange', {
      dailyStartDate: dateRange.value[0],
      dailyTime: dateRange.value[1],
    });
  } else if (dateType.value === 'week') {
    emit('dateChange', {
      weekStartDate: weekStartDate.value,
      weekEndDate: weekEndDate.value,
    });
  } else if (dateType.value === 'month') {
    emit('dateChange', {
      startDate,
      endDate,
    });
  }
};

const monthShortCuts = [
  {
    text: '本月',
    value: [new Date(), new Date()],
  },
  {
    text: '今年',
    value: () => {
      const end = new Date();
      const start = new Date(new Date().getFullYear(), 0);
      return [start, end];
    },
  },
  {
    text: '上六个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 6);
      return [start, end];
    },
  },
];

// 处理开始周变化的函数
const handleStartWeekChange = (value) => {
  if (value) {
    weekStartDate.value = dayjs(value).locale('en').startOf('week').format('YYYY-MM-DD');
    wEndDate.value = dayjs(value).locale('en').endOf('week').format('YYYY-MM-DD');
  }
  checkAndEmitDateChange();
};

const handleEndWeekChange = (value) => {
  if (value) {
    wStartDate.value = dayjs(value).locale('en').startOf('week').format('YYYY-MM-DD');
    weekEndDate.value = dayjs(value).locale('en').endOf('week').format('YYYY-MM-DD');
  }
  checkAndEmitDateChange();
};

const checkAndEmitDateChange = () => {
  if (startWeek.value && endWeek.value) {
    dateChange();
  }
};

const handleMonthChange = (value) => {
  if (value) {
    if (monthlyDataTime.value[0]) {
      const start = new Date(monthlyDataTime.value[0]);
      const year = start.getFullYear();
      const month = start.getMonth();
      startDate.value = `${year}-${String(month + 1).padStart(2, '0')}-01`;
      if (monthlyDataTime.value[1]) {
        const end = new Date(monthlyDataTime.value[1]);
        const year = end.getFullYear();
        const month = end.getMonth() + 1;
        const lastDay = new Date(year, month, 0).getDate();
        endDate.value = `${year}-${String(month).padStart(2, '0')}-${lastDay}`;
      }
      dateChange();
    }
  }
};

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};

const weekDisabledDate = (time: Date) => {
  if (startWeek.value) {
    const startDate = dayjs(startWeek.value).toDate();
    const currentDate = new Date();
    // 禁用结束日期不是在当前日期之前或不是在开始日期之后的日期
    return time.getTime() >= currentDate.getTime() || time.getTime() <= startDate.getTime();
  }
  return time.getTime() >= new Date().getTime();
};

function setDefaultDate() {
  switch (dateType.value) {
    case 'day':
      dateRange.value = [
        dayjs().subtract(6, 'day').startOf('day').format('YYYY-MM-DD'),
        dayjs().subtract(1, 'day').endOf('day').format('YYYY-MM-DD')
      ];
      dateChange();
      break;
    case 'week':
      startWeek.value = dayjs().locale('en').subtract(2, 'week').startOf('week').format('YYYY-MM-DD');
      endWeek.value = dayjs().locale('en').subtract(1, 'week').endOf('week').format('YYYY-MM-DD');
      dateChange();
      break;
    case 'month':
      const startOfMonth = new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1);
      const endOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 0); // 设置下个月的第一天减去1天，得到当前月的最后一天
      monthlyDataTime.value = [startOfMonth, endOfMonth];
      const formattedStartDate = dayjs(startOfMonth).format('YYYY-MM-DD');
      const formattedEndDate = dayjs(endOfMonth).format('YYYY-MM-DD');
      startDate.value = formattedStartDate;
      endDate.value = formattedEndDate;
      dateChange();
      break;
  }
}

onMounted(() => {
  setDefaultDate();
});

watch(dateType, () => {
  setDefaultDate();
});
</script>

<template>
  <div>
    <div v-if="dateType === 'day'" class="demo-date-picker">
      <div class="block">
        <span class="demonstration">日数据时间:</span>
        <DateRangePicker v-model="dateRange" class="date-picker" @change="dateChange"></DateRangePicker>
      </div>
    </div>
    <div v-if="dateType === 'week'" class="demo-date-picker">
      <div class="week-block">
        <span class="demonstration">周数据时间:</span>
        <el-config-provider :locale="enLocale">
          <el-date-picker
              v-model="startWeek"
              :clearable="false"
              :disabled-date="disabledDate"
              class="date-picker"
              :format="sFormat"
              placeholder="选择开始周"
              type="week"
              @change="handleStartWeekChange"
              style="width: 210px"
          />
        </el-config-provider>
        <span class="demonstration">至</span>
        <el-config-provider :locale="enLocale">
          <el-date-picker
              v-model="endWeek"
              :clearable="false"
              :disabled="!startWeek"
              :disabled-date="weekDisabledDate"
              class="date-picker"
              :format="wFormat"
              placeholder="选择结束周"
              type="week"
              @change="handleEndWeekChange"
              style="width: 210px"
          />
        </el-config-provider>
      </div>
    </div>
    <div v-if="dateType === 'month'" class="demo-date-picker">
      <div class="block">
        <span class="demonstration">月数据时间:</span>
        <el-date-picker
            v-model="monthlyDataTime"
            :clearable="false"
            :disabled-date="disabledDate"
            :shortcuts="monthShortCuts"
            end-placeholder="结束月"
            range-separator="To"
            start-placeholder="开始月"
            type="monthrange"
            unlink-panels
            @change="handleMonthChange"
            class="date-picker"
            :popper-options="{
              modifiers: [
                  {
                      name: 'flip',
                      options: {
                          fallbackPlacements: ['bottom'],
                          allowedAutoPlacements: ['bottom'],
                      }
                  }
              ]
  }"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.demo-date-picker {
  display: flex;
  align-items: center;
  padding: 0;
  overflow: hidden;
  width: 100%;
}

.block,
.week-block {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  overflow: hidden;
  width: 100%;
}

.week-block .demonstration {
  margin-right: 8px;
}

.demonstration {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin: 8px;
  white-space: nowrap;
}

.date-picker {
  flex-grow: 1;
  min-width: 0;
}
</style>