<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">
            <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"
                  />
                </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"
                  />
                </a-space>
              </div>
              <div class="flex items-center">
                <div class="w-70px">账号名称</div>
                <a-input
                  v-model="query.name"
                  :style="{ width: '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" @click="handleMore(record, column)">
              <div
                :key="record[column.dataIndex][0].id"
                class="task-item size-12px"
                :title="record[column.dataIndex][0].name || '-'"
              >
                <div class="size-12px color-#211F24 mr-4px">
                  {{ timestampToTime(record[column.dataIndex][0].execution_time) }}
                </div>
                <div :style="{ color: getTaskColor(record[column.dataIndex][0].type) }">
                  {{ formatTaskName(record[column.dataIndex][0].name) }}{{ record[column.dataIndex][0].type }}
                </div>
              </div>
              <div class="size-12px color-#8f959f" style="padding: 0px 8px">
                还有{{ record[column.dataIndex].length - 1 }}项
              </div>
            </div>
            <div
              v-else
              v-for="task in record[column.dataIndex]"
              :key="task.id"
              class="task-item"
              :title="task.name || '-'"
            >
              <div class="size-12px color-#211F24 mr-4px">
                {{ timestampToTime(record[column.dataIndex][0].execution_time) }}
              </div>
              <div :style="{ color: getTaskColor(task.type) }">
                {{ formatTaskName(record[column.dataIndex][0].name) }}{{ record[column.dataIndex][0].type }}
              </div>
            </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 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]);
};

// 计算当前日期范围内的所有日期，统一返回 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) => {
  console.log('taskType', taskType);
  // 根据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(); // 返回数字类型的日期
};

// 时间戳转时间格式 (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);
        console.log('taskDay', taskDay, typeof taskDay);
        console.log('currentDateHeaders', currentDateHeaders.value);
        console.log('rowData', currentDateHeaders.value.includes(taskDay));
        // 如果这个日期在当前表头中，则添加到对应列
        if (currentDateHeaders.value.includes(taskDay)) {
          console.log('taskDay', task);
          rowData[taskDay].push({
            id: task.id,
            name: task.name,
            type: task.type,
            execution_time: task.execution_time,
          });
          console.log('taskDay', rowData[taskDay]);
        }
      });
    }

    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,
      fixed: 'left',
    },
  ];

  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;
  } else {
    // 日维度
    const date = new Date(dayModel.value);
    const day = date.getDate();
    const weekday = DateUtils.formatDateToWeekdayDay(date);
    dateHeaders = [{ day: day, weekday, date: DateUtils.formatDate(date) }];
  }

  // 添加日期列
  dateHeaders.forEach((item) => {
    columns.value.push({
      title: `${item.weekday}`,
      dataIndex: item.day, // 使用日期数字作为dataIndex
      slotName: 'dateCell',
      width: 135,
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    });
  });
};

// 日期变化处理（日维度）
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) => {
  console.log('onChangeWeek val', val);
  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);
    console.log('onChangeMonth val', val);
  }
  console.log('onChangeMonth val', 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;
  console.log('query', query);
  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) => {
      console.error('获取任务排期数据失败:', 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,
        label: 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;
  gap: 4px;
  padding: 4px 0;
}

.task-item {
  padding: 4px 8px;
  border-radius: 4px;
  color: white;
  line-height: 1.4;
  word-break: break-word;
  cursor: pointer;
  transition: opacity 0.2s;
  display: flex;
}

.task-item:hover {
  opacity: 0.8;
}

.no-task {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 8px 0;
}
.tip-trigger {
  background-color: #ffffff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  transition: background-color 0.3s;
  width: 100px;
  height: 80px;
}
.tip-trigger:hover {
  background-color: #f0f0f0;
}
</style>
