<template>
  <div class="flex flex-col justify-between bg-white rounded-8px p-24px">
    <!-- 日期选择器和筛选区域 -->
    <div class="flex justify-between items-start w-full mb-24px">
      <DateSelector v-model="dateSelectorModel" @date-change="handleDateSelectorChange" />
      <div class="flex items-start gap-12px">
        <ColorTip />
        <FilterPopup
          :operators="operators"
          :platformOptions="platformOptions"
          :accountList="accountList"
          :query="query"
          @filter-change="handleFilterChange"
        />
        <a-button type="primary" class="w-112px" size="middle" @click="handleAddTask"> 创建任务 </a-button>
      </div>
    </div>

    <!-- 表格内容区域 -->
    <div class="flex-1 w-full">
      <div class="flex flex-col" style="width: 100%; overflow-x: auto">
        <a-table
          :columns="columns"
          :data-source="data"
          :bordered="true"
          :scroll="{ x: 'max-content' }"
          :pagination="false"
          :locale="{ emptyText: emptyText }"
          @change="handleTableChange"
        >
          <!-- 账号与平台列 -->
          <template #bodyCell="{ column, record, index }">
            <!-- 账号名称列 -->
            <template v-if="column.dataIndex === 'name'">
              <div class="flex items-center justify-start color-#211F24">
                <img
                  :src="getPlatformIcon(record.platform)"
                  class="w-16px h-16px mr-8px rounded-4px"
                  :alt="getPlatformName(record.platform)"
                />
                {{ record.name || '-' }}
              </div>
            </template>

            <!-- 动态日期单元格 -->
            <template v-else-if="column.dataIndex === 'dateCell'">
              <div
                v-if="record[column.dataIndex]?.length"
                class="task-container"
                @click="handleCellClick(record, column)"
              >
                <!-- 任务数量≥3时显示更多 -->
                <div v-if="record[column.dataIndex].length >= 3" class="task-more">
                  <TaskItem :task="record[column.dataIndex][0]" :record="record" @handle-task="handleTaskAction" />
                  <a-popover trigger="click" placement="bottomRight">
                    <template #content>
                      <div class="bg-white w-160px p-12px rounded-4px flex flex-col more-content">
                        <TaskItem
                          v-for="task in record[column.dataIndex].slice(1)"
                          :key="task.id"
                          :task="task"
                          :record="record"
                          @handle-task="handleTaskAction"
                        />
                      </div>
                    </template>
                    <div class="size-12px color-#8f959f h-19px ml-4px rounded-2px cursor-pointer" @click.stop>
                      还有{{ record[column.dataIndex].length - 1 }}项
                    </div>
                  </a-popover>
                </div>
                <!-- 任务数量<3时直接显示 -->
                <div v-else>
                  <TaskItem
                    v-for="task in record[column.dataIndex]"
                    :key="task.id"
                    :task="task"
                    :record="record"
                    @handle-task="handleTaskAction"
                  />
                </div>
              </div>
              <div v-else class="no-task" @click="handleCellClick(record, column)"></div>
            </template>
          </template>
        </a-table>

        <!-- 分页控件 -->
        <div v-if="pageInfo.total > 0" class="pagination-box">
          <a-pagination
            :total="pageInfo.total"
            size="small"
            show-total
            show-jumper
            show-size-changer
            :current="pageInfo.page"
            :page-size="pageInfo.page_size"
            @change="handlePageChange"
            @showSizeChange="handlePageSizeChange"
          />
        </div>
      </div>
    </div>
  </div>

  <!-- 删除确认弹窗 -->
  <a-modal
    v-model:open="showModal"
    @ok="handleDeleteConfirm"
    @cancel="showModal = false"
    ok-text="确认删除"
    :title="deleteTitle"
  >
    <div>{{ deleteContent }}</div>
  </a-modal>

  <DrawPopup ref="drawerPopupRef" @create-task="handleCreateTask" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick, h } from 'vue';
import { Table, Button, Popover, Pagination, Modal, notification, message } from 'ant-design-vue';
import type { TableProps } from 'ant-design-vue';
import router from '@/router';
import DateUtils from '@/utils/DateUtils';

// 组件引入
import DateSelector from './components/date-selector.vue';
import ColorTip from './components/colorTip.vue';
import FilterPopup from './components/filter-popup.vue';
import DrawPopup from './components/draw-popup.vue';
import TaskItem from './components/task-item.vue';

// API引入
import {
  getTaskSchedules,
  delTaskSchedules,
  editTaskSchedulesTime,
  createTask,
  generateContent,
} from '@/api/all/assignment-management';
import { fetchAccountOperators, getMediaAccountList } from '@/api/all/propertyMarketing';

// 工具引入
import { useTableSelectionWithPagination } from '@/hooks/useTableSelectionWithPagination';

// 静态资源
import emptyIcon from '@/assets/img/media-account/icon-empty.png';
// 平台图标
import iconDy from '@/assets/img/platform/icon-dy.png';
import iconXhs from '@/assets/img/platform/icon-xhs.png';
import iconBilibili from '@/assets/img/platform/icon-bilibili.png';
import iconKs from '@/assets/img/platform/icon-ks.png';
import iconSph from '@/assets/img/platform/icon-sph.png';
import iconWb from '@/assets/img/platform/icon-wb.png';
import iconGzh from '@/assets/img/platform/icon-gzh.png';
import iconWarn from '@/assets/img/media-account/icon-warn.png';

// 表格分页逻辑
const { pageInfo, onPageChange, onPageSizeChange } = useTableSelectionWithPagination({
  onPageChange: () => handleSearch(),
  onPageSizeChange: () => handleSearch(),
});

// 状态管理
const dateSelectorModel = ref({
  choseType: '周' as '日' | '周' | '月',
  dayModel: new Date(),
  weekModel: new Date(),
  monthModel: new Date(),
});

const columns = ref<TableProps['columns']>([]);
const data = ref<any[]>([]);
const operators = ref([]);
const accountList = ref([]);
const showModal = ref(false);
const currentTask = ref<any>(null);
const deleteTitle = ref('');
const deleteContent = ref('');
const drawerPopupRef = ref();

// 空状态显示
const emptyText = () => {
  return h('div', { class: 'flex flex-col items-center justify-center', style: { minHeight: '600px' } }, [
    h('img', { src: emptyIcon, class: 'img mt-20px', alt: '暂无数据', width: 106, height: 72 }),
    h('div', { class: 'text mt-36px' }, '暂无数据'),
    h('div', { class: 'mt-12px mb-12px' }, '可通过账号管理添加账号，进行任务排期管理'),
    h(Button, { type: 'primary', onClick: handleAddAccount }, '去添加'),
  ]);
};

// 获取当前周的日期范围
const getCurrentWeekRange = () => {
  const weekRange = DateUtils.getWeekRangeByDate(new Date());
  return [weekRange.startFormatted, weekRange.endFormatted];
};

// 查询参数
const query = reactive({
  page: pageInfo.value.page,
  page_size: pageInfo.value.page_size,
  platforms: undefined,
  operator_ids: undefined,
  ids: [],
  execution_time: getCurrentWeekRange(),
  top_execution_time: undefined,
});

// 平台配置
const platformConfig = {
  icons: { 0: iconDy, 1: iconXhs, 2: iconBilibili, 3: iconKs, 4: iconSph, 5: iconWb, 6: iconGzh },
  names: { 0: '抖音', 1: '小红书', 2: 'B站', 3: '快手', 4: '视频号', 5: '微博', 6: '公众号' },
  options: [
    { id: 0, name: '抖音', icon: iconDy },
    { id: 1, name: '小红书', icon: iconXhs },
    { id: 2, name: 'B站', icon: iconBilibili },
    { id: 3, name: '快手', icon: iconKs },
    { id: 4, name: '视频号', icon: iconSph },
    { id: 5, name: '微博', icon: iconWb },
    { id: 6, name: '公众号', icon: iconGzh },
  ],
};

const platformOptions = ref(platformConfig.options);

// 工具函数
const getPlatformIcon = (platform: number) => platformConfig.icons[platform] || iconWarn;
const getPlatformName = (platform: number) => platformConfig.names[platform] || '未知平台';

const timestampToDayNumber = (timestamp: number) => {
  return new Date(timestamp * 1000).getDate();
};

// 处理表格数据
const processTableData = (apiData: any[]) => {
  const processedData: any[] = [];
  const dateHeaders = currentDateHeaders.value;

  apiData.forEach((account) => {
    const rowData: any = {
      id: account.id,
      name: account.name,
      platform: account.platform,
    };

    // 初始化日期列
    dateHeaders.forEach((day) => {
      rowData[day] = [];
    });

    // 分配任务到对应日期列
    if (account.task_schedules?.length) {
      account.task_schedules.forEach((task: any) => {
        const taskDay = timestampToDayNumber(task.execution_time);
        if (dateHeaders.includes(taskDay)) {
          rowData[taskDay].push(task);
        }
      });
    }

    processedData.push(rowData);
  });

  return processedData;
};

// 设置表格列
const setTableColumns = () => {
  const baseColumns: TableProps['columns'] = [
    {
      title: '账号与发布平台',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true,
      fixed: 'left',
    },
  ];

  let dateHeaders: any[] = [];
  const { choseType } = dateSelectorModel.value;

  if (choseType === '周') {
    dateHeaders = DateUtils.getWeekDaysByDate(dateSelectorModel.value.weekModel, 0);
  } else if (choseType === '月') {
    const date = dateSelectorModel.value.monthModel;
    dateHeaders = DateUtils.getDaysAndWeekdays(date.getFullYear(), date.getMonth());
  } else {
    const date = dateSelectorModel.value.dayModel;
    dateHeaders = [
      {
        day: date.getDate(),
        weekday: DateUtils.formatDateToWeekdayDay(date),
        date,
      },
    ];
  }

  // 判断是否为今天
  const isToday = (date: Date) => {
    if (!date) return false;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const targetDate = new Date(date);
    targetDate.setHours(0, 0, 0, 0);
    return targetDate.getTime() === today.getTime();
  };

  // 添加日期列
  dateHeaders.forEach((item) => {
    const isWeekend = item.date?.getDay() === 0 || item.date?.getDay() === 6;
    const todayFlag = item.date ? isToday(item.date) : false;

    const columnConfig: any = {
      title: item.weekday,
      dataIndex: item.day.toString(),
      key: item.day.toString(),
      width: 135,
      sorter: true,
      customRender: ({ text, record, index }) => {
        if (!text || !text.length) {
          return h('div', { class: 'no-task' });
        }

        if (text.length >= 3) {
          return h('div', { class: 'task-more' }, [
            h(TaskItem, {
              task: text[0],
              record: record,
              onHandleTask: handleTaskAction,
            }),
            h(
              Popover,
              {
                trigger: 'click',
                placement: 'bottomRight',
              },
              {
                content: () =>
                  h(
                    'div',
                    { class: 'more-content' },
                    text.slice(1).map((task) =>
                      h(TaskItem, {
                        task: task,
                        record: record,
                        onHandleTask: handleTaskAction,
                      }),
                    ),
                  ),
                default: () =>
                  h(
                    'div',
                    {
                      class: 'task-more-indicator',
                      onClick: (e: Event) => e.stopPropagation(),
                    },
                    `还有${text.length - 1}项`,
                  ),
              },
            ),
          ]);
        }

        return h(
          'div',
          {},
          text.map((task) =>
            h(TaskItem, {
              task: task,
              record: record,
              onHandleTask: handleTaskAction,
            }),
          ),
        );
      },
      onCell: (record, index) => ({
        style: {
          backgroundColor: isWeekend ? '#fbfaff' : todayFlag ? '#6d4cfe' : 'transparent',
        },
        class: todayFlag ? 'today-column' : isWeekend ? 'weekend-column' : '',
      }),
      onHeaderCell: () => ({
        style: {
          backgroundColor: todayFlag ? '#6d4cfe' : 'transparent',
          color: todayFlag ? 'white' : 'inherit',
        },
        class: todayFlag ? 'today-column' : '',
      }),
    };

    baseColumns.push(columnConfig);
  });

  columns.value = baseColumns;
};

// 当前日期头部计算
const currentDateHeaders = computed(() => {
  const { choseType } = dateSelectorModel.value;
  if (choseType === '周') {
    return DateUtils.getWeekDaysByDate(dateSelectorModel.value.weekModel, 0).map((item) =>
      parseInt(item.day.toString(), 10),
    );
  } else if (choseType === '月') {
    const date = dateSelectorModel.value.monthModel;
    return DateUtils.getDaysAndWeekdays(date.getFullYear(), date.getMonth()).map((item) =>
      parseInt(item.day.toString(), 10),
    );
  } else {
    return [dateSelectorModel.value.dayModel.getDate()];
  }
});

// 数据获取
const handleSearch = () => {
  query.page = pageInfo.value.page;
  query.page_size = pageInfo.value.page_size;

  getTaskSchedules(query)
    .then((response) => {
      if (response.data) {
        const apiData = response.data.data || response.data;
        if (apiData) {
          data.value = processTableData(apiData);
        }
        pageInfo.value.total = response.data.total || apiData.length;
      }
    })
    .catch(() => {
      data.value = [];
    });
};

// 日期选择器变化处理
let isDateSelectorUpdating = false;
const handleDateSelectorChange = (value: any) => {
  if (isDateSelectorUpdating) return;

  const newStartDate = value.dateRange.start;
  const newEndDate = value.dateRange.end;

  const currentStart =
    Array.isArray(query.execution_time) && query.execution_time.length > 0 ? query.execution_time[0] : null;
  const currentEnd =
    Array.isArray(query.execution_time) && query.execution_time.length > 1 ? query.execution_time[1] : null;

  if (currentStart === newStartDate && currentEnd === newEndDate) return;

  isDateSelectorUpdating = true;
  query.execution_time = [newStartDate, newEndDate];
  setTableColumns();
  handleSearch();

  setTimeout(() => {
    isDateSelectorUpdating = false;
  }, 0);
};

// 筛选条件变化处理
const handleFilterChange = (filters: any) => {
  if (typeof filters === 'object' && filters !== null) {
    Object.keys(filters).forEach((key) => {
      switch (key) {
        case 'operator':
          query.operator_ids = filters[key];
          break;
        case 'platform':
          query.platforms = filters[key];
          break;
        case 'accounts':
          query.ids = filters[key];
          break;
        default:
          query[key] = filters[key];
      }
    });
    handleSearch();
  }
};

// 表格排序变化
const handleTableChange = (pagination: any, filters: any, sorter: any) => {
  if (sorter && sorter.order === 'ascend' && sorter.column?.date) {
    const column = sorter.column;
    query.top_execution_time = DateUtils.formatDate(column.date);
  } else {
    query.top_execution_time = undefined;
  }
  handleSearch();
};

// 单元格点击事件
const handleCellClick = (record: any, column: any) => {
  const accountInfo = {
    id: record.id,
    name: record.name,
    platform: record.platform,
  };

  const selectedDate = column.date;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const selectedDateTime = new Date(selectedDate);
  selectedDateTime.setHours(0, 0, 0, 0);

  if (selectedDateTime < today) {
    message.warning('选择的日期已过去，无法创建任务');
    return;
  }

  drawerPopupRef.value?.showDrawer(accountInfo, selectedDate);
};

// 任务操作处理
const handleTaskAction = async (action: string, task: any, ...args: any[]) => {
  switch (action) {
    case 'delete':
      currentTask.value = task;
      deleteTitle.value = task.type === 1 ? '删除内容稿件排期' : '删除选题排期';
      deleteContent.value = `确认删除"${task.name || 'AI生成内容'}"吗？`;
      showModal.value = true;
      break;

    case 'edit-time':
      editTaskSchedulesTime(task.id, { execution_time: args[0] }).then((res) => {
        if (res.code === 200) {
          message.success(res.message);
          handleSearch();
        }
      });
      break;

    case 'goto-detail':
      router.push(`/media-account/management-detail/${task.id}`);
      break;

    case 'ai-create':
      const res = await generateContent(task.id);
      if (res.code === 200) {
        message.success(res.message);
      }
      break;

    case 'edit-task':
      const accountInfo = {
        id: args[0].id,
        name: args[0].name,
        platform: args[0].platform,
      };
      const selectedDate = task.execution_time;
      const date = new Date(selectedDate);

      drawerPopupRef.value?.showDrawer(accountInfo, date);
      nextTick(() => {
        drawerPopupRef.value?.fillTaskData(task);
      });
      break;
  }
};

// 创建任务
const handleAddTask = () => {
  drawerPopupRef.value?.showDrawer();
};

const handleCreateTask = async (value: any) => {
  const res = await createTask(value);
  if (res && res.code === 200) {
    message.success('创建成功');
    handleSearch();
  }
};

// 确认删除
const handleDeleteConfirm = () => {
  if (currentTask.value) {
    delTaskSchedules(currentTask.value.id).then(() => {
      showModal.value = false;
      message.success('删除成功');
      handleSearch();
    });
  }
};

// 添加账号
const handleAddAccount = () => {
  router.push('/media-account/add');
};

// 获取运营人员列表
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);
  }
};

// 获取账号列表
const getAccountList = async () => {
  try {
    const { code, data: accountData } = await getMediaAccountList();
    if (code === 200) {
      accountList.value = accountData.map((account: any) => ({
        value: account.id,
        name: `${account.name}(${getPlatformName(account.platform)})`,
        platform: account.platform,
        icon: getPlatformIcon(account.platform),
      }));
    }
  } catch (error) {
    console.error('获取账号列表失败:', error);
  }
};

// 分页处理
const handlePageChange = (page: number, pageSize: number) => {
  onPageChange(page);
};

const handlePageSizeChange = (current: number, size: number) => {
  onPageSizeChange(size);
};

// 初始化
onMounted(() => {
  setTableColumns();
  handleSearch();
  getOperators();
  getAccountList();
});
</script>

<style scoped>
.task-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 42px;
  cursor: pointer;
}

.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;
}

.task-more-indicator {
  color: #8f959f;
  height: 19px;
  margin-left: 4px;
  border-radius: 2px;
  cursor: pointer;
  font-size: 12px;
}

.no-task {
  min-height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

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

/* 今日列样式 */
:deep(.today-column) {
  background-color: #6d4cfe !important;
}

:deep(.today-column .ant-table-cell) {
  color: white !important;
}

:deep(.today-column .ant-table-cell .task-item) {
  color: white !important;
}

/* 添加表格分割线和固定行高 */
:deep(.ant-table) {
  border: 1px solid #f0f0f0;
}
:deep(.ant-table-container) {
  border-left: 1px solid #f0f0f0;
  border-right: 1px solid #f0f0f0;
}
:deep(.ant-table-thead > tr > th) {
  border-right: 1px solid #f0f0f0 !important;
  background-color: #fafafa;
  font-weight: 600;
  height: 42px;
  padding: 8px 12px;
}

:deep(.ant-table-tbody > tr > td) {
  border-right: 1px solid #f0f0f0 !important;
  height: 42px;
  padding: 8px 12px;
  vertical-align: top;
}

/* 第一列垂直居中 */
:deep(.ant-table-tbody > tr > td:first-child) {
  vertical-align: middle !important;
}

/* 移除最后一列的右边框 */
:deep(.ant-table-thead > tr > th:last-child),
:deep(.ant-table-tbody > tr > td:last-child) {
  border-right: none !important;
}

.task-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 42px;
  cursor: pointer;
}
/* 分页样式 */
.pagination-box {
  display: flex;
  width: 100%;
  padding: 16px 0;
  justify-content: flex-end;
  align-items: center;
}

.more-content {
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
}
</style>
