<!-- components/DatePicker.vue -->
<template>
  <!-- 底部弹窗遮罩层 -->
  <view v-if="visible" class="picker-layer-mask" @click="close"></view>
  <!-- 弹窗内容区 -->
  <view v-if="visible" class="picker-layer-popup">
    <view class="picker-layer-panel">
      <!-- 可自定义头部 -->
      <view class="picker-layer-header">
        <text class="picker-layer-cancel" @click="close">取消</text>
        <text class="picker-layer-confirm" @click="handleConfirm">确定</text>
      </view>
      <view class="picker-layer-view-mask-top"></view>
      <view class="picker-layer-view-mask-bottom"></view>

      <!-- picker-view 选择器核心 -->
      <picker-view 
        class="picker-layer-view"
        mask-style="background: rgb(246, 248, 250); z-index: 0;"
        indicator-style="border-radius: 10px; height: 50px; background:#ffffff; z-index:0" 
        :value="timeValue"
        :immediate-change="true"
        @change="bindChange" 
      >
        <picker-view-column>
          <view class="picker-layer-item" v-for="(item,index) in years" :key="index">{{item}}年</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-layer-item" v-for="(item,index) in months" :key="index">{{item}}月</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-layer-item" v-for="(item,index) in days" :key="index">{{item}}日</view>
        </picker-view-column>
      </picker-view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
	type: Array,
	default: [],
  },
  currentIndex: {
	type: String,
	default: '',
  },
  currentSubIndex: {
	type: String,
	default: ''
  },
  currentFieldIndex: {
	type: String,
	default: '',
   },
})

const emit = defineEmits(['update:visible', 'confirm'])

// 日期选择器相关状态
const dueDate = ref(uni.getStorageSync('dueDate') || '')
const date = new Date()
const timeValue = ref([]) // 日期选择器当前值

// 计算日期范围
const minDate = computed(() => {
  if (!dueDate.value) return new Date(2010, 0, 1)
  const due = new Date(dueDate.value)
  const min = new Date(due)
  min.setDate(min.getDate() - 280) // 280天前
  return min
})

const maxDate = computed(() => {
  if (!dueDate.value) return new Date(date.getFullYear() + 2, 11, 31)
  return new Date(dueDate.value)
})

// 年份数据 (minDate的年份到maxDate的年份)
const years = computed(() => {
  const yearList = []
  const minYear = minDate.value.getFullYear()
  const maxYear = maxDate.value.getFullYear()
  for (let i = minYear; i <= maxYear; i++) {
    yearList.push(i)
  }
  return yearList
})

// 月份数据 (根据当前选中的年份动态生成)
const months = computed(() => {
  const monthList = []
  let minMonth = 1
  let maxMonth = 12
  
  if (selectedYear.value === minDate.value.getFullYear()) {
    minMonth = minDate.value.getMonth() + 1
  }
  
  if (selectedYear.value === maxDate.value.getFullYear()) {
    maxMonth = maxDate.value.getMonth() + 1
  }
  
  for (let i = minMonth; i <= maxMonth; i++) {
    monthList.push(i)
  }
  return monthList
})

// 日期数据 (动态生成)
const days = computed(() => {
  const dayList = []
  let minDay = 1
  let maxDay = getDaysInMonth(selectedYear.value, selectedMonth.value)
  
  // 如果是范围的最小年月
  if (selectedYear.value === minDate.value.getFullYear() && 
      selectedMonth.value === minDate.value.getMonth() + 1) {
    minDay = minDate.value.getDate()
  }
  
  // 如果是范围的最大年月
  if (selectedYear.value === maxDate.value.getFullYear() && 
      selectedMonth.value === maxDate.value.getMonth() + 1) {
    maxDay = maxDate.value.getDate()
  }
  
  for (let i = minDay; i <= maxDay; i++) {
    dayList.push(i)
  }
  return dayList
})

// 当前选中的年月日
const selectedYear = ref(date.getFullYear())
const selectedMonth = ref(date.getMonth() + 1)
const selectedDay = ref(date.getDate())

// 获取某年某月的天数
function getDaysInMonth(year, month) {
  return new Date(year, month, 0).getDate()
}

// 更新选择器的索引值
const updateValueIndices = () => {
  const yearIndex = years.value.indexOf(selectedYear.value)
  const monthIndex = months.value.indexOf(selectedMonth.value)
  const dayIndex = days.value.indexOf(selectedDay.value)
  
  if (yearIndex !== -1 && monthIndex !== -1 && dayIndex !== -1) {
    timeValue.value = [yearIndex, monthIndex, dayIndex]
  } else {
    // 如果当前选中的值不在范围内，自动调整到最近的合法值
    adjustToValidDate()
  }
}

// 调整到合法的日期
const adjustToValidDate = () => {
  let year = selectedYear.value
  let month = selectedMonth.value
  let day = selectedDay.value
  
  // 调整年份
  if (year < minDate.value.getFullYear()) {
    year = minDate.value.getFullYear()
  } else if (year > maxDate.value.getFullYear()) {
    year = maxDate.value.getFullYear()
  }
  
  // 调整月份
  if (year === minDate.value.getFullYear() && month < minDate.value.getMonth() + 1) {
    month = minDate.value.getMonth() + 1
  } else if (year === maxDate.value.getFullYear() && month > maxDate.value.getMonth() + 1) {
    month = maxDate.value.getMonth() + 1
  }
  
  // 调整日期
  const maxDays = getDaysInMonth(year, month)
  if (day > maxDays) {
    day = maxDays
  }
  
  if (year === minDate.value.getFullYear() && 
      month === minDate.value.getMonth() + 1 && 
      day < minDate.value.getDate()) {
    day = minDate.value.getDate()
  }
  
  if (year === maxDate.value.getFullYear() && 
      month === maxDate.value.getMonth() + 1 && 
      day > maxDate.value.getDate()) {
    day = maxDate.value.getDate()
  }
  
  selectedYear.value = year
  selectedMonth.value = month
  selectedDay.value = day
  
  updateValueIndices()
}

// 设置日期
const setDate = (indices) => {
  if (!indices || indices.length !== 3) return
   
  const year = years.value[indices[0]]
  const month = months.value[indices[1]]
  const day = days.value[indices[2]]
  
  selectedYear.value = year
  selectedMonth.value = month
  selectedDay.value = day
}

// 时间选择变化时间
const bindChange = (e) => {
  const values = e.detail.value
  timeValue.value = values
  
  selectedYear.value = years.value[values[0]]
  selectedMonth.value = months.value[values[1]]
  selectedDay.value = days.value[values[2]]
}

// 关闭弹窗
const close = () => {
  emit('update:visible', false)
}

// 确认选择
const handleConfirm = () => {
  const formattedDate = `${selectedYear.value}-${String(selectedMonth.value).padStart(2, '0')}-${String(selectedDay.value).padStart(2, '0')}`
  emit('confirm', {currentIndex: props.currentIndex, currentSubIndex: props.currentSubIndex, currentFieldIndex: props.currentFieldIndex,formattedDate})
  close()
}

// 初始化日期数据
const initDate = () => {
  // 如果有默认日期，解析日期并设置选中值
  const { currentIndex, currentSubIndex, currentFieldIndex, formData } = props
  	console.log(currentIndex, currentSubIndex, currentFieldIndex, formData,'dateopen--')
	if(currentIndex !=='' && currentFieldIndex !== ''){
		let defaultDate = ""
		if (currentSubIndex !== '') {
				defaultDate = formData[currentIndex].subFormList[currentSubIndex].formComponentList[currentFieldIndex].fieldValue
			} else {
				defaultDate = formData[currentIndex].formComponentList[currentFieldIndex].fieldValue
			}
			console.log(defaultDate,'defaultDate---')
		if (defaultDate) {
		  const dateParts = defaultDate.split('-')
		  const year = parseInt(dateParts[0])
		  const month = parseInt(dateParts[1])
		  const day = parseInt(dateParts[2])
		  
		  // 更新选中值
		  selectedYear.value = year
		  selectedMonth.value = month
		  selectedDay.value = day
		  
		  // 调整到合法日期
		  adjustToValidDate()
		} else {
		  // 如果没有时间，设置为当前日期或最大允许日期
		  const today = new Date()
		  if (today > maxDate.value) {
		    selectedYear.value = maxDate.value.getFullYear()
		    selectedMonth.value = maxDate.value.getMonth() + 1
		    selectedDay.value = maxDate.value.getDate()
		  } else if (today < minDate.value) {
		    selectedYear.value = minDate.value.getFullYear()
		    selectedMonth.value = minDate.value.getMonth() + 1
		    selectedDay.value = minDate.value.getDate()
		  } else {
		    selectedYear.value = today.getFullYear()
		    selectedMonth.value = today.getMonth() + 1
		    selectedDay.value = today.getDate()
		  }
		  console.log(selectedYear.value,selectedMonth.value,selectedDay.value,'898989')
		  updateValueIndices()
		}
	}
}

// 监听选择器值变化，更新选中日期
watch(() => timeValue.value, (newVal) => {
  setDate(newVal)
})

// 监听visible变化，初始化数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initDate()
  }
})

// 监听dueDate变化，重新初始化
watch(() => uni.getStorageSync('dueDate'), (newVal) => {
  dueDate.value = newVal
  if (props.visible) {
    initDate()
  }
})

onMounted(() => {
  dueDate.value = uni.getStorageSync('dueDate')
  initDate()
})
</script>

<style lang="less" scoped>
/* 保持原有样式不变 */
.picker-layer-mask {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 3999;
}

.picker-layer-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 4000;
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: picker-layer-up 0.3s;
}

@keyframes picker-layer-up {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0);
  }
}

.picker-layer-panel {
  width: 100vw;
  height: 50vh;
  background: #f6f8fa;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
}

.picker-layer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 140rpx;
  box-sizing: border-box;
  background: #f6f8fa;
  padding: 0 32rpx;

  .picker-layer-cancel {
    color: #6f6d67;
    font-size: 30rpx;
    width: 136rpx;
    height: 74rpx;
    border-radius: 20rpx;
    background: #ffffff;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  .picker-layer-confirm {
    color: #ffffff;
    font-size: 30rpx;
    width: 136rpx;
    height: 74rpx;
    border-radius: 20rpx;
    background: #d3a358;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .picker-layer-title {
    color: #222;
    font-size: 30rpx;
    font-weight: bold;
  }
}

.picker-layer-view {
  flex: 1;
  width: 100%;
  height: 100%;
}

.picker-layer-item {
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  font-size: 30rpx;
  color: #1d1e25;
}

.picker-layer-view-mask-top {
  position: absolute;
  top: 140rpx;
  left: 0;
  width: 100%;
  height: calc(50% - 100rpx);
  z-index: 1;
  background: linear-gradient(to bottom,
      rgb(246, 248, 250) 0%,
      rgba(255, 255, 255, 0.5) 100%);
  pointer-events: none;
}

.picker-layer-view-mask-bottom {
  position: absolute;
  bottom: 0rpx;
  left: 0;
  width: 100%;
  height: calc(50% - 100rpx);
  z-index: 1;
  background: linear-gradient(to top,
      rgb(246, 248, 250) 0%,
      rgba(255, 255, 255, 0.5) 100%);
  pointer-events: none;
}
</style>