<template>
  <div class="wl-date-range" weiling-mobile-ui-wl-date-range>
    <div class="date-select" @click="onOpenSelect('start')">
      <p class="text" :class="start_date ? '' : 'text-default'">
        {{ date_text(start_date, "start") }}
      </p>
      <p
        class="icon-wrap"
        @click.stop="onClear('start')"
        v-if="start_date && clearable"
      >
        <WlSvgIcon
          type="closeCircularLine"
          width="12"
          color="var(--wl-text-color-placeholder)"
        />
      </p>
    </div>
    <p class="space">-</p>
    <div class="date-select" @click="onOpenSelect('end')">
      <p class="text" :class="end_date ? '' : 'text-default'">
        {{ date_text(end_date, "end") }}
      </p>
      <p
        class="icon-wrap"
        @click.stop="onClear('end')"
        v-if="end_date && clearable"
      >
        <WlSvgIcon
          type="closeCircularLine"
          width="12"
          color="var(--wl-text-color-placeholder)"
        />
      </p>
    </div>
    <WlDatePicker
      v-model="dateVisbile"
      color="var(--wl-primary-color)"
      :date-value="dateDefaultVal"
      :min-date="minDate"
      :max-date="maxDate"
      @onConfrim="onSelectDate"
    />
  </div>
</template>

<script lang="ts">
export default {
  name: "WlDateRange",
};
</script>

<script lang="ts" setup>
import WlSvgIcon from "@mobileUI/components/WlSvgIcon/src/index.vue";
import { watchEffect, ref, computed } from "vue";
import { formatMoment } from "@mobileUI/utils/dayjs";
import WlDatePicker from "@mobileUI/components/WlDatePicker/src/index.vue";

type Props = {
  min_date?: number | string;
  max_date?: number | string;
  start_date: number | string;
  end_date: number | string;
  clearable?: boolean;
};
const props = withDefaults(defineProps<Props>(), {
  start_date: "",
  end_date: "",
  min_date: "",
  max_date: "",
  clearable: true,
});
const currentTime = new Date().getTime();
const minDate = computed(() => {
  const t = props.min_date || currentTime - 1000 * 60 * 60 * 24 * 365 * 10;
  return new Date(parseInt(t as string));
});
const maxDate = computed(() => {
  const t = props.max_date || currentTime + 1000 * 60 * 60 * 24 * 365 * 10;
  return new Date(parseInt(t as string));
});

const emit = defineEmits<{
  (e: "update:start_date", val: number | string);
  (e: "update:end_date", val: number | string);
  (
    e: "onSelect",
    val: { start_date: number | string; end_date: number | string },
  );
}>();
const selectd_start_date = ref(""),
  selectd_end_date = ref("");

const dateVisbile = ref(false);
const dateDefaultVal = ref([]);

const date_text = computed(() => {
  return function (date, type) {
    if (type === "start") {
      return formatMoment(parseInt(date || props.min_date), "YYYY-MM-DD");
    } else {
      return formatMoment(parseInt(date || props.max_date), "YYYY-MM-DD");
    }
  };
});

const getResTime = () => {
  return {
    start_date: selectd_start_date.value || minDate.value.getTime(),
    end_date: selectd_end_date.value || maxDate.value.getTime(),
  };
};

const onClear = (type) => {
  let { start_date, end_date } = getResTime();
  if (type === "start") {
    emit("update:start_date", "");
    start_date = minDate.value.getTime();
  } else {
    emit("update:end_date", "");
    end_date = maxDate.value.getTime();
  }
  emit("onSelect", { start_date, end_date });
};
let select_time_type = "";
const onOpenSelect = (type) => {
  select_time_type = type;
  let time: any =
    type === "start" ? getResTime().start_date : getResTime().end_date;
  if (time) {
    time = new Date(parseInt(time));
    dateDefaultVal.value = [
      time.getFullYear() + "",
      `${time.getMonth() + 1 > 9 ? "" : "0"}${time.getMonth() + 1}`,
      time.getDate() + "",
    ];
  } else {
    dateDefaultVal.value = [];
  }
  dateVisbile.value = true;
};

const getStartTime = (timestamp) => {
  const time = new Date(Number(timestamp));
  if (time.getHours() === 0 && time.getMinutes() === 0) {
    return timestamp;
  } else {
    // 开始日期应该包括的是当天的00：00,
    return new Date(
      `${time.getFullYear()}/${time.getMonth() + 1}/${time.getDate()} 00:00:00`,
    ).getTime();
  }
};
const getEndTime = (timestamp) => {
  const time = new Date(Number(timestamp));
  if (time.getHours() === 23 && time.getMinutes() === 59) {
    return timestamp;
  } else {
    // 结束日期应该包括的是当天的23:59,
    return new Date(
      `${time.getFullYear()}/${time.getMonth() + 1}/${time.getDate()} 23:59:59`,
    ).getTime();
  }
};

const onSelectDate = (date) => {
  dateDefaultVal.value = [];
  const timestamp = new Date(date).getTime();
  // 获取以选择日期的开始或结束日期
  let selectedStart = getStartTime(timestamp);
  let selectedEnd = getEndTime(timestamp);
  // 获取当前页面上显示的日期范围
  let { start_date, end_date } = getResTime();
  const origin_start_date = start_date,
    origin_end_date = end_date;
  // 如果是选择的开始时间，那么如果选择的开始时间大于结束日期，那么就应该交换
  if (select_time_type === "start") {
    if (timestamp > end_date) {
      start_date = getStartTime(end_date);
      end_date = selectedEnd;
    } else {
      start_date = selectedStart;
    }
  } else {
    // 如果选择的是结束日期，那么如果选择的日期是小于开始日期的，那么就应该交换
    if (timestamp < start_date) {
      end_date = getEndTime(start_date);
      start_date = selectedStart;
    } else {
      end_date = selectedEnd;
    }
  }
  if (start_date !== origin_start_date) {
    emit("update:start_date", start_date);
  }
  if (end_date !== origin_end_date) {
    emit("update:end_date", end_date);
  }
  emit("onSelect", {
    start_date,
    end_date,
  });
};
watchEffect(() => {
  selectd_end_date.value = props.end_date as string;
  selectd_start_date.value = props.start_date as string;
});
</script>

<style lang="scss" scoped>
.wl-date-range[weiling-mobile-ui-wl-date-range] {
  @extend %flex-middle;
  .space {
    margin: 0 j(10);
    color: var(--wl-text-color-placeholder);
    transform: scaleX(1.5);
  }
  .date-select {
    border: j(1) solid var(--wl-line-color-light);
    border-radius: j(6);
    padding: j(6);
    cursor: pointer;
    min-width: j(106);
    min-height: j(33);
    box-sizing: border-box;
    @extend %flex-middle-center;
    .text {
      margin-right: j(6);
    }
    .text-default {
      color: var(--wl-text-color-placeholder);
    }
    .icon-wrap {
      line-height: 0;
      svg {
        height: j(12);
      }
    }
  }
}
</style>
