<template>
  <div class="date-selector">
    <nav class="time-tabs">
      <button v-for="tab in tabs" :key="tab.id" class="tab-item" :class="{ active: timeType === tab.id }"
        @click="timeChange(tab.id)">
        {{ $t(`dateSelectList.${tab.labelKey}`) }}
        <span v-if="tab.id === '4'" class="dropdown-indicator"></span>
      </button>
    </nav>

    <!-- 日期选择器 -->
    <van-calendar color="var(--primary-color)" v-model:show="calendarShow" type="range" :max-range="366"
      :show-confirm="false" :allow-same-day="true" :min-date="minDate" :max-date="maxDate" @confirm="calendarConfirm" />

    <!-- 类型选择弹出层 -->
    <van-popup v-model:show="timeTypeShow" position="bottom">
      <van-picker :title="$t('dateSelectList.timeType')" :columns="timeTypeList" @confirm="timeTypeConfirm"
        @cancel="timeTypeCancel" />
    </van-popup>
    <!-- 按月统计 -->
    <van-calendar color="#2c87c8" v-model:show="monthDateShow" type="range" :max-range="366" :show-confirm="false"
      :allow-same-day="true" :min-date="minDate" :max-date="maxDate" @confirm="monthDateConfirm" />
  </div>
</template>

<script>
import { ref } from "vue";
import dateUtil from "../../utils/dateUtil";
import { getLoginUser } from "@/common/js/utils";
// import { showToast } from "vant";
import { useI18n } from 'vue-i18n';


export default {
  name: "dateSelectList",
  components: {},
  setup(props, { emit }) {
    // 加载样式
    const tabs = [
      { id: '0', labelKey: 'today' },
      { id: '1', labelKey: 'yesterday' },
      { id: '2', labelKey: 'thisWeek' },
      { id: '3', labelKey: 'thisMonth' },
      { id: '4', labelKey: 'other' }
    ]
    const { t } = useI18n();
    const minDate = new Date(2022, 0, 1);
    const maxDate = new Date();
    const user = getLoginUser();
    // 时间类型
    const timeType = ref("0");
    // 统计类型
    const chartType = ref("0");
    // 时间类型切换
    const timeChange = (data) => {
      timeType.value = data;
      // 当时时间类型切换为其他时间弹出日期控件
      (data === "4") ? timeTypeShow.value = true : outputDate();
    };
    let calendarDate = [];
    const calendarShow = ref(false);
    // 其他时间日期组件确认返回
    const calendarConfirm = (data) => {
      calendarShow.value = false;
      calendarDate = data;
      outputDate();
    };
    const outputDate = async () => {
      const params = {};
      // 今日
      if (timeType.value === "0") {
        params.chartType = "day";
        params.startDate = dateUtil.formateDate(
          new Date(new Date(new Date().getTime()).setHours(0, 0, 0, 0)),
          "yyyy-MM-dd hh:mm:ss"
        );
        params.endDate = dateUtil.formateDate(
          new Date(new Date(new Date().getTime()).setHours(23, 59, 59, 59)),
          "yyyy-MM-dd hh:mm:ss"
        );
      }
      // 昨日
      if (timeType.value === "1") {
        let yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        params.chartType = "day";
        params.startDate = dateUtil.formateDate(
          new Date(new Date(yesterday.getTime()).setHours(0, 0, 0, 0)),
          "yyyy-MM-dd hh:mm:ss"
        );
        params.endDate = dateUtil.formateDate(
          new Date(new Date(yesterday.getTime()).setHours(23, 59, 59, 59)),
          "yyyy-MM-dd hh:mm:ss"
        );
      }
      // 本周
      if (timeType.value === "2") {
        const curr = new Date();
        const dayOfWeek = curr.getDay();
        // 如果是周日，将当前日期设置到本周的周一
        if (dayOfWeek === 0 && user.ifForeign != '1') {
          curr.setDate(curr.getDate() - 6); // 将当前日期设置为本周的周一
        }
        const firstday = new Date(
          curr.setDate(curr.getDate() - curr.getDay() + 1)
        );
        const lastday = new Date(
          curr.setDate(curr.getDate() - curr.getDay() + 7)
        );
        params.chartType = "week";
        params.startDate =
          dateUtil.formateDate(firstday, "yyyy-MM-dd") + " 00:00:00";
        params.endDate =
          dateUtil.formateDate(lastday, "yyyy-MM-dd") + " 23:59:59";
      }
      // 本月
      if (timeType.value === "3") {
        const now = new Date(); //当前日期
        const nowMonth = now.getMonth(); //当前月
        const nowYear = now.getFullYear(); //当前年
        params.chartType = "month";
        params.startDate =
          dateUtil.formateDate(new Date(nowYear, nowMonth, 1), "yyyy-MM-dd") +
          " 00:00:00";
        params.endDate =
          dateUtil.formateDate(
            new Date(nowYear, nowMonth + 1, 0),
            "yyyy-MM-dd"
          ) + " 23:59:59";
      }
      // 其他时间
      if (timeType.value === "4") {
        let startTime = null;
        let endTime = null;
        if (chartType.value == '1') {
          // 按日统计
          const firstday = Date.parse(calendarDate[0]);
          const lastday = Date.parse(calendarDate[1]);
          const diffDate = Math.abs(firstday - lastday);
          const totalDays = Math.floor(diffDate / (1000 * 3600 * 24));
          if (totalDays === 0) {
            params.chartType = "day";
          } else {
            params.chartType = "month";
          }
          timeTypeShow.value = false;
          startTime = calendarDate[0];
          endTime = calendarDate[1];
          params.startDate =
            dateUtil.formateDate(startTime, "yyyy-MM-dd") + " 00:00:00";
          params.endDate =
            dateUtil.formateDate(endTime, "yyyy-MM-dd") + " 23:59:59";
        } else {
          // 按月统计
          params.chartType = "year";
          startTime = calendarDate[0];
          endTime = calendarDate[1];
          params.startDate =
            dateUtil.formateDate(startTime, "yyyy-MM-dd") + " 00:00:00";
          params.endDate =
            dateUtil.formateDate(endTime, "yyyy-MM-dd") + " 23:59:59";
          timeTypeShow.value = false;
        }
      }
      emit('update', params);
    };
    // 统计类型
    const timeTypeShow = ref(false);
    const timeTypeList = [
      { text: t('dateSelectList.dayType'), value: "1" },
      { text: t('dateSelectList.monthType'), value: "2" },
    ];
    const timeTypeConfirm = ({ selectedOptions }) => {
      // 按日统计
      chartType.value = selectedOptions[0].value;
      if (selectedOptions[0].value == '1') {
        calendarShow.value = true;
      } else {
        monthDateShow.value = true;
      }

    }
    const timeTypeCancel = () => { timeTypeShow.value = false; }
    // 按月统计
    // 创建一个Date对象，表示当前时间
    const currentDate = new Date();
    // 获取当前时间的年份
    const currentYear = currentDate.getFullYear();
    // 获取当前时间的月份（注意，月份是从0开始的，所以要加1）
    const currentMonth = currentDate.getMonth() + 1;
    const monthDateShow = ref(false);
    const monthDate = ref([currentYear, currentMonth]);
    const monthDateType = ['year', 'month'];
    const monthDateConfirm = (data) => {
      monthDateShow.value = false;
      calendarDate = data;
      outputDate();
    }
    const monthDateCancel = () => { monthDateShow.value = false; }
    return {
      minDate,
      maxDate,
      timeType,
      timeChange,
      calendarShow,
      calendarConfirm,
      timeTypeShow,
      timeTypeList,
      timeTypeConfirm,
      timeTypeCancel,
      monthDateShow,
      monthDateType,
      monthDateConfirm,
      monthDateCancel,
      monthDate,
      tabs,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common";
.date-selector {
  --primary-color: #2c87c8;
  --border-color: #b9bad0;
  --text-primary: #404d74;
  --bg-active: var(--primary-color);
  --tab-height: 38px;

  padding: 0 10px;
  margin: 0 auto;

  .time-tabs {
    display: flex;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .tab-item {
      flex: 1;
      position: relative;
      height: var(--tab-height);
      padding: 0 12px;
      border: none;
      background: transparent;
      color: var(--text-primary);
      font-size: 13px;
      white-space: nowrap;
      cursor: pointer;
      transition: all 0.2s ease;

      &:last-child {
        border-right: none;
      }

      &:hover {
        background-color: rgba(77, 106, 221, 0.1);
      }

      &.active {
        background: var(--bg-active);
        color: #fff;
        font-weight: 500;

        .dropdown-indicator {
          border-top-color: #fff;
        }
      }

      .dropdown-indicator {
        display: inline-block;
        margin-left: 4px;
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-top: 4px solid var(--text-primary);
        transition: border-color 0.2s;
      }
    }
  }

  // 适配移动端
  @media (max-width: 480px) {
    .time-tabs {
      .tab-item {
        font-size: 12px;
        padding: 0 5px;
      }
    }
  }
}
</style>