<template>
  <view class="check-date-box" :style="style">
    <view class="title" :style="textStyle">检验时间：</view>
    <wd-datetime-picker
      class="date-picker"
      v-model="dateRange"
      type="date"
      :min-date="minDate"
      :max-date="maxDate"
      :default-value="defaultValue"
      @confirm="onConfirm"
    >
      <view class="date-input">
        <text :class="['date-text', { 'date-text--placeholder': !displayText }]">
          {{ displayText || '请选择日期范围' }}
        </text>
      </view>
    </wd-datetime-picker>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import dayjs from 'dayjs'

interface Props {
  textStyle?: any
  style?: any
}

const props = defineProps<Props>()

const emit = defineEmits<{
  change: [date: string[], type: string]
}>()

const minDate = new Date(new Date().getFullYear() - 10, 0, 1).getTime()
const maxDate = new Date(new Date().getFullYear() + 10, 11, 31).getTime()
const defaultValue = [Date.now(), Date.now()]

const dateRange = ref<(number | string)[]>([])

const displayText = computed(() => {
  if (!dateRange.value || dateRange.value.length < 2 || !dateRange.value[0] || !dateRange.value[1]) {
    return ''
  }
  const start = dayjs(Number(dateRange.value[0])).format('YYYY-MM-DD')
  const end = dayjs(Number(dateRange.value[1])).format('YYYY-MM-DD')
  return `${start} 至 ${end}`
})

const onConfirm = ({ value }: { value: (number | string)[] }) => {
  if (value && value.length === 2) {
    const startDateTime = `${dayjs(Number(value[0])).format('YYYY-MM-DD')} 00:00:00`
    const endDateTime = `${dayjs(Number(value[1])).format('YYYY-MM-DD')} 23:59:59`
    emit('change', [startDateTime, endDateTime], 'checkDate')
  }
}

defineExpose({
  reset: () => {
    dateRange.value = []
  },
  inputContent: computed(() => {
    if (!dateRange.value || dateRange.value.length < 2) return ''
    return [dateRange.value[0], dateRange.value[1]]
  }),
})
</script>

<style lang="scss" scoped>
.check-date-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px !important;
}

.title {
  flex-shrink: 0;
  width: 60px;
  font-size: 12px;
  color: rgb(51, 51, 51);
  text-align: right;
}

.date-picker {
  flex: 1;
  min-width: 0;
}

.date-input {
  box-sizing: border-box;
  display: flex;
  flex: 1;
  align-items: center;
  min-width: 0;
  height: 30px;
  min-height: 30px;
  padding: 0 5px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

.date-text {
  font-size: 12px;
  color: rgb(51, 51, 51);

  &--placeholder {
    color: rgba(136, 136, 136, 1);
  }
}
</style>
