<script setup lang="ts">
import { computed, useAttrs, watch } from 'vue'
import { usePropBind, LABEL_KEY, getDatePattern } from './common'
import GdFormItem from './GdFormItem.vue';
import moment from 'moment';

const props = withDefaults(defineProps<{
  label: string,
  rules?: [],
  type?: string
}>(), { label: '' })

const { propValue, handleChange } = usePropBind()
const attrs = <any>useAttrs()

const type = computed(() => props.type ? props.type : 'date')
watch(type, (val) => {
  handleChange('')
})

const propValueTransfer = computed(() => {
  if (props.type?.includes('range')) {
    return propValue.value ? propValue.value.split(',') : []
  }
  return propValue.value
})
const handlePropValueChange = (value: any) => {
  handleChange(props.type?.includes('range') ? value?.join(',') : value)
}
const selectedLabel = computed(() => {
  const value = propValue.value
  if (!value) {
    return ''
  }
  return value.split(',').map((val: any) => moment(val).format(getDatePattern(props.type))).join(' ~ ')
})
</script>

<template>
  <GdFormItem :label="props.label" :rules="props.rules">
    <p class="viewer-content" v-if="attrs.viewerMode">{{ selectedLabel }}</p>
    <el-date-picker v-else :model-value="propValueTransfer" value-format="YYYY-MM-DD"
      @update:model-value="handlePropValueChange"
      :placeholder="`${$t('placeholder_prefix_select')?.replace(LABEL_KEY, label)}`" class="gd-datepicker" clearable
      :type="type" v-bind="attrs" />
  </GdFormItem>
</template>

<style lang="scss">
.gd-form .gd-datepicker.el-date-editor.el-input,
.gd-form .gd-datepicker.el-date-editor.el-input .el-input__wrapper {
  width: 100%;
}
</style>