<script setup>
import dayjs from 'dayjs'
import PreviewPlanPopup from './components/PreviewPlanPopup.vue'
import {
  getAnnualPlanGetByDateApi,
  getAnnualPlanGetDateApi
} from '@/api/elevator'

const currYear = ref()
// 生产 year 一年 所有月份的日期数组
const allMonthLimit3 = ref([])

const computedYear = () => {
  const allMonth = []
  for (let i = 0; i < 12; i++) {
    const month = i + 1
    const year = currYear.value
    const days = dayjs(new Date(year, month, 0)).daysInMonth()
    const curr = { year, month }
    const monthArr = []
    // 补上前面的空白
    const FirstDay = new Date(year, month - 1, 1)
    let dayOfWeek = dayjs(FirstDay).day()
    // 调整为以周一为首天
    if (dayOfWeek === 0) {
      dayOfWeek = 6 // 周日调整为6
    } else {
      dayOfWeek -= 1 // 其他天减1
    }
    for (let j = 0; j < dayOfWeek; j++) {
      monthArr.push({ ...curr, day: '' })
    }

    for (let j = 1; j <= days; j++) {
      monthArr.push({ ...curr, day: j })
    }
    allMonth.push(monthArr)
  }
  // allMonth 变成三个一组的数组
  const limit3 = []
  for (let i = 0; i < allMonth.length; i += 3) {
    const arr = allMonth.slice(i, i + 3)
    limit3.push(arr)
  }
  allMonthLimit3.value = limit3
}
onMounted(() => {
  currYear.value = dayjs().year()
  computedYear()
})

const pre = () => {
  currYear.value -= 1
  computedYear()
}

const next = () => {
  if (currYear.value === dayjs().year()) {
    return
  }
  currYear.value += 1
  computedYear()
}

const planList = ref([])
const handleDays = async ({ year, month, day, has }) => {
  if (!day) {
    return
  }

  if (has) {
    showPopup.value = true
    const planDate = dayjs(`${year}-${month}-${day} 00:00:00`).format(
      'YYYY-MM-DD'
    )
    const { error, data } = await getAnnualPlanGetByDateApi({
      planDate
    })

    if (!error) {
      planList.value = data
    }
  } else {
    showPopup.value = false
  }
  console.log('click day:', year, month, day)
}

const selected = ref([])
onLoad(async () => {
  const { error, data } = await getAnnualPlanGetDateApi()
  if (!error) {
    selected.value = data
  }
})

const isSelected = (days) => {
  const { year, month, day } = days
  const date = `${year}-${month}-${day}`
  const enterDate = dayjs(date).format('YYYY-MM-DD')
  return selected.value.some((item) => item === enterDate)
}

const showPopup = ref(false)
</script>

<template>
  <view class="inspection-plan" w-full>
    <!-- 年份切换 -->
    <view w-full flex justify-between mt-24 mb-30 px-30>
      <view bg="#F0F7FC" w-50 h-50 rounded-full f-c-c @tap="pre">
        <up-icon name="arrow-left" :color="`${'#4395D5'}`" />
      </view>
      <view text-40 font-500 color="#4396D5">{{ currYear }}</view>
      <view bg="#F0F7FC" w-50 h-50 rounded-full f-c-c @tap="next">
        <up-icon name="arrow-right" :color="`${'#4395D5'}`" />
      </view>
    </view>

    <view px-16>
      <up-row
        v-for="(months, index) in allMonthLimit3"
        :key="index"
        :align="`${'top'}`"
        justify="space-between"
        gutter="5"
      >
        <up-col v-for="(month, idx) in months" :key="idx" span="4">
          <view text-30 font-500 mb-8 px-10>{{ month[0].month }}月</view>
          <view class="calendar-box" w-full h-auto>
            <view
              v-for="(days, i) in month"
              :key="i"
              text-22
              text-center
              :style="{
                color: isSelected(days) ? '#4396D5' : '#333',
                // 下划线
                'text-decoration-line': isSelected(days) ? 'underline' : 'none'
              }"
              @tap="handleDays({ ...days, has: isSelected(days) })"
            >
              {{ days.day }}
            </view>
          </view>
        </up-col>
      </up-row>
    </view>
  </view>

  <PreviewPlanPopup v-model="showPopup" v-model:list="planList" />
</template>

<style lang="scss" scoped>
.calendar-box {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0;
}
</style>

<style>
.inspection-plan .u-row {
  margin-bottom: 40rpx;
}
</style>
