<!-- 报告元数据日期输入类型组件 -->

<script setup lang="ts">
import { onMounted, ref, type PropType } from "vue";
import type { Dayjs } from 'dayjs';
import dayjs from "dayjs";
import type { ReportMetadataItem } from "@/types/report.types";

const props = defineProps({
  data: {
    type: Object as PropType<ReportMetadataItem>,
    required: true,
  }
});

type RangeValue = [Dayjs, Dayjs];

const value = ref<RangeValue>();
// 日期连接字符串
const concatChar = ' 至 ';

onMounted(() => {
  const v = props.data.value;
  let from = '', to = '';
  if (v.includes(concatChar)) {
    [from, to] = v.split(concatChar);
  } else {
    [from, to] = props.data.value.split(' ');
  }
  const dateFrom = dayjs(from);
  const dateTo = dayjs(to);
  if (dateFrom.isValid() && dateTo.isValid()) {
    value.value = [dateFrom, dateTo]
  }
});

const emits = defineEmits<{
  (e: "update:data", data: ReportMetadataItem): void;
}>();

function onNameChange(e: InputEvent) {
  change((e.target as HTMLInputElement).value, props.data.value);
}

function onValueChange(_: Dayjs | string, dateString: [string, string]) {
  change(props.data.name, dateString.join(concatChar));
}

function change(name: string, value: string) {
  emits("update:data", { name, value, type: props.data.type });
}
</script>

<template>
  <a-row type="flex" style="align-items: center">
    <a-col class="name-wrap">
      <a-space>
        <a-input :value="data.name" @change="onNameChange" placeholder="字段名称" class="name" />
        <span>：</span>
      </a-space>
    </a-col>
    <a-col flex="1">
      <a-range-picker v-model:value="value" @change="onValueChange" class="value" />
    </a-col>
  </a-row>
</template>

<style scoped lang="scss">
.name-wrap {
  width: 120px;

  .name {
    width: 100%
  }
}
.value {
  width: 100%;
}
</style>
