export default {
  data() {
    return {
      selectedQuarters: [],
      quarters: this.generateQuarters(),
      showAlert: true,
    };
  },
  computed: {
    selectedDateRange() {
      if (this.selectedQuarters.length) {
        const sortedQuarters = [...this.selectedQuarters].sort();
        const startDate = this.quarterToDateRange(sortedQuarters[0]).split(" ~ ")[0];
        const endDate = this.quarterToDateRange(sortedQuarters[this.selectedQuarters.length - 1]).split(" ~ ")[1];
        return `${startDate} ~ ${endDate}`;
      }
      return "";
    },
  },
  methods: {
    generateQuarters() {
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      let currentQuarter = Math.floor(currentDate.getMonth() / 3) + 1;

      let quarters = [];

      for (let i = 3; i >= 0; i--) {
        // 包括当前季度和前三个季度
        let year = currentYear;
        let quarter = currentQuarter - i;

        while (quarter <= 0) {
          year--; // 上一年
          quarter += 4; // 季度数增加
        }

        quarters.push({
          label: `${year}Q${quarter}`,
          value: `${year}Q${quarter}`,
        });
      }

      return quarters;
    },

    isDisabled(quarter) {
      if (this.selectedQuarters.length === 0) return false;
      const sortedSelected = [...this.selectedQuarters].sort();
      const firstIndex = this.quarters.findIndex((q) => q.value === sortedSelected[0]);
      const lastIndex = this.quarters.findIndex((q) => q.value === sortedSelected[sortedSelected.length - 1]);

      const currentIndex = this.quarters.findIndex((q) => q.value === quarter.value);

      return currentIndex < firstIndex - 1 || currentIndex > lastIndex + 1;
    },

    quarterToDateRange(quarterLabel) {
      const [year, q] = quarterLabel.split("Q");

      switch (parseInt(q)) {
        case 1:
          return `${year}-01-01 ~ ${year}-03-31`;
        case 2:
          return `${year}-04-01 ~ ${year}-06-30`;
        case 3:
          return `${year}-07-01 ~ ${year}-09-30`;
        case 4:
          return `${year}-10-01 ~ ${year}-12-31`;
      }
    },
    isConsecutiveSelection() {
      const sortedSelectedIndexes = this.selectedQuarters.map((sq) => this.quarters.findIndex((aq) => aq.value === sq)).sort((a, b) => a - b);
      for (let i = 0; i < sortedSelectedIndexes.length - 1; i++) {
        if (sortedSelectedIndexes[i + 1] - sortedSelectedIndexes[i] !== 1) {
          return false;
        }
      }

      return true;
    },
  },

  watch: {
    selectedQuarters(newValue, oldValue) {
      if (!newValue.length) return;
      if (!this.isConsecutiveSelection() && this.showAlert && this.isXClassCustom) {
        this.showAlert = false;
        this.selectedQuarters.pop();
        this.$message.error("只能选择相邻的季度");
        this.$nextTick(() => {
          this.selectedQuarters.pop();
          this.showAlert = true;
        });
      }
    },
  },
};
