<template>
  <view class="picker-custom">
    <!-- 插槽内容，点击触发弹层 -->
    <view @click="open">
      <slot></slot>
    </view>
    <!-- 遮罩层 -->
    <view v-if="show" class="picker-layer-mask" @click="close"></view>
    <!-- 底部弹出层 -->
    <view v-if="show" class="picker-layer-popup">
      <view class="picker-layer-panel">
        <!-- 可自定义头部 -->
        <view class="picker-layer-header">
          <text @click="close" class="picker-layer-cancel">取消</text>
          <text @click="confirm" class="picker-layer-confirm">确定</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="pickerValue"
          :immediate-change="true"
          @change="onChange"
        >
          <template v-if="mode === 'date'">
            <picker-view-column>
              <view
                v-for="(item, idx) in years"
                :key="idx"
                class="picker-layer-item"
              >
                {{ item }}年
              </view>
            </picker-view-column>
            <picker-view-column>
              <view
                v-for="(item, idx) in months"
                :key="idx"
                class="picker-layer-item"
              >
                {{ item }}月
              </view>
            </picker-view-column>
            <picker-view-column>
              <view
                v-for="(item, idx) in days"
                :key="idx"
                class="picker-layer-item"
              >
                {{ item === "请选择" ? item : `${item}日` }}
              </view>
            </picker-view-column>
          </template>
          <template v-else>
            <picker-view-column>
              <view
                v-for="(item, idx) in columns[0]"
                :key="idx"
                class="picker-layer-item"
              >
                {{ item }}
              </view>
            </picker-view-column>
          </template>
        </picker-view>
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, computed, watch } from "vue";

const props = defineProps({
  mode: {
    type: String,
    default: "custom", // 'date' | 'custom'
  },
  range: {
    type: [Array, Object],
    default: () => [],
  },
  value: {
    type: [Number, Array, String],
    default: 0,
  },
  onPickerChange: {
    type: Function,
    default: () => {},
  },
  onLayerVisibleChange: {
    type: Function,
    default: () => {},
  },
  onStatusChange: {
    type: Function,
    default: () => {},
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const show = ref(false);
// date模式相关
const today = new Date();
const currentYear = today.getFullYear();
const currentMonth = today.getMonth() + 1;
const currentDay = today.getDate();

// 计算未来280天的日期
const futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 280);
const futureYear = futureDate.getFullYear();
const futureMonth = futureDate.getMonth() + 1;
const futureDay = futureDate.getDate();

// 工具函数：生成年份数组
function getYears() {
  const arr = [];
  const startYear = currentYear - 3;
  const endYear = futureYear;
  for (let i = startYear; i <= endYear; i++) {
    arr.push(i);
  }
  return arr;
}
// 工具函数：生成月份数组
function getMonths(selectedYear) {
  let startMonth = 1;
  let endMonth = 12;
  if (selectedYear === currentYear - 3) {
    startMonth = currentMonth;
  }
  if (selectedYear === futureYear) {
    endMonth = futureMonth;
  }
  const arr = [];
  for (let i = startMonth; i <= endMonth; i++) {
    arr.push(i);
  }
  return arr;
}
// 工具函数：生成天数数组（含"请选择"）
function getDays(selectedYear, selectedMonth) {
  const dayCount = new Date(selectedYear, selectedMonth, 0).getDate();
  let startDay = 1;
  let endDay = dayCount;
  if (selectedYear === currentYear - 3 && selectedMonth === currentMonth) {
    startDay = currentDay;
  }
  if (selectedYear === futureYear && selectedMonth === futureMonth) {
    endDay = futureDay;
  }

  const arr = ["请选择"];
  for (let i = startDay; i <= endDay; i++) {
    arr.push(i);
  }
  return arr;
}

const years = computed(() => getYears());
const defaultValue = computed(() => {
  if (props.mode === "date") {
    // 1. value为索引数组
    if (Array.isArray(props.value) && props.value.length === 3) {
      return props.value;
    }
    // 2. value为日期字符串
    if (
      typeof props.value === "string" &&
      props.value.match(/^\d{4}-\d{2}-\d{2}$/)
    ) {
      const idxArr = getPickerIndexByDate(props.value);
      if (idxArr) return idxArr;
    }
    // 3. 默认选中今天
    const yearIdx = years.value.findIndex((y) => y === currentYear);
    // 直接用当前年推算可用月份
    let tempMonths = [];
    let startMonth = 1,
      endMonth = 12;
    if (yearIdx === 0) startMonth = currentMonth;
    if (yearIdx === years.value.length - 1) endMonth = futureMonth;
    for (let i = startMonth; i <= endMonth; i++) tempMonths.push(i);
    const monthIdx = tempMonths.findIndex((m) => m === currentMonth);
    // days
    let tempDays = ["请选择"];
    if (yearIdx >= 0 && monthIdx >= 0) {
      const selectedYear = years.value[yearIdx];
      const selectedMonth = tempMonths[monthIdx];
      const dayCount = new Date(selectedYear, selectedMonth, 0).getDate();
      let startDay = 1,
        endDay = dayCount;
      if (yearIdx === 0 && selectedMonth === currentMonth)
        startDay = currentDay;
      if (yearIdx === years.value.length - 1 && selectedMonth === futureMonth)
        endDay = futureDay;
      for (let i = startDay; i <= endDay; i++) tempDays.push(i);
    }
    const dayIdx = tempDays.findIndex((d) => d === currentDay);
    return [
      yearIdx >= 0 ? yearIdx : 0,
      monthIdx >= 0 ? monthIdx : 0,
      dayIdx >= 0 ? dayIdx : 0,
    ];
  } else if (Array.isArray(props.value)) {
    return props.value;
  } else {
    return [props.value];
  }
});

const pickerValue = ref([...defaultValue.value]);

watch(
  () => props.value,
  (val) => {
    if (props.mode === "date") {
      pickerValue.value = [...defaultValue.value];
    } else if (Array.isArray(val)) {
      pickerValue.value = [...val];
    } else {
      pickerValue.value = [val];
    }
  }
);

const months = computed(() => {
  const [yearIdx] = pickerValue.value;
  const selectedYear = years.value[yearIdx];
  return getMonths(selectedYear);
});

const days = computed(() => {
  const [yearIdx, monthIdx] = pickerValue.value;
  const selectedYear = years.value[yearIdx];
  const selectedMonth = months.value[monthIdx] || 1;
  return getDays(selectedYear, selectedMonth);
});

// custom模式相关
const columns = computed(() => {
  if (Array.isArray(props.range[0])) {
    return props.range;
  } else {
    return [props.range];
  }
});

// 工具函数：根据日期字符串获取索引
function getPickerIndexByDate(dateStr) {
  if (!dateStr) return null;
  const [year, month, day] = dateStr.split("-").map(Number);
  const yearsArr = getYears();
  const yearIdx = yearsArr.findIndex((y) => y === year);
  if (yearIdx < 0) return null;
  const selectedYear = yearsArr[yearIdx];
  const monthsArr = getMonths(selectedYear);
  const monthIdx = monthsArr.findIndex((m) => m === month);
  if (monthIdx < 0) return null;
  const daysArr = getDays(selectedYear, month);
  const dayIdx = daysArr.findIndex((d) => d === day);
  if (dayIdx < 0) return null;
  return [yearIdx, monthIdx, dayIdx];
}

function open() {
  if (props.disabled) return;
  pickerValue.value = [...defaultValue.value];
  show.value = true;
  props.onLayerVisibleChange(true);
}
function close() {
  show.value = false;
  props.onLayerVisibleChange(false);
}
function confirm() {
  close();
  if (props.mode === "date") {
    const [yIdx, mIdx, dIdx] = pickerValue.value;


    if (dIdx === 0) {
      props.onPickerChange("");
      return;
    }

    const year = years.value[yIdx];
    const month = months.value[mIdx];
    const day = days.value[dIdx];
    const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(
      day
    ).padStart(2, "0")}`;

    // 新增：判断状态并回调
    const today = new Date();
    const selectedDate = new Date(year, month - 1, day);
    // 清除时分秒
    today.setHours(0, 0, 0, 0);
    selectedDate.setHours(0, 0, 0, 0);
    let status = -1;
    if (selectedDate.getTime() <= today.getTime()) {
      status = 2;
    } else {
      status = 1;
    }

    console.log("status", status);
    const changeRes = props.onStatusChange(status);
    if (changeRes) {
      props.onPickerChange(dateStr);
    }
  } else {
    // 单列时只返回索引，否则返回数组
    if (columns.value.length === 1) {
      props.onPickerChange(pickerValue.value[0]);
    } else {
      props.onPickerChange([...pickerValue.value]);
    }
  }
}
function onChange(e) {
  let val = e.detail.value;
  console.log('onChange', val);
  if (props.mode === "date") {
    // 记录上一次的 pickerValue
    const prevValue = [...pickerValue.value];
    // 如果年份变化，月份和日都重置为0
    if (val[0] !== prevValue[0]) {
      val[1] = 0;
      val[2] = 0;
    } else if (val[1] !== prevValue[1]) {
      // 如果月份变化，日重置为0
      val[2] = 0;
    }
    // 如果天数溢出，自动修正到最大天数
    const maxDay = days.value.length;
    if (val[2] >= maxDay) val[2] = maxDay - 1;
    pickerValue.value = val;
  } else {
    pickerValue.value = val;
  }
}
</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: 28rpx;
    width: 136rpx;
    height: 74rpx;
    border-radius: 20rpx;
    background: #ffffff;

    display: flex;
    align-items: center;
    justify-content: center;
  }
  .picker-layer-confirm {
    color: #ffffff;
    font-size: 28rpx;
    width: 136rpx;
    height: 74rpx;
    border-radius: 20rpx;
    background: #d3a358;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .picker-layer-title {
    color: #222;
    font-size: 32rpx;
    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: 32rpx;
  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;
}

.picker-custom[disabled] {
  opacity: 0.5;
  pointer-events: none;
}
</style>