<script setup lang="ts">
import { computed, defineEmits, defineProps, h, onMounted, ref, resolveComponent, watch } from 'vue';

import FileListView from './fileListView.vue'; // '/codes/fileListView.vue';

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
const axios = (window as any).$axios;
// 获取主题状态
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;
  Kvid: string;
  StandardKvid: string;
  Title?: string;
  Code?: string;
  Unit?: string;
  QualifiedValue?: string;
  Description?: string;
  StatusType?: string;
  ReportKvid?: string;
  [key: string]: any; // 添加索引签名，以支持可能出现的其他字段
}

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

// 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);

// 记录当前已加载的reportKvid，避免重复请求
const loadedReportKvid = ref('');

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

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

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

    // 调用标准实体查询接口
    const response = await axios.post('/Restful/Kivii.Standards.Entities.Standard/Query.json?Type=文件审核');
    console.log('完整响应数据:', response.data);

    // 添加数据存在性检查
    if (response.data && response.data.Results) {
      // 直接使用Results数组
      titleOptions.value = response.data.Results.map((item: any) => ({
        label: item.Title,
        value: item.Kvid
      }));
    } else {
      console.error('无效的数据格式:', response.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 queryParams: any = {
      StandardKvid: selectedStandardKvid.value
    };

    // 如果有报告Kvid，添加到查询参数中
    if (props.kvid) {
      queryParams.ReportKvid = props.kvid;
    }

    const response = await axios.post('/Restful/Kivii.Standards.Entities.Detection/Query.json', queryParams);

    if (response.data && response.data.Results) {
      // 直接使用API返回的数据
      fileData.value = response.data.Results;

      // 向父组件更新文件列表
      emit('update:file-list', fileData.value);
    } else {
      message.error('获取文件数据失败');
    }
  } catch (error) {
    message.error('获取文件详情失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
}

// 使用报告Kvid获取数据
async function fetchDataByReportKvid(reportKvid: string) {
  if (!reportKvid) return;

  console.log(`准备获取文件审核数据，ReportKvid: ${reportKvid}，当前loadedReportKvid: ${loadedReportKvid.value}`);
  if (reportKvid === loadedReportKvid.value && fileData.value.length > 0) {
    console.log('跳过重复请求，使用已缓存的数据');
    return;
  }

  try {
    loading.value = true;

    const response = await axios.post('/Restful/Kivii.Standards.Entities.Detection/Query.json', {
      ReportKvid: reportKvid
    });

    if (response.data && response.data.Results) {
      // 直接使用API返回的数据
      fileData.value = response.data.Results;

      // 如果有StandardKvid，自动选中对应的标题
      if (fileData.value.length > 0 && fileData.value[0].StandardKvid) {
        selectedStandardKvid.value = fileData.value[0].StandardKvid;
      }

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

      // 更新已加载的reportKvid
      loadedReportKvid.value = reportKvid;

      message.success('文件审核数据加载成功');
    } else {
      message.info('暂无文件审核数据');
    }
  } catch (error) {
    console.error('获取文件审核数据失败:', error);
    message.error('获取文件审核数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

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

// 监听kvid的变化，如果有值则获取详情数据
watch(
  () => props.kvid,
  newKvid => {
    if (newKvid && newKvid !== loadedReportKvid.value) {
      fetchDataByReportKvid(newKvid);
    }
  },
  { immediate: true }
);

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

  // 如果有kvid，获取数据
  if (props.kvid && props.kvid !== loadedReportKvid.value) {
    fetchDataByReportKvid(props.kvid);
  }
});

// 表格列定义
const columns = ref<DataTableColumn<FileItem>[]>([
  {
    title: '文件名称',
    key: 'Title',
    width: '35%'
  },
  {
    title: '备注',
    key: 'Description',
    width: '20%'
  },
  {
    title: '文件状态',
    key: 'StatusType',
    width: '15%',
    align: 'center',
    render(row: FileItem) {
      const statusMap: Record<string, { type: string; label: string }> = {
        Disable: { type: 'warning', label: '待上传' },
        approved: { type: 'success', label: '已通过' }
      };
      const status = row.StatusType || '';
      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.Title}`);
  showFileListView.value = true;
}

// 删除文件记录
function deleteFileRecord(row: FileItem) {
  // 实际应该调用删除API
  message.success(`文件"${row.Title}"删除成功`);
  // 从列表中移除
  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>
