<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';

// @ts-ignore
import { Page, useVbenDrawer } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import {
  CaretLeft,
  CaretRight,
  Plus,
  Tickets,
  User,
} from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { ElCheckbox, ElRadioButton, ElRadioGroup } from 'element-plus';

import {
  addtodoaskslist,
  queryGasStationList,
  querytodoaskslist,
} from '#/api/schedule/index';

import CreateWorkOrder from './components/create/createworkorder.vue';
import CreateTasK from './components/create/index.vue';
import CreateVisitorTask from './components/create/visitortaskdraw.vue';
import Day from './components/day/index.vue';
// @ts-ignore
import Month from './components/month/index.vue';
// @ts-ignore
import Week from './components/week/index.vue';

const userStore = useUserStore();
// 根据timeType计算默认日期
const getDefaultDate = (type: string) => {
  switch (type) {
    case 'month': {
      return dayjs().format('YYYY-MM-DD');
    }
    case 'week': {
      return dayjs().format('YYYY-MM-DD');
    }
    default: {
      return dayjs().format('YYYY-MM-DD');
    }
  }
};
const gasstationlist = ref([]) as any;
const searchParams = ref({
  timeType: 'day',
  station: '',
  date: getDefaultDate('day'),
});

// 当前显示的日期
const currentDate = ref(dayjs()); // 时间对象包含时分秒
const currentDate2 = ref(dayjs()); // 单独给月份的时间
const daylist = ref([]);
const overduedaylist = ref([]);
// 主页面loading
const mainloing = ref(false);
// 抽屉loading
const drawerloing = ref(false);
// 访客任务抽屉loading
const VisitorTaskloing = ref(false);
// 当前选中的日期
const selectedDate = ref(''); // 当前选中的日期2026-01-16
// 任务授权状态
const checkList = ref([]);
// 0-未授权，1-已授权，2-被授权
const checkAll = ref([
  {
    label: '任务可授权',
    value: '0',
  },
  {
    label: '任务已授权',
    value: '1',
  },
  {
    label: '任务被授权',
    value: '2',
  },
]);
// 查询当前视图类型的数据
const queryCurrentViewData = async (timeType: string, userId: any) => {
  switch (timeType) {
    case 'day': {
      await querytodoaskslistfn({
        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'),
        authStatusStr: checkList.value.join(','),
        // status: '1',
      });

      break;
    }
    case 'month': {
      const monthStart = dayjs(currentDate.value).startOf('month');
      const monthEnd = dayjs(currentDate.value).endOf('month');
      await querytodoaskslistfn({
        showStartTime: monthStart.format('YYYY-MM-DD 00:00:00'),
        showEndTime: monthEnd.format('YYYY-MM-DD 23:59:59'),
        authStatusStr: checkList.value.join(','),
      });

      break;
    }
    case 'week': {
      const date = dayjs(selectedDate.value);
      const startOfWeek = date.startOf('week');
      const weekStart =
        startOfWeek.day() === 0 ? startOfWeek.subtract(1, 'day') : startOfWeek;
      const weekEnd = weekStart.add(6, 'day');
      await querytodoaskslistfn({
        showStartTime: weekStart.format('YYYY-MM-DD 00:00:00'),
        showEndTime: weekEnd.format('YYYY-MM-DD 23:59:59'),
        authStatusStr: checkList.value.join(','),
        userId,
      });

      break;
    }
    // No default
  }
  await queryoverduelistfn({
    authStatusStr: checkList.value.join(','),
  });
};
// 视图切换函数
const handleTimeTypeChange = async (val: any) => {
  if (val === 'day' || val === 'week') {
    selectedDate.value = searchParams.value.date;
  }
  await queryCurrentViewData(val, searchParams.value.station?.split('-')[0]);
};
// 切换油站方法
const handleStationChange = async (val: any) => {
  const userId = val.split('-')[0];
  // const stationId = val.split('-')[1];
  queryCurrentViewData(searchParams.value.timeType, userId);
};
// 当日和明日的任务列表
const querytodoaskslistfn = async ({
  showStartTime,
  showEndTime,
  authStatusStr,
}: any) => {
  mainloing.value = true;
  try {
    const stationId = searchParams.value.station.split('-')[1];
    const executorId = searchParams.value.station.split('-')[0];
    const res = await querytodoaskslist({
      showStartTime,
      showEndTime,
      authStatusStr,
      stationId,
      executorId,
      taskStatusStr: '0,1,3',
      // userId,
      // isOverdue: '0'
    });
    daylist.value = res || [];
  } catch (error) {
    console.error(error);
  } finally {
    mainloing.value = false;
  }
};
// 逾期任务列表
const queryoverduelistfn = async ({ authStatusStr }: any) => {
  mainloing.value = true;
  try {
    const stationId = searchParams.value.station.split('-')[1];
    const executorId = searchParams.value.station.split('-')[0];
    const res = await querytodoaskslist({
      authStatusStr,
      status: '2',
      executorId,
      stationId,
      showStartTime: dayjs(currentDate.value).format('YYYY-MM-DD 00:00:00'),
      showEndTime: dayjs(currentDate.value)
        .add(1, 'day')
        .format('YYYY-MM-DD 23:59:59'),
    });
    overduedaylist.value = res || [];
  } catch (error) {
    console.log(error);
  } finally {
    mainloing.value = false;
  }
};
// 查询加油站列表
const queryGasStationListfn = async () => {
  // mainloing.value = true;
  try {
    const res = await queryGasStationList({});
    gasstationlist.value = res || [];
  } catch (error) {
    console.log(error);
  } finally {
    // mainloing.value = false;
  }
};
// 处理创建任务的提交
const handleCreateTask = async (formData: any) => {
  drawerloing.value = true;
  try {
    await addtodoaskslist({
      ...formData,
      type: '1',
    });
    await querytodoaskslistfn({
      showStartTime: dayjs(currentDate.value).format('YYYY-MM-DD 00:00:00'),
      showEndTime: dayjs(currentDate.value)
        .add(1, 'day')
        .format('YYYY-MM-DD 23:59:59'),
      authStatusStr: checkList.value.join(','),
    });
    await queryoverduelistfn({
      authStatusStr: checkList.value.join(','),
    });
    createTaskDrawerApi.close();
  } catch (error) {
    console.error('任务创建失败:', error);
  } finally {
    drawerloing.value = false;
  }
};
// 处理创建访客任务的提交
const handleCreateVisitorTask = async (formData: any) => {
  VisitorTaskloing.value = true;
  try {
    await addtodoaskslist({
      ...formData,
      type: '1',
    });
    await querytodoaskslistfn({
      showStartTime: dayjs(currentDate.value).format('YYYY-MM-DD 00:00:00'),
      showEndTime: dayjs(currentDate.value)
        .add(1, 'day')
        .format('YYYY-MM-DD 23:59:59'),
      authStatusStr: checkList.value.join(','),
    });
    await queryoverduelistfn({
      authStatusStr: checkList.value.join(','),
    });
    createVisitorTaskDrawerApi.close();
  } catch (error) {
    console.error('任务创建失败:', error);
  } finally {
    VisitorTaskloing.value = false;
  }
};
onMounted(() => {
  queryGasStationListfn().then(() => {
    if (userStore.userInfo?.stations?.length) {
      searchParams.value.station = `${userStore.userInfo?.userId}-${userStore.userInfo?.stations[0]?.id}`;
    }

    queryCurrentViewData(
      searchParams.value.timeType,
      searchParams.value.station?.split('-')[0],
    );
  });
  selectedDate.value = searchParams.value.date;
});
// 处理复选框变化
const handleCheckChange = async () => {
  await queryCurrentViewData(
    searchParams.value.timeType,
    searchParams.value.station?.split('-')[0],
  );
};

// 监听timeType变化，更新默认日期和当前显示日期
watch(
  () => searchParams.value.timeType,
  (newType) => {
    searchParams.value.date = getDefaultDate(newType);
    currentDate.value = dayjs(searchParams.value.date);
    currentDate2.value = dayjs(searchParams.value.date); // 单独给月份的时间
    selectedDate.value =
      newType === 'day' || newType === 'week' ? searchParams.value.date : '';
  },
);

// 确保currentDate和currentDate2始终保持同步
watch(
  () => currentDate.value,
  (newDate) => {
    currentDate2.value = newDate;
  },
);
// 单独给月份的监听器
watch(
  () => currentDate2.value,
  (newDate) => {
    currentDate.value = newDate;
  },
);

// 计算年份和周数
const year = computed(() => {
  return dayjs(searchParams.value.date).year();
});

const weekNumber = computed(() => {
  // @ts-ignore
  return dayjs(searchParams.value.date).week();
});

// 计算当前选中日期所在周的开始和结束日期
const currentWeekRange = computed(() => {
  const date = dayjs(searchParams.value.date);
  // 计算周开始（周一）
  const startOfWeek = date.startOf('week');
  // 调整为周一（dayjs默认周日为一周开始）
  const monday =
    startOfWeek.day() === 0 ? startOfWeek.subtract(1, 'day') : startOfWeek;
  // 计算周日
  const sunday = monday.add(6, 'day');
  return {
    start: monday,
    end: sunday,
  };
});

// 生成日历天数
const calendarDays = computed(() => {
  const days = [];
  const year = currentDate.value.year();
  const month = currentDate.value.month();
  const today = dayjs().startOf('day');

  // 获取当月第一天
  const firstDay = dayjs(new Date(year, month, 1));
  // 获取当月第一天是星期几（0-6，0是周日）
  const firstDayOfWeek = firstDay.day();
  // 计算需要显示的上个月天数
  const prevMonthDays = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;

  // 获取当月最后一天
  const lastDay = dayjs(new Date(year, month + 1, 0));
  const lastDate = lastDay.date();

  // 添加上个月的日期
  for (let i = prevMonthDays; i > 0; i--) {
    const date = firstDay.subtract(i, 'day');
    const isInCurrentWeek =
      searchParams.value.timeType === 'week' &&
      date.isAfter(currentWeekRange.value.start.subtract(1, 'day')) &&
      date.isBefore(currentWeekRange.value.end.add(1, 'day'));
    const isDisabled =
      searchParams.value.timeType === 'day' && date.isBefore(today);
    days.push({
      date: date.format('YYYY-MM-DD'),
      day: date.date(),
      isToday: date.isSame(dayjs(), 'day'),
      isOtherMonth: true,
      isInCurrentWeek,
      isDisabled,
    });
  }

  // 添加当月的日期
  for (let i = 1; i <= lastDate; i++) {
    const date = dayjs(new Date(year, month, i));
    const isInCurrentWeek =
      searchParams.value.timeType === 'week' &&
      date.isAfter(currentWeekRange.value.start.subtract(1, 'day')) &&
      date.isBefore(currentWeekRange.value.end.add(1, 'day'));
    const isDisabled =
      searchParams.value.timeType === 'day' && date.isBefore(today);
    days.push({
      date: date.format('YYYY-MM-DD'),
      day: i,
      isToday: date.isSame(dayjs(), 'day'),
      isOtherMonth: false,
      isInCurrentWeek,
      isDisabled,
    });
  }

  // 计算需要显示的下个月天数
  const totalDays = days.length;
  const nextMonthDays = 42 - totalDays; // 6行7列=42个格子

  // 添加下个月的日期
  for (let i = 1; i <= nextMonthDays; i++) {
    const date = lastDay.add(i, 'day');
    const isInCurrentWeek =
      searchParams.value.timeType === 'week' &&
      date.isAfter(currentWeekRange.value.start.subtract(1, 'day')) &&
      date.isBefore(currentWeekRange.value.end.add(1, 'day'));
    const isDisabled =
      searchParams.value.timeType === 'day' && date.isBefore(today);
    days.push({
      date: date.format('YYYY-MM-DD'),
      day: date.date(),
      isToday: date.isSame(dayjs(), 'day'),
      isOtherMonth: true,
      isInCurrentWeek,
      isDisabled,
    });
  }

  return days;
});

// 切换到上个月
const prevMonth = async () => {
  currentDate.value = currentDate.value.subtract(1, 'month');
  currentDate2.value = currentDate2.value.subtract(1, 'month');
  if (searchParams.value.timeType === 'month') {
    await queryCurrentViewData(
      searchParams.value.timeType,
      searchParams.value.station?.split('-')[0],
    );
  }
};
// 切换到下个月
const nextMonth = async () => {
  currentDate.value = currentDate.value.add(1, 'month');
  currentDate2.value = currentDate2.value.add(1, 'month');
  if (searchParams.value.timeType === 'month') {
    await queryCurrentViewData(
      searchParams.value.timeType,
      searchParams.value.station?.split('-')[0],
    );
  }
};

// 选择日期
const selectDate = async (date: string) => {
  searchParams.value.date = date;
  selectedDate.value = date;
  currentDate.value = dayjs(date);
  currentDate2.value = dayjs(date);
  if (searchParams.value.timeType !== 'month') {
    await queryCurrentViewData(
      searchParams.value.timeType,
      searchParams.value.station?.split('-')[0],
    );
  }
  // let showStartTime, showEndTime;
  // const currentType = searchParams.value.timeType;
  // const selectedDateObj = dayjs(date);
  // if (currentType === 'day') {
  //   // 日视图：查询选中日期当天的数据
  //   showStartTime = selectedDateObj.format('YYYY-MM-DD 00:00:00');
  //   showEndTime = selectedDateObj.add(1, 'day').format('YYYY-MM-DD 23:59:59');
  //   await querytodoaskslistfn({
  //     showStartTime,
  //     showEndTime,
  //     authStatusStr: checkList.value.join(','),
  //     userId: searchParams.value.station?.split('-')[0],
  //   });
  // } else if (currentType === 'week') {
  //   // 周视图：查询选中日期所在周的数据（周一到周日）
  //   const startOfWeek = selectedDateObj.startOf('week');
  //   const weekStart = startOfWeek.day() === 0 ? startOfWeek.subtract(1, 'day') : startOfWeek;
  //   const weekEnd = weekStart.add(6, 'day');
  //   showStartTime = weekStart.format('YYYY-MM-DD 00:00:00');
  //   showEndTime = weekEnd.format('YYYY-MM-DD 23:59:59');
  //   await querytodoaskslistfn({
  //     showStartTime,
  //     showEndTime,
  //     authStatusStr: checkList.value.join(','),
  //     userId: searchParams.value.station?.split('-')[0],
  //   });
  // }
};
// 新增油站任务抽屉
const [CreateTaskDrawer, createTaskDrawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: CreateTasK,
  // placement: 'left',
});
// 新增访客任务抽屉
const [CreateVisitorTaskDrawer, createVisitorTaskDrawerApi] = useVbenDrawer({
  connectedComponent: CreateVisitorTask,
});
// 工单提报
const [CreateWorkOrderDrawer, createWorkOrderDrawerApi] = useVbenDrawer({
  connectedComponent: CreateWorkOrder,
});
const createTaskDrawerEvent = () => {
  createTaskDrawerApi.setData({ isUpdate: false }).open();
};
// 新增访客任务抽屉
const createVisitorTaskDrawerEvent = () => {
  createVisitorTaskDrawerApi.setData({ isUpdate: false }).open();
};
// 工单提报
const createWorkOrderDrawerEvent = () => {
  createWorkOrderDrawerApi.setData({ isUpdate: false }).open();
};
</script>

<template>
  <Page
    style="height: 100%"
    title=""
    :auto-content-height="true"
    class="h-screen"
  >
    <div class="flex h-full min-h-0 flex-row space-x-4">
      <!--左侧筛选区域-->
      <div
        class="relative flex h-full w-80 flex-shrink-0 flex-col rounded-lg bg-white shadow"
      >
        <div class="flex-1 overflow-y-auto p-4">
          <!--油站选择-->
          <div class="mb-4">
            <ElSelect
              v-model="searchParams.station"
              @change="handleStationChange"
              filterable
              placeholder="请选择油站"
              class="w-full"
            >
              <ElOption
                v-for="item in gasstationlist"
                :key="`${item.userId}-${item.stationId}`"
                :label="`${item.nickName}-${item.stationName}`"
                :value="`${item.userId}-${item.stationId}`"
              />
            </ElSelect>
          </div>

          <!--日期导航和视图切换-->
          <div class="mb-4">
            <div class="flex items-center justify-between">
              <!--时间筛选靠左-->
              <div class="flex items-center space-x-2">
                <el-icon><CaretLeft @click="prevMonth" /></el-icon>
                <span class="font-medium">{{
                  currentDate.format('YYYY年 M月')
                }}</span>
                <el-icon><CaretRight @click="nextMonth" /></el-icon>
              </div>

              <!--视图切换靠右-->
              <ElRadioGroup
                v-model="searchParams.timeType"
                @change="handleTimeTypeChange"
                size="small"
                class="custom-radio-group"
              >
                <ElRadioButton label="day" class="custom-radio-btn">
                  日
                </ElRadioButton>
                <ElRadioButton label="week" class="custom-radio-btn">
                  周
                </ElRadioButton>
                <ElRadioButton label="month" class="custom-radio-btn">
                  月
                </ElRadioButton>
              </ElRadioGroup>
            </div>

            <!--日历显示-->
            <div class="calendar-container mt-1">
              <!--星期标题-->
              <div class="mb-1 flex justify-between text-xs text-gray-500">
                <div class="w-7 text-center">一</div>
                <div class="w-7 text-center">二</div>
                <div class="w-7 text-center">三</div>
                <div class="w-7 text-center">四</div>
                <div class="w-7 text-center">五</div>
                <div class="w-7 text-center">六</div>
                <div class="w-7 text-center">日</div>
              </div>

              <!--日期网格-->
              <div class="grid grid-cols-7 gap-1">
                <div
                  v-for="day in calendarDays"
                  :key="day.date"
                  :style="
                    day.date === '2025-12-22' || day.date === '2025-12-23'
                      ? 'background-color: #FFE6E0'
                      : day.isInCurrentWeek && !day.isToday
                        ? 'background-color: #409EFF;color: #fff'
                        : ''
                  "
                  class="flex h-7 w-7 items-center justify-center rounded text-xs"
                  :class="{
                    'bg-blue-600 text-white': day.isToday,
                    'cursor-pointer bg-gray-200':
                      day.date === selectedDate &&
                      !day.isToday &&
                      !day.isDisabled,
                    'bg-gray-100 text-gray-400': day.isOtherMonth,
                    'cursor-not-allowed bg-gray-100 text-gray-400':
                      day.isDisabled,
                    'cursor-pointer': !day.isDisabled,
                  }"
                  @click="!day.isDisabled && selectDate(day.date)"
                >
                  {{ day.day }}
                </div>
              </div>
            </div>
          </div>

          <!--任务授权状态-->
          <div class="mb-4">
            <div class="mb-2 font-medium">任务授权状态：</div>
            <div
              class="space-y-1"
              style="display: flex; flex-direction: column"
            >
              <el-checkbox-group
                @change="handleCheckChange"
                v-model="checkList"
                style="display: flex; flex-direction: column; gap: 8px"
              >
                <ElCheckbox
                  v-for="value in checkAll"
                  :key="value.value"
                  :label="value.label"
                  :value="value.value"
                />
              </el-checkbox-group>
            </div>
          </div>

          <!-- <div style="width: 50px;height: 50px; background-color: #339169;"></div> -->

          <div style="display: flex; flex-direction: column; gap: 12px">
            <div style="color: #409eff">蓝色任务：任务可处理</div>
            <div style="color: #67c23a">绿色任务：任务已完成</div>
            <div style="color: #e6a23c">黄色任务：即将到期任务</div>
            <div style="color: #909399">灰色任务：任务未开始/任务取消</div>
            <div style="color: #f56c6c">红色任务：任务过期未完成</div>
          </div>
        </div>
        <!--新增任务按钮固定在底部-->
        <div class="p-4">
          <div class="space-y-2">
            <ElButton
              type="primary"
              class="w-full"
              v-access:code="'schedule:view:addstationtask'"
              @click="createTaskDrawerEvent"
            >
              <template #icon>
                <el-icon><Plus /></el-icon>
              </template>
              场站新增任务
            </ElButton>
          </div>
          <div class="mt-1 space-y-2">
            <ElButton
              type="default"
              class="w-full"
              v-access:code="'schedule:view:addvisittask'"
              @click="createVisitorTaskDrawerEvent"
            >
              <template #icon>
                <el-icon><User /></el-icon>
              </template>
              访客新增任务
            </ElButton>
          </div>
          <div class="mt-1 space-y-2">
            <ElButton
              type="default"
              class="w-full"
              v-access:code="'schedule:view:addworktask'"
              @click="createWorkOrderDrawerEvent"
            >
              <template #icon>
                <el-icon><Tickets /></el-icon>
              </template>
              工单提报
            </ElButton>
          </div>
        </div>
      </div>

      <!--右侧内容区域-->
      <div class="flex h-full min-h-0 flex-1 flex-col">
        <ElCard class="flex h-full w-full flex-col">
          <div
            class="min-h-0 flex-1 overflow-y-auto"
            style="max-height: calc(100vh - 120px)"
            v-loading="mainloing"
          >
            <Day
              v-if="searchParams.timeType === 'day'"
              :daylist="daylist"
              :overduedaylist="overduedaylist"
              :selected-date="selectedDate"
            />
            <Week
              v-if="searchParams.timeType === 'week'"
              :daylist="daylist"
              :overduedaylist="overduedaylist"
              :year="year"
              :week-number="weekNumber"
            />
            <Month
              v-if="searchParams.timeType === 'month'"
              :daylist="daylist"
              :overduedaylist="overduedaylist"
              :month="currentDate"
            />
          </div>
        </ElCard>
      </div>
    </div>
    <!-- 1油站新增 2访客新增 -->
    <CreateTaskDrawer @submit="handleCreateTask" :drawerloing="drawerloing" />
    <CreateVisitorTaskDrawer
      @submit="handleCreateVisitorTask"
      :VisitorTaskloing="VisitorTaskloing"
    />
    <CreateWorkOrderDrawer />
  </Page>
</template>
<style scoped lang="scss">
// :deep(.el-card) {
//   border: none !important;
//   box-shadow: none !important;
//   background: transparent !important;
// }

:deep(.custom-radio-group .el-radio-button) {
  padding: 4px;
  // background: transparent !important;
  background-color: #fafafa !important;
  border: none !important;
}

:deep(.custom-radio-group .el-radio-button__inner) {
  padding: 0 8px;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.custom-radio-group .el-radio-button__inner:hover) {
  color: #1890ff !important;
  background: transparent !important;
}

:deep(.custom-radio-group .el-radio-button.is-active .el-radio-button__inner) {
  color: #1890ff !important;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}
</style>
