<template>
  <div class="flex-column justify-between">
    <div class="flex justify-between items-start" style="width: 100%">
      <div class="flex justify-between items-center" style="width: 100%">
        <div class="flex items-center">
          <a-date-picker
            class="w-188px size-14px"
            v-if="choseType === '日'"
            @change="onChangeDate"
            v-model="dayModel"
            format="YYYY年MM月DD日周dd"
          />
          <a-week-picker
            class="w-188px size-14px"
            v-else-if="choseType === '周'"
            @change="onChangeWeek"
            v-model="weekModel"
            format="YYYY年MM月DD日"
          />
          <a-month-picker
            class="w-188px size-14px"
            v-else
            @change="onChangeMonth"
            v-model="monthModel"
            format="YYYY年MM月"
          />
          <div class="flex items-center ml-12px">
            <a-button class="mr-4px" @click="handlePrev">
              <template #icon>
                <icon-left />
              </template>
            </a-button>

            <a-button @click="handleToday">今天</a-button>
            <a-button class="ml-4px" @click="handleNext">
              <template #icon>
                <icon-right />
              </template>
            </a-button>
          </div>
          <div class="flex items-center ml-12px">
            <a-space class="flex justify-between">
              <a-dropdown position="bottom" @select="handleSelect">
                <a-button class="w-80px flex justify-between">{{ choseType }}<icon-down /></a-button>
                <template #content>
                  <a-doption value="日" class="w-80px">日</a-doption>
                  <a-doption value="周" class="w-80px">周</a-doption>
                  <a-doption value="月" class="w-80px">月</a-doption>
                </template>
              </a-dropdown>
            </a-space>
          </div>
        </div>
      </div>
      <div class="flex items-start">
        <a-trigger
          trigger="click"
          style="
            background-color: #ffffff;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            box-shadow: #00000010 0px 2px 8px;
            width: 120px;
            height: 64px;
            padding: 8px;
            margin-top: 8px;
          "
        >
          <a-button size="small" class="mr-12px color-scheme-btn" :bordered="false">
            <template #icon>
              <icon-info-circle-fill size="16" class="color-#55585F" />
            </template>
            <template #default>颜色示意</template>
          </a-button>
          <template #content>
            <div class="flex items-center mb-8px">
              <div
                style="background-color: #6d4cfe; width: 16px; height: 16px; margin-right: 5px; border-radius: 4px"
              ></div>
              <div>选题</div>
            </div>
            <div class="flex items-center">
              <div
                style="background-color: #ffae00; width: 16px; height: 16px; margin-right: 5px; border-radius: 4px"
              ></div>
              <div>内容稿件</div>
            </div>
          </template>
        </a-trigger>

        <a-trigger
          trigger="click"
          style="
            background-color: #ffffff;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            box-shadow: #00000010 0px 2px 8px;
            width: 308px;
            height: 180px;
            padding: 24px;
            margin-top: 8px;
          "
        >
          <a-button size="small">
            <template #icon>
              <icon-filter size="16" class="color-#55585F" />
            </template>
            <template #default>筛选</template>
          </a-button>
          <template #content>
            <div>
              <div class="flex items-center mb-24px">
                <div class="w-70px">运营人员</div>
                <a-space class="w-200px">
                  <CommonSelect
                    :multiple="false"
                    :options="operators"
                    v-model="query.operator_id"
                    @change="handleSearch"
                    class="!w-200px"
                  />
                </a-space>
              </div>
              <div class="flex items-center mb-24px">
                <div class="w-70px">发布平台</div>
                <a-space class="w-200px">
                  <CommonSelect
                    :multiple="false"
                    :options="platformOptions"
                    v-model="query.platform"
                    @change="handleSearch"
                    class="!w-200px"
                  />
                </a-space>
              </div>
              <div class="flex items-center">
                <div class="w-70px">账号名称</div>
                <a-input
                  v-model="query.name"
                  class="!w-200px"
                  placeholder="输入账号名称"
                  @change="handleSearch"
                />
              </div>
            </div>
          </template>
        </a-trigger>
      </div>
    </div>
    <div class="flex justify-between items-start mt-16px" style="width: 100%">
      <a-table :columns="columns" :data="data" :bordered="{ cell: true }" style="width: 100%" :pagination="false">
        <template #name="{ record }">
          <div class="flex items-center">
            <img
              :src="getPlatformIcon(record.platform)"
              style="border-radius: 8px; width: 16px; height: 16px; margin-right: 8px"
            />
            {{ record.name || '-' }}
          </div>
        </template>

        <!-- 动态日期列渲染 -->
        <template #dateCell="{ record, column }">
          <div v-if="record[column.dataIndex] && record[column.dataIndex].length > 0" class="task-container">
            <div v-if="record[column.dataIndex].length >= 3" class="task-more">
              <div
                :key="record[column.dataIndex][0].id"
                class="task-item size-12px"
                :title="record[column.dataIndex][0].name || '-'"
              >
                <a-trigger trigger="click" position="br">
                  <div class="task-item size-12px">
                    <div class="size-12px color-#211F24 mr-4px">
                      {{ timestampToTime(record[column.dataIndex][0].execution_time) }}
                    </div>
                    <div
                      class="size-12px"
                      :style="{
                        color: getTaskColor(
                          record[column.dataIndex][0].type,
                          record[column.dataIndex][0].execution_time,
                        ),
                      }"
                      style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
                    >
                      {{ formatTaskName(record[column.dataIndex][0].name) }}
                    </div>
                  </div>
                  <template #content>
                    <div class="flex flex-col items-start cell-detail">
                      <div class="flex items-center">
                        <img
                          :src="getPlatformIcon(record.platform)"
                          style="border-radius: 8px; width: 16px; height: 16px; margin-right: 8px; font-size: 14px"
                        />
                        {{ record.name || '-' }}
                      </div>
                      <div class="size-12px color-#939499 mt-2px">
                        {{ timestampToTime1(record[column.dataIndex][0].execution_time) }}
                      </div>
                      <div class="size-14px color-#211F24 mt-12px">
                        {{ record[column.dataIndex][0].name || '未命名' }}
                      </div>
                      <div class="flex items-center mt-12px">
                        <div class="opt-btn">修改发布时间</div>
                        <div class="opt-btn" style="margin-right: 0px">删除</div>
                      </div>
                    </div>
                  </template>
                </a-trigger>
              </div>
              <a-trigger trigger="click" position="br">
                <div class="size-12px color-#8f959f" style="padding: 0px 8px">
                  还有{{ record[column.dataIndex].length - 1 }}项
                </div>
                <template #content>
                  <div
                    class="flex flex-col items-start"
                    style="background-color: #fff; padding: 12px; box-shadow: #00000010 0px 2px 8px; border-radius: 4px"
                  >
                    <div v-for="task in record[column.dataIndex]" :key="task.id" :title="task.name || '-'">
                      <a-trigger trigger="click" align-point>
                        <div class="flex items-start mb-8px">
                          <div class="size-12px color-#211F24 mr-4px">
                            {{ timestampToTime(task.execution_time) }}
                          </div>
                          <div class="size-12px" :style="{ color: getTaskColor(task.type, task.execution_time) }">
                            {{ task.name || '未命名' }}
                          </div>
                        </div>
                        <template #content>
                          <div class="flex flex-col items-start cell-detail">
                            <div class="flex items-center">
                              <img
                                :src="getPlatformIcon(record.platform)"
                                style="
                                  border-radius: 8px;
                                  width: 16px;
                                  height: 16px;
                                  margin-right: 8px;
                                  font-size: 14px;
                                "
                              />
                              {{ record.name || '-' }}
                            </div>
                            <div class="size-12px color-#939499 mt-2px">
                              {{ timestampToTime1(task.execution_time) }}
                            </div>
                            <div class="size-14px color-#211F24 mt-12px">{{ task.name || '未命名' }}</div>
                            <div class="flex items-center mt-12px">
                              <div class="opt-btn">修改发布时间</div>
                              <div class="opt-btn" style="margin-right: 0px">删除</div>
                            </div>
                          </div>
                        </template>
                      </a-trigger>
                    </div>
                  </div>
                </template>
              </a-trigger>
            </div>
            <div v-else v-for="task in record[column.dataIndex]" :key="task.id" :title="task.name || '-'">
              <a-trigger trigger="click" align-point>
                <div class="task-item">
                  <div class="size-12px color-#211F24 mr-4px">
                    {{ timestampToTime(task.execution_time) }}
                  </div>
                  <div
                    :style="{ color: getTaskColor(task.type, task.execution_time) }"
                    style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
                  >
                    {{ formatTaskName(task.name) }}
                  </div>
                </div>
                <template #content>
                  <div class="flex flex-col items-start cell-detail">
                    <div class="flex items-center">
                      <img
                        :src="getPlatformIcon(record.platform)"
                        style="border-radius: 8px; width: 16px; height: 16px; margin-right: 8px; font-size: 14px"
                      />
                      {{ record.name || '-' }}
                    </div>
                    <div class="size-12px color-#939499 mt-2px">
                      {{ timestampToTime1(task.execution_time) }}
                    </div>
                    <div class="size-14px color-#211F24 mt-12px">{{ task.name || '未命名' }}</div>
                    <div class="flex items-center mt-12px">
                      <div class="opt-btn">修改发布时间</div>
                      <div class="opt-btn" style="margin-right: 0px">删除</div>
                    </div>
                  </div>
                </template>
              </a-trigger>
            </div>
          </div>
          <div v-else class="no-task"></div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue';
import type { TableColumnData } from '@arco-design/web-vue';
import { getTaskSchedules } from '@/api/all/assignment-management';
import { fetchAccountOperators } from '@/api/all/propertyMarketing';

import icon1 from '@/assets/img/platform/icon-dy.png';
import icon2 from '@/assets/img/platform/icon-xhs.png';
import icon3 from '@/assets/img/media-account/icon-warn.png';
import icon4 from '@/assets/img/platform/icon-sph.png';
import icon5 from '@/assets/img/platform/icon-wb.png';
import icon6 from '@/assets/img/platform/icon-gzh.png';
import icon7 from '@/assets/img/platform/icon-ks.png';
import icon8 from '@/assets/img/platform/icon-bilibili.png';
import DateUtils from '@/utils/DateUtils';

const visible = ref(false);
const modalVisible = ref(false);
const selectedTask = ref<any>(null);

const choseType = ref('周');
const dayModel = ref(new Date());
const weekModel = ref(new Date());
const monthModel = ref(new Date());
const currentDateRange = reactive({
  start: '',
  end: '',
});
const columns = ref<TableColumnData[]>([]);
const data = ref<any[]>([]);
const operators = ref([]);
const platformOptions = ref([
  { value: 0, label: '抖音' },
  { value: 1, label: '小红书' },
  { value: 2, label: 'B站' },
  { value: 3, label: '快手' },
  { value: 4, label: '视频号' },
  { value: 5, label: '微博' },
  { value: 6, label: '公众号' },
]);

const pageInfo = reactive({
  page: 1,
  page_size: 10,
  total: 0,
});

const query = reactive({
  page: 1,
  page_size: 20,
  platform: '',
  operator_id: undefined,
  name: '',
  execution_time: [] as string[],
});

// 显示所有的
const handleMore = (record: any, column: any) => {
  console.log('record', record);
  console.log('column', column);
  console.log('data', record[column.dataIndex]);
};

const handleCell = (record: any, column: any, task: any) => {
  selectedTask.value = {
    ...task,
    platform: record.platform,
    accountName: record.name,
  };
  modalVisible.value = true;
  console.log('data', record[column.dataIndex]);
};

// 计算当前日期范围内的所有日期，统一返回 number 数组
const currentDateHeaders = computed(() => {
  if (choseType.value === '周') {
    const specificWeek = DateUtils.getWeekDaysByDate(new Date(weekModel.value), 0);
    return specificWeek.map((item) => parseInt(item.day.toString(), 10)); // 转换为数字数组
  } else if (choseType.value === '月') {
    const date = new Date(monthModel.value);
    const tabTitle = DateUtils.getDaysAndWeekdays(date.getFullYear(), date.getMonth());
    return tabTitle.map((item) => parseInt(item.day.toString(), 10)); // 转换为数字数组
  } else {
    // 日维度，返回当天的日期数字
    const day = new Date(dayModel.value).getDate();
    return [day];
  }
});

// 获取平台图标
const getPlatformIcon = (platform: number) => {
  const platformIcons: Record<number, any> = {
    0: icon1, // 抖音
    1: icon2, // 小红书
    2: icon8, // B站
    3: icon7, // 快手
    4: icon4, // 视频号
    5: icon5, // 微博
    6: icon6, // 公众号
  };

  return platformIcons[platform] || icon3; // 默认图标
};

// 获取任务颜色
const getTaskColor = (taskType: number, executionTime: number) => {
  // 判断任务是否已过期
  const isExpired = executionTime * 1000 < Date.now();
  // 如果已过期，根据任务类型返回对应颜色
  if (isExpired) {
    return taskType === 0 ? '#A794FE' : '#FFCF66';
  }

  // 未过期，根据API文档，type: 0=选题，1=内容稿件
  return taskType === 0 ? '#6d4cfe' : '#ffae00';
};

// 格式化任务名称
const formatTaskName = (name: string) => {
  if (!name) return '未命名';
  return name.length > 8 ? name.substring(0, 8) + '...' : name;
};

// 时间戳转日期格式，并提取日期数字
const timestampToDayNumber = (timestamp: number) => {
  const date = new Date(timestamp * 1000); // 假设时间戳是秒级
  return date.getDate(); // 返回数字类型的日期
};

// 时间戳转时间格式 (MM月DD HH:MM)
const timestampToTime1 = (timestamp: number): string => {
  const date = new Date(timestamp * 1000); // 假设时间戳是秒级
  // 获取月份和日期（注意：月份从0开始，需要+1）
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');

  return `${month}月${day} ${hours}:${minutes}`;
};

// 时间戳转时间格式 (HH:MM)
const timestampToTime = (timestamp: number): string => {
  const date = new Date(timestamp * 1000); // 假设时间戳是秒级

  // 获取小时和分钟
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');

  return `${hours}:${minutes}`;
};

// 处理表格数据，使其与动态表头匹配
const processTableData = (apiData: any[]) => {
  const processedData: any[] = [];

  // 处理每条账号数据
  apiData.forEach((account) => {
    const rowData: any = {
      id: account.id,
      name: account.name,
      platform: account.platform,
    };

    // 初始化所有日期列为空数组
    currentDateHeaders.value.forEach((day) => {
      rowData[day] = [];
    });

    // 将任务按日期分组
    if (account.task_schedules && account.task_schedules.length > 0) {
      account.task_schedules.forEach((task: any) => {
        const taskDay = timestampToDayNumber(task.execution_time);
        // 如果这个日期在当前表头中，则添加到对应列
        if (currentDateHeaders.value.includes(taskDay)) {
          rowData[taskDay].push({
            id: task.id,
            name: task.name,
            type: task.type,
            execution_time: task.execution_time,
          });
        }
      });
    }

    processedData.push(rowData);
  });

  return processedData;
};

// 设置日期范围
const setDateRange = () => {
  if (choseType.value === '周') {
    const weekRange = DateUtils.getWeekRangeByDate(new Date(weekModel.value));
    currentDateRange.start = weekRange.startFormatted;
    currentDateRange.end = weekRange.endFormatted;
    query.execution_time = [currentDateRange.start, currentDateRange.end];
  } else if (choseType.value === '月') {
    const monthRange = DateUtils.getMonthRangeByYearMonth(
      new Date(monthModel.value).getFullYear(),
      new Date(monthModel.value).getMonth() + 1,
    );
    currentDateRange.start = monthRange.startFormatted;
    currentDateRange.end = monthRange.endFormatted;
    query.execution_time = [currentDateRange.start, currentDateRange.end];
  } else {
    // 日维度
    const date = new Date(dayModel.value);
    currentDateRange.start = DateUtils.formatDate(date);
    currentDateRange.end = DateUtils.formatDate(date);
    query.execution_time = [currentDateRange.start, currentDateRange.end];
  }
};

// 设置table的头部
const setTableSpecific = () => {
  columns.value = [
    {
      title: '账号与发布平台',
      slotName: 'name',
      width: 150,
      ellipsis: true,
      tooltip: true,
    },
  ];

  let dateHeaders: any[] = [];

  if (choseType.value === '周') {
    const specificWeek = DateUtils.getWeekDaysByDate(new Date(weekModel.value), 0);
    dateHeaders = specificWeek;
  } else if (choseType.value === '月') {
    const date = new Date(monthModel.value);
    const tabTitle = DateUtils.getDaysAndWeekdays(date.getFullYear(), date.getMonth());
    // 为月视图添加日期对象，以便后续判断是否为周末
    dateHeaders = tabTitle.map((item) => {
      const dayDate = new Date(date.getFullYear(), date.getMonth(), item.day);
      return {
        ...item,
        date: dayDate,
      };
    });
  } else {
    // 日维度
    const date = new Date(dayModel.value);
    const day = date.getDate();
    const weekday = DateUtils.formatDateToWeekdayDay(date);
    dateHeaders = [{ day: day, weekday, date: date }];
  }

  // 添加日期列
  dateHeaders.forEach((item) => {
    // 检查是否为周末（周日为0，周六为6）
    const isWeekend = item.date ? item.date.getDay() === 0 || item.date.getDay() === 6 : false;

    columns.value.push({
      title: `${item.weekday}`,
      dataIndex: item.day, // 使用日期数字作为dataIndex
      slotName: 'dateCell',
      width: 135,
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      // 如果是周末，添加自定义样式
      cellClass: isWeekend ? 'weekend-column' : '',
    });
  });
};

// 日期变化处理（日维度）
const onChangeDate = (val: any) => {
  if (val) {
    // 确保val是Date对象
    const selectedDate = val instanceof Date ? val : new Date(val);
    dayModel.value = selectedDate;

    // 更新日期范围和其他相关状态
    setDateRange();
    setTableSpecific();

    // 在下一个tick中执行搜索，确保DOM更新完成
    nextTick(() => {
      handleSearch();
    });
  }
};

// 日期变化处理（周维度）
const onChangeWeek = (val: any) => {
  if (val) {
    // 确保val是Date对象
    const selectedDate = val instanceof Date ? val : new Date(val);
    weekModel.value = selectedDate;

    // 更新日期范围和其他相关状态
    setDateRange();
    setTableSpecific();

    // 在下一个tick中执行搜索，确保DOM更新完成
    nextTick(() => {
      handleSearch();
    });
  }
};

const onChangeMonth = (val: any) => {
  if (typeof val === 'string') {
    val = DateUtils.MonthStrToDate(val);
  }
  if (val) {
    // 确保val是Date对象
    const selectedDate = val instanceof Date ? val : new Date(val);
    monthModel.value = selectedDate;

    // 更新日期范围和其他相关状态
    setDateRange();
    setTableSpecific();

    // 在下一个tick中执行搜索，确保DOM更新完成
    nextTick(() => {
      handleSearch();
    });
  }
};

// 设置维度
const handleSelect = (val: string) => {
  choseType.value = val;
  setDateRange();
  setTableSpecific();
  nextTick(() => {
    handleSearch();
  });
};

// 日期导航
const handlePrev = () => {
  // 根据当前维度向前导航
  if (choseType.value === '周') {
    const prevWeek = new Date(weekModel.value);
    prevWeek.setDate(prevWeek.getDate() - 7);
    onChangeWeek(prevWeek);
  } else if (choseType.value === '月') {
    const prevMonth = new Date(monthModel.value);
    prevMonth.setMonth(prevMonth.getMonth() - 1);
    onChangeMonth(prevMonth);
  } else {
    const prevDay = new Date(dayModel.value);
    prevDay.setDate(prevDay.getDate() - 1);
    onChangeDate(prevDay);
  }
};

const handleNext = () => {
  // 根据当前维度向后导航
  if (choseType.value === '周') {
    const nextWeek = new Date(weekModel.value);
    nextWeek.setDate(nextWeek.getDate() + 7);
    onChangeWeek(nextWeek);
  } else if (choseType.value === '月') {
    const nextMonth = new Date(monthModel.value);
    nextMonth.setMonth(nextMonth.getMonth() + 1);
    onChangeMonth(nextMonth);
  } else {
    const nextDay = new Date(dayModel.value);
    nextDay.setDate(nextDay.getDate() + 1);
    onChangeDate(nextDay);
  }
};

const handleToday = () => {
  // 回到今天
  const today = new Date();
  if (choseType.value === '周') {
    onChangeWeek(today);
  } else if (choseType.value === '月') {
    onChangeMonth(today);
  } else {
    onChangeDate(today);
  }
};

// 获取数据
const handleSearch = () => {
  query.page = pageInfo.page;
  query.page_size = pageInfo.page_size;
  getTaskSchedules(query)
    .then((response) => {
      if (response.data) {
        // 根据API响应结构调整
        const apiData = response.data.data || response.data;
        data.value = processTableData(apiData);
        pageInfo.total = response.data.total || apiData.length;
      }
    })
    .catch((error) => {
      data.value = [];
    });
};

// 获取运营人员
const getOperators = async () => {
  try {
    const { code, data: operatorsData } = await fetchAccountOperators();
    if (code === 200) {
      operators.value = operatorsData.map((op: any) => ({
        value: op.id,
        name: op.name,
      }));
    }
  } catch (error) {
    console.error('获取运营人员数据失败:', error);
  }
};

// 监听日期维度变化
watch(choseType, (newVal) => {
  // 重置对应模型的值为当前日期
  const now = new Date();
  if (newVal === '日') {
    dayModel.value = now;
  } else if (newVal === '周') {
    weekModel.value = now;
  } else if (newVal === '月') {
    monthModel.value = now;
  }
  nextTick(() => {
    setDateRange();
    setTableSpecific();
    handleSearch();
  });
});

onMounted(() => {
  setDateRange();
  setTableSpecific();
  handleSearch();
  getOperators();
});
</script>

<style scoped>
.content {
  background: white;
  width: 100%;
  height: 600px;
  padding: 12px;
}

.arco-dropdown-open .arco-icon-down {
  transform: rotate(180deg);
}

.task-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.task-item {
  display: flex;
  align-items: center;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.task-more {
  display: flex;
  flex-direction: column;
  cursor: pointer;
}

.no-task {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 周末列背景色 */
:deep(.weekend-column) {
  background-color: #fbfaff !important;
}

/* 颜色示意按钮样式 */
:deep(.color-scheme-btn) {
  border: none !important;
  background: none !important;
  box-shadow: none !important;
}

.cell-detail {
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  box-shadow: #00000010 0px 2px 8px;
  padding: 8px 16px;
  margin-top: 8px;
}
.opt-btn {
  font-size: 12px;
  width: 138px;
  height: 28px;
  background-color: #f2f3f5;
  text-align: center;
  line-height: 28px;
  border-radius: 4px;
  margin-right: 12px;
}
</style>
