<script setup lang="ts">
import { computed, defineEmits, defineProps, h, onMounted, ref, resolveComponent } from 'vue';
import { request } from '@/service/request';
import FileListView from './fileListView.vue';

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
// 获取主题状态
const themeStore = (window as any).$themeStore;
// 获取消息提示
const message = (window as any).$message;
const dialog = (window as any).$dialog;
// 通过计算属性确定当前的主体色
const isDarkMode = computed(() => themeStore?.darkMode || false);
// 根据主题计算文字颜色
const textColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.85)'));
const legendTextColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.65)' : 'rgba(0, 0, 0, 0.65)'));
const borderColor = computed(() => (isDarkMode.value ? '#303030' : '#ffffff'));
// CSS变量
const cssVars = computed(() => ({
  '--text-color': textColor.value,
  '--bg-color': isDarkMode.value ? '#1f1f1f' : '#f5f5f5',
  '--panel-bg': isDarkMode.value ? '#262626' : '#ffffff',
  '--card-bg': isDarkMode.value ? '#303030' : '#ffffff',
  '--border-color': isDarkMode.value ? '#434343' : '#e8e8e8'
}));

// 修改FileItem接口，但保留原有字段
interface FileItem {
  id?: number;
  name?: string; // 对应Title
  type?: string;
  status?: string; // 对应StatusType
  remark?: string; // 对应Description
  StandardKvid: string;
  Kvid: string;
  Title?: string;
  Code?: string;
  Unit?: string;
  QualifiedValue?: string;
  Description?: string;
  StatusType?: string;
}

// API返回的数据项接口
interface ResultItem {
  id?: number;
  StandardKvid: string;
  Kvid: string;
  Title?: string;
  Code?: string;
  Unit?: string;
  QualifiedValue?: string;
  Description?: string;
  StatusType?: string;
  [key: string]: any;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const props = defineProps({
  fileList: {
    type: Array as () => FileItem[],
    required: true
  },
  report: {
    type: Object as () => any,
    required: true
  }
});

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const emit = defineEmits(['update:file-list', 'update:reviewResult', 'update:reviewComment']);

// 状态变量
const titleOptions = ref<SelectOption[]>([]);
const selectedStandardKvid = ref<string>('');
const fileData = ref<FileItem[]>([]);
const loading = ref<boolean>(false);

// 控制fileListView模态框显示
const showFileListView = ref<boolean>(false);

// 根据选择的标题筛选数据
const filteredData = computed(() => {
  if (!selectedStandardKvid.value) {
    return [];
  }
  return fileData.value.filter(file => file.StandardKvid === selectedStandardKvid.value);
});

// 获取文件类型数据
async function fetchTitleOptions() {
  try {
    loading.value = true;

    // 调用标准实体查询接口
    const { data, error } = await request({
      url: '/Restful/Kivii.Standards.Entities.Standard/Query.json',
      method: 'get',
      params: { Type: '文件审核' }
    });
    console.log('完整响应数据:', data);

    if (error) {
      console.error('获取文件类型失败:', error);
      message.error('获取文件类型失败');
      return;
    }

    // 添加数据存在性检查
    if (data && data.Results) {
      // 直接使用Results数组
      titleOptions.value = data.Results.map((item: any) => ({
        label: item.Title,
        value: item.Kvid
      }));
    } else {
      console.error('无效的数据格式:', data);
      message.error('数据格式不正确');
    }
  } catch (error) {
    message.error('获取文件类型失败');
    console.error('获取文件类型失败:', error);
  } finally {
    loading.value = false;
  }
}

// 获取文件详情数据
async function fetchFileDetails() {
  if (!selectedStandardKvid.value) return;

  try {
    loading.value = true;

    const { data, error } = await request({
      url: '/Restful/Kivii.Standards.Entities.Detection/Query.json',
      method: 'get',
      params: { StandardKvid: selectedStandardKvid.value }
    });

    if (error) {
      console.error('获取文件详情失败:', error);
      message.error('获取文件详情失败');
      return;
    }

    if (data && data.Results) {
      createReportItems(data.Results);
    } else {
      message.error('获取文件数据失败');
    }
  } catch (error) {
    message.error('获取文件详情失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
}

async function createReportItems(reuslts: any) {
  const { data, error } = await request({
    url: '/Restful/Kivii.Lims.Entities.ReportItem/Detection.json',
    method: 'post',
    data: { Detections: reuslts, ReportKvid: props.report.Kvid }
  });

  if (error) {
    console.error('项目创建失败:', error);
    message.error(error.message);
    return;
  }
  if (data && data.Results) {
    // 保留完整的Results数组，同时添加必要的展示字段
    fileData.value = data.Results.map((item: any) => ({
      ...item, // 保留所有原始字段
      name: item.Title || '', // 添加展示用的name字段
      remark: item.Description || item.QualifiedValue || '', // 添加展示用的remark字段
      status: item.StatusType || 'pending' // 添加展示用的status字段
    }));

    // 向父组件更新文件列表
    emit('update:file-list', fileData.value);
  }
}

// 处理标题选择变化
function handleTitleChange(value: string) {
  selectedStandardKvid.value = value;
  fetchFileDetails();
}

// 页面加载时获取文件类型
onMounted(() => {
  fetchTitleOptions();
});

// 表格列定义
const columns = ref<DataTableColumn<FileItem>[]>([
  {
    title: '文件名称',
    key: 'name',
    width: '35%'
  },
  {
    title: '备注',
    key: 'remark',
    width: '20%'
  },
  {
    title: '文件状态',
    key: 'status',
    width: '15%',
    align: 'center',
    render(row: FileItem) {
      const statusMap: Record<string, { type: string; label: string }> = {
        BeforeTest: { type: 'warning', label: '待上传' },
        Asigning: { type: 'warning', label: '已上传' },
        Testing: { type: 'success', label: '审核中' },
        TestFinished: { type: 'warning', label: '不通过' },
        TestCollected: { type: 'success', label: '已通过' }
      };
      const status = row.status || '';
      const { type, label } = statusMap[status] || { type: 'default', label: status || '未知' };
      return h(
        resolveComponent('n-tag'),
        {
          type,
          size: 'small'
        },
        { default: () => label }
      );
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    render(row: any) {
      return h('div', { style: 'display: flex; gap: 8px; justify-content: center;' }, [
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            onClick: () => viewFile(row)
          },
          { default: () => '查看' }
        ),
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'error',
            onClick: () => deleteFileRecord(row)
          },
          { default: () => '删除' }
        )
      ]);
    }
  }
]);

// 查看文件
function viewFile(row: FileItem) {
  // 可以根据需要将文件信息传递给fileListView组件
  console.log(`查看文件: ${row.name}`);
  showFileListView.value = true;
}

// 删除文件记录
function deleteFileRecord(row: FileItem) {
  // 实际应该调用删除API
  message.success(`文件"${row.name}"删除成功`);
  // 从列表中移除
  fileData.value = fileData.value.filter(item => item.Kvid !== row.Kvid);
  // 向父组件更新文件列表
  emit('update:file-list', fileData.value);
}
</script>

<template>
  <div>
    <div class="section-title">
      <svg class="section-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
        <path
          fill="currentColor"
          d="M13,9H18.5L13,3.5V9M6,2H14L20,8V20A2,2 0 0,1 18,22H6C4.89,22 4,21.1 4,20V4C4,2.89 4.89,2 6,2M14,20V19C14,17.67 11.33,17 10,17C8.67,17 6,17.67 6,19V20H14M10,12A2,2 0 0,0 8,14A2,2 0 0,0 10,16A2,2 0 0,0 12,14A2,2 0 0,0 10,12Z"
        ></path>
      </svg>
      <span>审核文件提交</span>
    </div>

    <NFormItem label="选择文件类型">
      <NSelect
        v-model:value="selectedStandardKvid"
        :options="titleOptions"
        placeholder="选择文件类型"
        @update:value="handleTitleChange"
      ></NSelect>
    </NFormItem>

    <NDataTable
      :columns="columns"
      :data="filteredData"
      :bordered="false"
      max-height="300px"
      :loading="loading"
    ></NDataTable>

    <!-- fileListView模态框 -->
    <NModal v-model:show="showFileListView" preset="card" title="文件列表" style="width: 50%" :mask-closable="true">
      <FileListView></FileListView>
    </NModal>
  </div>
</template>

<style scoped>
.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.section-icon {
  margin-right: 8px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-hint {
  color: #999;
  font-size: 13px;
  margin-top: 8px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
