<template>
  <a-drawer
    title="原料库"
    cancel-text="取消"
    ok-text="确定"
    placement="right"
    :visible="visible"
    @after-visible-change="onAfterVisibleChange"
    @close="handleClose"
    @ok="handleOk"
    @cancel="handleCancel"
    width="904px"
    class="task-drawer"
    style="right: 481px"
  >
    <!-- 加载状态 -->
    <a-spin :spinning="loading" tip="加载中...">
      <!-- 表格区域 -->
      <div class="table-container">
        <Table
          :data-source="materialData"
          bordered
          :columns="columns"
          :pagination="false"
          row-key="id"
          :row-selection="rowSelection"
        >
          <!-- 名称列自定义渲染 -->
          <template #cell:name="{ record }">
            <div class="name-cell">
              <img :src="getTypeIcon(record.type)" alt="类型图标" class="type-icon" />
              <span class="material-name">{{ record.name }}</span>
            </div>
          </template>

          <!-- 类型列自定义渲染 -->
          <template #cell:type="{ record }">
            <span>{{ getType(record.type) }}</span>
          </template>

          <!-- 来源列自定义渲染 -->
          <template #cell:from="{ record }">
            <span>{{ getFrom(record.from) }}</span>
          </template>

          <!-- 上传时间列自定义渲染 -->
          <template #cell:created_at="{ record }">
            <span>{{ formatDate(record.created_at) }}</span>
          </template>
        </Table>

        <!-- 分页控件 -->
        <div v-if="pageInfo.total > 0" class="pagination-container">
          <a-pagination
            :current="pageInfo.page"
            :page-size="pageInfo.page_size"
            :total="pageInfo.total"
            @change="handlePageChange"
            @showSizeChange="handlePageSizeChange"
            show-size-changer
            show-quick-jumper
            :show-total="(total) => `共 ${total} 条`"
          />
        </div>
      </div>
    </a-spin>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits } from 'vue';
import { Table, Button, Pagination } from 'ant-design-vue';
// // 修正Arco Design图标导入方式
// import { FileTextOutlined } from '@arco-design/web-vue/es/icons';
import dayjs from 'dayjs';
import { RawMaterialType } from '@/views/material-center/components/raw-material/constants';
import { useTableSelectionWithPagination } from '@/hooks/useTableSelectionWithPagination';
import { getRawMaterialsPage } from '@/api/all/generationWorkshop';

// 引入类型图标
import imgIcon from '@/assets/img/material/icon-image.png';
import videoIcon from '@/assets/img/material/icon-video.png';
import textIcon from '@/assets/img/material/icon-text.png';
import unknownIcon from '@/assets/img/material/icon-unknown.png';

// 定义Props类型
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  query: {
    type: Object as () => {
      page?: number;
      page_size?: number;
      platforms?: any;
      operator_ids?: any;
      ids?: any[];
      top_execution_time?: any;
      keyword?: string;
      type?: any;
    },
    required: true,
    default: () => ({
      page: 1,
      page_size: 10,
      platforms: undefined,
      operator_ids: undefined,
      ids: [],
      top_execution_time: undefined,
      keyword: '',
      type: undefined,
    }),
  },
});

// 定义Emits类型
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'after-visible-change', visible: boolean): void;
  (
    e: 'confirm',
    data: {
      selectedKeys: string[];
      selectedData: any[];
      choseText: string;
      choseImgArray: any[];
    },
  ): void;
  (e: 'cancel'): void;
}>();

// 内部状态管理
const materialData = ref<any[]>([]);
const choseText = ref('');
const choseImgArray = ref<any[]>([]);
const loading = ref(false);
const pageInfo = ref({
  page: 1,
  page_size: 10,
  total: 0,
});

// 数据获取函数
const fetchMaterialData = async () => {
  if (!props.visible) return;

  try {
    loading.value = true;
    const params = {
      ...props.query,
      page: pageInfo.value.page,
      page_size: pageInfo.value.page_size,
    };

    const res = await getRawMaterialsPage(params);
    console.log('获取原料库数据成功:', res);
    if (res?.code == 200) {
      materialData.value = res.data.data;
      pageInfo.value.total = res.data.total || 0;
      console.log('获取原料库数据成功++++:', res, materialData.value);
    } else {
      materialData.value = [];
      pageInfo.value.total = 0;
    }
  } catch (error) {
    console.error('获取原料库数据失败:', error);
    materialData.value = [];
    pageInfo.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 表格列配置
const columns = ref([
  {
    title: '文件名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '来源',
    dataIndex: 'from',
    key: 'from',
    width: 100,
  },
  {
    title: '上传时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 200,
  },
]);

// 表格选择逻辑
const { rowSelection, selectedRowKeys } = useTableSelectionWithPagination({
  rowKey: 'id',
});

// 分页处理函数
const handlePageChange = (page: number) => {
  pageInfo.value.page = page;
  fetchMaterialData();
};

const handlePageSizeChange = (current: number, size: number) => {
  pageInfo.value.page = 1;
  pageInfo.value.page_size = size;
  fetchMaterialData();
};

// 监听查询参数变化
watch(
  () => props.query,
  (newQuery) => {
    if (props.visible) {
      pageInfo.value.page = 1;
      fetchMaterialData();
    }
  },
  { deep: true },
);

// 监听抽屉显示状态
watch(
  () => props.visible,
  (visible) => {
    emit('after-visible-change', visible);
    if (visible) {
      pageInfo.value.page = 1;
      fetchMaterialData();
    } else {
      materialData.value = [];
      selectedRowKeys.value = [];
      choseText.value = '';
      choseImgArray.value = [];
    }
  },
);

// 监听选中项变化
watch(selectedRowKeys, (newKeys) => {
  const filteredData = materialData.value.filter((item) => newKeys.includes(item.id));

  const typeCount: Record<string, number> = {};
  filteredData.forEach((item) => {
    typeCount[item.type] = (typeCount[item.type] || 0) + 1;
  });

  choseText.value = Object.entries(typeCount)
    .map(([type, count]) => `${getType(Number(type))}: ${count}个`)
    .join(' ');

  choseImgArray.value = filteredData.filter((item) => [0, 1].includes(item.type));
});

// 辅助函数
const getType = (type: number): string => {
  const typeMap = {
    [RawMaterialType.Image]: '图片',
    [RawMaterialType.Video]: '视频',
    [RawMaterialType.Text]: '文本',
  };
  return typeMap[type] || '未知';
};

const getTypeIcon = (type: number): string => {
  const iconMap = {
    [RawMaterialType.Image]: imgIcon,
    [RawMaterialType.Video]: videoIcon,
    [RawMaterialType.Text]: textIcon,
  };
  return iconMap[type] || unknownIcon;
};

const getFrom = (from: number): string => {
  const fromMap = {
    0: '本地上传',
    1: 'AI生成',
  };
  return fromMap[from] || '未知';
};

const formatDate = (dateString?: string): string => {
  if (!dateString) return '';
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 事件处理函数
const handleClose = () => {
  emit('update:visible', false);
};

const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
};

const handleOk = () => {
  const selectedData = materialData.value.filter((item) => selectedRowKeys.value.includes(item.id));
  emit('confirm', {
    selectedKeys: selectedRowKeys.value,
    selectedData,
    choseText: choseText.value,
    choseImgArray: choseImgArray.value,
  });
  emit('update:visible', false);
};

const onAfterVisibleChange = (visible: boolean) => {
  // 空实现，避免未定义错误
};
</script>

<style scoped>
/* 样式保持不变 */
.table-container {
  height: calc(100% - 50px);
  min-height: 300px;
  display: flex;
  flex-direction: column;
}

.material-table {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  padding: 16px 0;
  text-align: right;
}

.name-cell {
  display: flex;
  align-items: center;
}

.type-icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
  object-fit: contain;
}

.material-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
}

.empty-icon {
  margin-bottom: 16px;
  color: #ccc;
}

.empty-text {
  font-size: 14px;
}
</style>
