<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import scheduleNavBar from './components/schedulenavbar/index.vue'
import day from './components/day/index.vue'
import week from './components/week/index.vue'
import Moon from './components/Moon/index.vue'
import { querytodoaskslist } from '@/api/workorder'
import dayjs from 'dayjs'
definePage({
  // 使用 type: "home" 属性设置首页，其他页面不需要设置，默认为page
  type: 'home',
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    navigationStyle: 'custom',
    navigationBarTitleText: '工单',
  },
})
interface CalendarDate {
  day: number
  date: Date
  isOtherMonth: boolean
  isToday: boolean
  isSelected: boolean
  isPast: boolean
}
const mainloing = ref(false)
const GasStationId = ref('')
const currentMonth = ref(new Date())
const isExpanded = ref(false)
const radioActive = ref('日')
const selectedDate = ref(new Date())
const overduedaylist = ref([]) as any // 逾期任务列表
const todoaskslist = ref([]) as any // 今日和明日任务列表
const tab = ref('全部')
const tabmap = {
  全部: '全部',
  可授权: '0',
  已授权: '1',
  被授权: '2',
}
//今日和明日任务列表
const querytodoaskslistfn = async ({
  showStartTime,
  showEndTime,
  executorId,
  stationId,
  authStatusStr,
}) => {
  try {
    mainloing.value = true
    const res = (await querytodoaskslist({
      showStartTime,
      showEndTime,
      executorId,
      stationId,
      authStatusStr,
      taskStatusStr: '0,1,3',
    })) as any
    if (res?.code === 200) {
      todoaskslist.value = res?.data || []
    }
  } catch (error) {
    console.log(error)
  } finally {
    mainloing.value = false
  }
}
//逾期任务列表
const queryoverduelistfn = async ({
  showStartTime,
  showEndTime,
  executorId,
  stationId,
  authStatusStr,
}) => {
  try {
    mainloing.value = true
    const res = (await querytodoaskslist({
      showStartTime,
      showEndTime,
      executorId,
      stationId,
      authStatusStr,
      taskStatusStr: '2',
    })) as any
    if (res?.code === 200) {
      overduedaylist.value = res?.data || []
    }
  } catch (error) {
    console.log(error)
  } finally {
    mainloing.value = false
  }
}
const queryViewlist = async () => {
  if (radioActive.value === '日') {
    const data = {
      showStartTime: dayjs(selectedDate.value).format('YYYY-MM-DD 00:00:00'),
      showEndTime: dayjs(selectedDate.value)
        .add(1, 'day')
        .format('YYYY-MM-DD 23:59:59'),
      executorId: GasStationId.value.split('-')[0],
      stationId: GasStationId.value.split('-')[1],
    } as any
    if (tabmap[tab.value] !== '全部') {
      data['authStatusStr'] = tabmap[tab.value]
    }
    await Promise.all([querytodoaskslistfn(data), queryoverduelistfn(data)])
  } else if (radioActive.value === '周') {
    // 计算选中日期所在周的开始（周一）和结束（周日）
    const selected = new Date(selectedDate.value)
    const dayOfWeek = selected.getDay() || 7 // 转换周日为7
    const weekStart = new Date(selected)
    weekStart.setDate(selected.getDate() - dayOfWeek + 1)
    const weekEnd = new Date(selected)
    weekEnd.setDate(selected.getDate() + (7 - dayOfWeek))
    const data = {
      showStartTime: dayjs(weekStart).format('YYYY-MM-DD 00:00:00'),
      showEndTime: dayjs(weekEnd).format('YYYY-MM-DD 23:59:59'),
      executorId: GasStationId.value.split('-')[0],
      stationId: GasStationId.value.split('-')[1],
    } as any
    await Promise.all([querytodoaskslistfn(data), queryoverduelistfn(data)])
  } else if (radioActive.value === '月') {
    const year = currentMonth.value.getFullYear()
    const month = currentMonth.value.getMonth()
    const StartTime = new Date(year, month, 1)
    const EndTime = new Date(year, month + 1, 0)
    const data = {
      showStartTime: dayjs(StartTime).format('YYYY-MM-DD 00:00:00'),
      showEndTime: dayjs(EndTime).format('YYYY-MM-DD 23:59:59'),
      executorId: GasStationId.value.split('-')[0],
      stationId: GasStationId.value.split('-')[1],
    } as any
    await Promise.all([querytodoaskslistfn(data), queryoverduelistfn(data)])
  }
}

watch(
  () => GasStationId.value,
  async () => {
    if (GasStationId.value) {
      await queryViewlist()
    }
  }
)
watch(
  () => radioActive.value,
  async () => {
    // 切换视图时默认选中当前时间
    const today = new Date()
    selectedDate.value = today
    currentMonth.value = today
    await queryViewlist()
  }
)
const currentDate = computed(() => {
  return currentMonth.value.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
  })
})

const generateDates = () => {
  const dates: CalendarDate[] = []
  const year = currentMonth.value.getFullYear()
  const month = currentMonth.value.getMonth()
  const today = new Date()

  // First day of current month
  const firstDay = new Date(year, month, 1)
  // Last day of current month
  const lastDay = new Date(year, month + 1, 0)
  // Start day (Monday) of the first week
  const startDate = new Date(firstDay)
  const dayOfWeek = firstDay.getDay() || 7 // Convert 0 (Sunday) to 7
  startDate.setDate(startDate.getDate() - dayOfWeek + 1)

  // Generate 42 days (6 weeks) to fill the calendar
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i)

    const isToday = date.toDateString() === today.toDateString()
    let isSelected = date.toDateString() === selectedDate.value.toDateString()
    
    // 计算是否是过去的日期
    const dateOnly = new Date(date)
    dateOnly.setHours(0, 0, 0, 0)
    const todayOnly = new Date(today)
    todayOnly.setHours(0, 0, 0, 0)
    const isPast = dateOnly < todayOnly
    
    // 周模式下，标记选中日期所在周的所有日期
    if (radioActive.value === '周') {
      const selected = new Date(selectedDate.value)
      const dayOfWeek = selected.getDay() || 7 // 转换周日为7
      const weekStart = new Date(selected)
      weekStart.setDate(selected.getDate() - dayOfWeek + 1)
      const weekEnd = new Date(selected)
      weekEnd.setDate(selected.getDate() + (7 - dayOfWeek))
      
      const currentDate = new Date(date)
      // 重置时间部分，只比较日期
      currentDate.setHours(0, 0, 0, 0)
      weekStart.setHours(0, 0, 0, 0)
      weekEnd.setHours(0, 0, 0, 0)
      isSelected = currentDate >= weekStart && currentDate <= weekEnd
    }

    dates.push({
      day: date.getDate(),
      date: date,
      isOtherMonth: date.getMonth() !== month,
      isToday: isToday,
      isSelected: isSelected,
      isPast: isPast,
    })
  }

  return dates
}

const dates = computed(() => generateDates())

const displayDates = computed(() => {
  if (isExpanded.value) {
    return dates.value
  } else {
    // When collapsed, show only the week containing today
    const today = new Date()
    const todayDate = today.getDate()
    const todayMonth = today.getMonth()
    const todayYear = today.getFullYear()

    // Find the index of today in the dates array
    const todayIndex = dates.value.findIndex(
      (date) =>
        date.date.getDate() === todayDate &&
        date.date.getMonth() === todayMonth &&
        date.date.getFullYear() === todayYear
    )

    if (todayIndex === -1) return []

    // Get the start index of the week (Monday)
    const weekStartIndex = Math.floor(todayIndex / 7) * 7
    // Return 7 days (1 week)
    return dates.value.slice(weekStartIndex, weekStartIndex + 7)
  }
})

// 导航到创建工单页面
function navigateToCreateOrder() {
  uni.navigateTo({
    url: '/pages/archive/order/creatOrder'
  })
}

const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

const prevMonth = async () => {
  if (currentMonth.value) {
    const newDate = new Date(currentMonth.value)
    newDate.setMonth(newDate.getMonth() - 1)
    currentMonth.value = newDate
    if (radioActive.value === '月') {
      await queryViewlist()
    }
  }
}

const nextMonth = async () => {
  if (currentMonth.value) {
    const newDate = new Date(currentMonth.value)
    newDate.setMonth(newDate.getMonth() + 1)
    currentMonth.value = newDate
    if (radioActive.value === '月') {
      await queryViewlist()
    }
  }
}
const handleDateClick = async (date: CalendarDate) => {
  selectedDate.value = date.date
  await queryViewlist()
}
const addtodoaskslistfn = (val) => {
  uni.navigateTo({
    url: `/pages/schedule/view/addgasstation/index?type=新增${val}`,
  })
}
const handletabs = async (val) => {
  tab.value = val
  await queryViewlist()
}
</script>
<template>
  <view class="box">
    <view v-if="mainloing" class="loading-container">
      <wd-loading size="40px" color="#215ACD"></wd-loading>
    </view>
    <scheduleNavBar @GasStationchange="(value) => (GasStationId = value)" />
    <view class="Calendar">
      <view class="Calendar-header">
        <view style="display: flex; align-items: center">
          <wd-icon name="caret-left-small" size="36rpx" @click="prevMonth" />
          <text style="font-size: 36rpx; font-weight: 500">{{
            currentDate
          }}</text>
          <wd-icon name="caret-right-small" size="36rpx" @click="nextMonth" />
        </view>
        <view class="Calendar-header-Radio">
          <text
            class="Calendar-header-Radio-text"
            :class="{ active: radioActive === '日' }"
            @click="radioActive = '日'"
            >日</text
          >
          <text
            class="Calendar-header-Radio-text"
            :class="{ active: radioActive === '周' }"
            @click="radioActive = '周'"
            >周</text
          >
          <text
            class="Calendar-header-Radio-text"
            :class="{ active: radioActive === '月' }"
            @click="radioActive = '月'"
            >月</text
          >
        </view>
      </view>
      <view
        class="Calendar-weekdays"
        v-if="radioActive === '月' ? false : true"
      >
        <text class="Calendar-weekday">一</text>
        <text class="Calendar-weekday">二</text>
        <text class="Calendar-weekday">三</text>
        <text class="Calendar-weekday">四</text>
        <text class="Calendar-weekday">五</text>
        <text class="Calendar-weekday">六</text>
        <text class="Calendar-weekday">日</text>
      </view>
      <view class="Calendar-dates" v-if="radioActive === '月' ? false : true">
        <view
          v-for="(date, index) in displayDates"
          :key="index"
          :class="[
            'Calendar-date',
            {
              'Calendar-date-active': date.isToday,
              'Calendar-date-other': date.isOtherMonth,
              'Calendar-date-selected': date.isSelected && !date.isToday,
              'Calendar-date-disabled': radioActive === '日' && date.isPast,
            },
          ]"
          @click="(radioActive === '日' && date.isPast) ? null : handleDateClick(date)"
        >
          {{ date.day }}
        </view>
      </view>
      <view
        class="Calendar-footer"
        @click="toggleExpand"
        v-if="radioActive === '月' ? false : true"
      >
        <wd-icon :name="isExpanded ? 'arrow-up' : 'arrow-down'" size="20px" />
      </view>
    </view>
    <view class="box-rigth-fixed">
      <view
        @click="addtodoaskslistfn('油站')"
        style="
          display: flex;
          gap: 14rpx;
          flex-direction: column;
          align-items: center;
          color: #31373d;
        "
      >
        <wd-icon name="add1" size="22px"></wd-icon>
        <text style="font-size: 24rpx; font-weight: 400">油站</text>
      </view>
      <view
        @click="addtodoaskslistfn('访客')"
        style="
          display: flex;
          gap: 14rpx;
          flex-direction: column;
          align-items: center;
          color: #31373d;
        "
      >
        <wd-icon name="user" size="22px"></wd-icon>
        <text style="font-size: 24rpx; font-weight: 400">访客</text>
      </view>
      <view
        style="
          display: flex;
          gap: 14rpx;
          flex-direction: column;
          align-items: center;
          color: #31373d;
        "
        @click="navigateToCreateOrder"
      >
        <wd-icon name="list" size="22px"></wd-icon>
        <text style="font-size: 24rpx; font-weight: 400">工单</text>
      </view>
    </view>
    <view class="Calendar-content">
      <day
        class="box-day"
        v-if="radioActive === '日'"
        @handletabs="handletabs"
        :overduedaylist="overduedaylist"
        :todoaskslist="todoaskslist"
        :selectedDate="selectedDate"
      />
      <week
        v-else-if="radioActive === '周'"
        :overduedaylist="overduedaylist"
        :todoaskslist="todoaskslist"
        :selectedDate="selectedDate"
      />
    </view>
    <Moon
      v-if="radioActive === '月'"
      :overduedaylist="overduedaylist"
      :todoaskslist="todoaskslist"
      :currentMonth="currentMonth"
    />
  </view>
</template>
<style lang="scss" scoped>
html,
body {
  overflow: hidden;
}
.box {
  width: 100%;
  height: calc(100vh - 100rpx);
  // height: 100vh;
  // position: relative;
  padding-top: 1px;
  overflow: hidden;
  .Calendar {
    width: 100%;
    position: fixed;
    z-index: 100;
    top: 118rpx;
    left: 0;
    background-color: white;
    border-radius: 18px;
    box-sizing: border-box;
    padding: 0 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    .Calendar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      > view:first-child {
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .Calendar-header-Radio {
        width: 308rpx;
        height: 64rpx;
        background-color: #f2f3f5;
        border-radius: 4px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 0 4px;
        .Calendar-header-Radio-text {
          flex: 1;
          text-align: center;
          font-size: 28rpx;
          font-weight: 400;
          height: 48rpx;
          line-height: 48rpx;
          border-radius: 4px;
          &.active {
            background-color: white;
            color: #1989fa;
          }
        }
      }
    }

    .Calendar-weekdays {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 5px;
      margin-bottom: 10px;

      .Calendar-weekday {
        width: 62rpx;
        height: 40rpx;
        text-align: center;
        font-size: 28rpx;
        font-weight: 500;
        color: #606266;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .Calendar-dates {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 5px;

      .Calendar-date {
        // flex: 1;
        width: 62rpx;
        height: 62rpx;
        text-align: center;
        font-size: 24rpx;
        font-weight: 500;
        padding: 2px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        &.Calendar-date-active {
          background-color: #215acd;
          color: white;
        }

        &.Calendar-date-other {
          color: #c0c4cc;
        }

        &.Calendar-date-selected {
          // border: 1px solid #409eff;
          color: #215ACD;
          background-color: #E6E8EB;
        }

        &.Calendar-date-disabled {
          color: #c0c4cc;
          pointer-events: none;
          cursor: not-allowed;
        }
      }
    }

    .Calendar-footer {
      text-align: center;
      margin-top: 15px;
      padding: 5px 0;
    }
  }
  .box-rigth-fixed {
    width: 96rpx;
    height: 364rpx;
    background-color: #ffffff;
    // border: 1px solid red;
    position: fixed;
    right: 16rpx;
    bottom: 8.625rem;
    z-index: 100;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    border: 1px solid #ebeef5;
    border-radius: 12px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    // align-items: center;
  }
  .Calendar-content {
    padding-top: 346rpx;
    // background-color: red;
    width: 100%;
    box-sizing: border-box;
  }

  .loading-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }
}
</style>
