<template>
  <view class="px-2 text-3.5">
    <view class="flex flex-items-center pos-relative">
      <view v-if="required" class="color-#f62933 pos-absolute left--2 mt-1">*</view>
      <view>{{ title }}</view>
    </view>
    <view class="py-2" @click="openDialog">
      <view class="flex flex-items-center flex-justify-between">
        <view :class="text ? 'custom-color-black' : 'color-#838589'">
          {{ text || placeholder }}
        </view>
        <wd-icon name="arrow-right" color="rgba(0,0,0,0.25)" size="18px"></wd-icon>
      </view>
    </view>
  </view>
  <wd-popup
    v-model="show"
    position="bottom"
    custom-style="border-radius:12rpx;"
    @after-leave="afterLeave"
  >
    <view>
      <view class="p-4 text-3.5 border-b-1 border-[#dcdcdc] border-solid flex flex-items-center">
        <view class="font-bold">日期：</view>
        <view class="font-bold ml-a" v-if="type !== 'dateHalfDay'">{{ date }}</view>
      </view>
      <view v-if="(type === 'date' || type === 'datetime') && showPicker">
        <wd-datetime-picker-view
          :formatter="formatter"
          :type="type"
          v-model="timestamp"
          label="日期选择"
          @change="change"
        />
      </view>
      <view v-if="type === 'dateHalfDay' && showPicker">
        <wd-tabs v-model="tab">
          <wd-tab :title="index === 0 ? date : halfDay" v-for="(item, index) in 2" :key="index">
            <view v-show="index === 0">
              <wd-datetime-picker-view
                :formatter="formatter"
                type="date"
                v-model="timestamp"
                @change="change"
              />
            </view>
            <view v-show="index === 1">
              <wd-picker-view :columns="['上午', '下午']" v-model="halfDay" @change="change" />
            </view>
          </wd-tab>
        </wd-tabs>
      </view>
      <view class="pb-safe">
        <view class="flex py-3 flex-items-center flex-justify-around text-3.5 px-2 font-bold">
          <view
            class="w-45% bg-#eeeff4 custom-color-blue py-2.5 rounded-2 text-center"
            @click="show = false"
          >
            取消
          </view>
          <view
            class="w-45% custom-bg-blue color-white py-2.5 rounded-2 text-center"
            @click="confirm"
          >
            确定
          </view>
        </view>
      </view>
    </view>
  </wd-popup>
</template>

<script setup lang="ts">
  import dayjs from 'dayjs'

  const show = ref<boolean>(false)
  const timestamp = ref<number>(0)
  const text = ref<string>('')
  const date = ref<string>('')
  const halfDay = ref<string>('')
  const showPicker = ref<boolean>(false)
  const returnTimestamp = ref<number>(0)

  const tab = ref<number>(0)

  const props = defineProps({
    id: {
      type: Number,
      required: true
    },
    type: {
      type: String,
      default: 'date'
    },
    required: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      required: true
    },
    value: {
      type: [Number, null],
      default: null
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    disabledText: {
      type: String,
      default: ''
    },
    minDate: {
      type: [Number, null],
      default: null
    },
    maxDate: {
      type: [Number, null],
      default: null
    },
    minDateText: {
      type: String,
      default: ''
    },
    maxDateText: {
      type: String,
      default: ''
    }
  })

  const formatter = (type, value) => {
    switch (type) {
      case 'year':
        return value + '年'
      case 'month':
        return value + '月'
      case 'date':
        return value + '日'
      case 'hour':
        return value + '时'
      case 'minute':
        return value + '分'
      default:
        return value
    }
  }

  const emits = defineEmits(['change'])

  onMounted(() => {
    if (props.value) {
      timestamp.value = props.value
      if (props.type === 'date') {
        date.value = dayjs(props.value).format('YYYY-M-D')
        text.value = date.value
      } else if (props.type === 'datetime') {
        date.value = dayjs(props.value).format('YYYY-M-D HH:mm')
        text.value = date.value
      } else if (props.type === 'dateHalfDay') {
        date.value = dayjs(props.value).format('YYYY年M月D日')
        halfDay.value = dayjs(props.value).hour() < 12 ? '上午' : '下午'
        text.value = `${date.value} ${halfDay.value}`
      }
    }
  })

  const change = ({ value }) => {
    if (props.type === 'date') {
      date.value = dayjs(value).format('YYYY-M-D')
    } else if (props.type === 'datetime') {
      date.value = dayjs(value).format('YYYY-M-D HH:mm')
    } else if (props.type === 'dateHalfDay') {
      if (tab.value === 0) {
        date.value = dayjs(value).format('YYYY年M月D日')
      } else {
        halfDay.value = value
      }
    }
  }

  const openDialog = () => {
    if (props.disabled) {
      uni.showToast({
        title: props.disabledText,
        icon: 'none'
      })
      return
    }
    if (!props.value) {
      if (text.value === '') {
        timestamp.value = new Date().getTime()
      } else {
        timestamp.value = returnTimestamp.value
      }

      if (props.type === 'date') {
        date.value = dayjs(timestamp.value).format('YYYY-M-D')
      } else if (props.type === 'datetime') {
        date.value = dayjs(timestamp.value).format('YYYY-M-D HH:mm')
      } else if (props.type === 'dateHalfDay') {
        date.value = dayjs(timestamp.value).format('YYYY年M月D日')
        halfDay.value = dayjs(timestamp.value).hour() < 12 ? '上午' : '下午'
      }
    }
    showPicker.value = true
    show.value = true
  }

  const confirm = () => {
    if (props.minDate && timestamp.value < props.minDate) {
      uni.showToast({
        title: props.minDateText,
        icon: 'none'
      })
      return
    }
    if (props.maxDate && timestamp.value > props.maxDate) {
      uni.showToast({
        title: props.maxDateText,
        icon: 'none'
      })
      return
    }
    show.value = false
    returnTimestamp.value = timestamp.value
    if (props.type === 'dateHalfDay') {
      text.value = `${date.value} ${halfDay.value}`
    } else {
      text.value = date.value
    }
    emits('change', { id: props.id, value: returnTimestamp.value, text: text.value })
  }

  const afterLeave = () => {
    showPicker.value = false
  }

  const clear = () => {
    text.value = ''
    date.value = ''
    halfDay.value = ''
    returnTimestamp.value = 0
    emits('change', { id: props.id, value: returnTimestamp.value, text: text.value })
  }

  defineExpose({
    clear
  })
</script>
