import { useVModel } from "@vueuse/core";

import { defineComponent, unref } from "vue";
import { IntervalTimeProps } from "./types";

const IntervalTime = defineComponent({
  name: "IntervalTime",
  props: IntervalTimeProps,
  emits: ["timeChange"],
  setup(props, { emit }) {
    const start = useVModel(props, "startValue");
    const end = useVModel(props, "endValue");
    const startDisabledDate = (time: Date) => {
      const timeEnd = end.value ?? "";
      const times = time.getTime().valueOf();
      if (timeEnd !== "" && times) {
        return times > new Date(timeEnd).valueOf();
      }
    };
    const endDisabledDate = (time: Date) => {
      const timeStart = start.value ?? "";
      const times = time.getTime().valueOf();
      if (timeStart !== "" && times) {
        return times < new Date(timeStart).valueOf();
      }
    };

    return () => (
      <ul class="IntervalTime">
        <li class="timeItem">
          <el-date-picker
            v-model={start.value}
            type={"date"}
            format={"YYYY-MM-DD"}
            value-format={"YYYY-MM-DD"}
            clearable
            style="width:100%"
            disabled-date={startDisabledDate}
            onChange={() => emit("timeChange", unref(start), unref(end))}
            placeholder={props.placeholder ?? "" + "开始时间"}
          />
        </li>
        <li class="timeZhi">至</li>
        <li class="timeItem">
          <el-date-picker
            v-model={end.value}
            disabled-date={endDisabledDate}
            type={"date"}
            style="width:100%"
            format={"YYYY-MM-DD"}
            value-format={"YYYY-MM-DD"}
            clearable
            onChange={() => emit("timeChange", unref(start), unref(end))}
            placeholder={props.placeholder ?? "" + "结束时间"}
          />
        </li>
      </ul>
    );
  }
});

export default IntervalTime;
