<template>
  <div class="p-2 volumeCatalog drawing">
    <div class="file-category">
      <span style="color: #757575; display: inline-block; margin-bottom: 15px">文件分类</span>
      <!-- 优化了图标与文字的对齐和间距 -->
      <div v-for="(item, i) of FolderList" :key="i" :class="{ active: currentActive === i }" @click="handleClick(item, i)" class="category-item">
        <el-icon :size="20" class="folder-icon">
          <Folder />
        </el-icon>
        <span class="folder-name">
          {{ item.catalogueName }}
        </span>
      </div>
    </div>
    <div class="boxs">
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item label="卷册号" prop="volumeNumber">
                <el-input v-model="queryParams.volumeNumber" placeholder="请输入卷册号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="资料名称" prop="documentName">
                <el-input v-model="queryParams.documentName" placeholder="请输入资料名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['design:volumeCatalog:query']">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery" v-hasPermi="['design:volumeCatalog:query']">重置</el-button>
              </el-form-item>
            </el-form>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>
        <el-table v-loading="loading" :data="volumeCatalogList">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="卷册号" align="center" prop="volumeNumber" />
          <el-table-column label="资料名称" align="center" prop="documentName" />
          <el-table-column label="子项名称" align="center" prop="designSubitem" />
          <el-table-column label="专业" align="center" prop="specialtyName"> </el-table-column>
          <el-table-column label="设计人员" align="center" prop="principalName" />
          <el-table-column label="版本号" align="center" prop="version" />
          <el-table-column label="图纸文件" align="center" prop="remark" width="300">
            <template #default="scope">
              <el-link
                :key="scope.row.fileId"
                :href="scope.row.fileUrl"
                target="_blank"
                type="primary"
                :underline="false"
                @click="handleBookFile(scope.row)"
              >
                {{ scope.row.fileName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" prop="remark" width="300">
            <template #default="scope">
              <el-button link type="primary" icon="view" @click="handleViewHis(scope.row)">查阅记录</el-button>
              <el-button type="warning" link icon="Download" @click="handleDownload(scope.row)"> 下载 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
    </div>
    <el-dialog draggable title="查阅记录" v-model="viewVisible1" width="600px">
      <el-table :data="histroyList" style="width: 100%" border>
        <el-table-column type="index" label="序号" align="center" width="80"> </el-table-column>
        <el-table-column prop="userName" label="用户名称" align="center"> </el-table-column>
        <el-table-column label="下载或查看" align="center">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.status == 2">下载</el-tag>
            <el-tag type="success" v-else>查看</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="查阅时间" align="center" width="200"> </el-table-column>
      </el-table>
      <template #footer>
        <span>
          <el-button type="primary" @click="viewVisible1 = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="VolumeCatalog" lang="ts">
import { listVolumeCatalog, addVolumeCatalog, updateVolumeCatalog } from '@/api/design/volumeCatalog';
import { VolumeCatalogVO } from '@/api/design/volumeCatalog/types';
import { useUserStoreHook } from '@/store/modules/user';
import { volumeFileViewer, volumeFileViewerList, joinList } from '@/api/design/drawing';
const fileList = ref([]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const volumeCatalogList = ref<VolumeCatalogVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const queryFormRef = ref<ElFormInstance>();
const volumeCatalogFormRef = ref<ElFormInstance>();
const catalogueId = ref(3);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const FolderList = [
  { id: 3, catalogueName: '蓝图' },
  { id: 1, catalogueName: '过程图纸' },
  { id: 4, catalogueName: '废弃图纸' }
];
const uploadForm = reactive({
  userIds: [],
  volumeCatalogId: undefined,
  fileId: undefined,
  explainText: '',
  fileList: [],
  cancellationIds: [] // 用于存储已作废的文件ID
});
const initFormData: any = {
  design: undefined,
  projectId: currentProject.value?.id || '',
  designSubitemId: undefined,
  volumeNumber: undefined,
  documentName: undefined,
  designState: '2',

  remark: undefined
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    designSubitemId: undefined,
    volumeNumber: undefined,
    documentName: undefined,
    params: {}
  },
  rules: {
    design: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    volumeNumber: [{ required: true, message: '卷册号不能为空', trigger: 'blur' }],
    documentName: [{ required: true, message: '资料名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const histroyList = ref([]);
/** 查询卷册目录列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await joinList({ type: catalogueId.value, ...queryParams.value });
    volumeCatalogList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleView = (row?: any) => {
  fileList.value = row.fileVoList;

  viewVisible.value = true;
};

const viewVisible = ref(false);
const viewVisible1 = ref(false);
/** 重置上传表单 */
const resetUploadForm = () => {
  uploadForm.userIds = [];
  uploadForm.volumeCatalogId = undefined;
  uploadForm.fileId = undefined;
  uploadForm.explainText = '';
  uploadForm.fileList = [];
  uploadForm.cancellationIds = []; // 重置作废文件ID列表
};

/** 提交按钮 */
const submitForm = () => {
  volumeCatalogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.design) {
        await updateVolumeCatalog(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addVolumeCatalog(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
const handleDownload = (row: any) => {
  getCheck(row, 2);
  proxy?.$download.oss(row.fileId);
};
const handleBookFile = (row: any) => {
  getCheck(row, 1);
};
// 调用查阅接口
const getCheck = async (row, status) => {
  volumeFileViewer({ volumeFileId: row.id, status });
};
const handleViewHis = async (row) => {
  viewVisible1.value = true;
  let res = await volumeFileViewerList(row.id);
  if (res.code == 200) {
    histroyList.value = res.rows;
  }
};
const currentActive = ref(0);
// 点击事件处理函数
const handleClick = (item, index) => {
  console.log(item.id);
  currentActive.value = index;
  catalogueId.value = item.id;
  // 重新获取数据
  getList();
};

onMounted(() => {
  getList();
});

//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    queryParams.value.projectId = nid;
    form.value.projectId = nid;
    getList();
  }
);

onUnmounted(() => {
  listeningProject();
});
</script>

<style lang="scss">
.drawing {
  display: flex;
  .el-tabs__header {
    height: 90vh !important;
  }
  .file-category {
    width: 200px;
    display: flex;
    flex-direction: column;
    /* 移除固定宽度，让容器根据内容自适应 */
    background-color: #ffffff;
    padding: 10px;
    border-radius: 6px;
    /* 限制最大宽度，防止内容过长 */
    /* max-width: 200px; */
    margin-right: 10px;
  }

  .file-category > div {
    cursor: pointer;
    padding: 8px 12px;
    margin-bottom: 4px;
    border-radius: 4px;
    display: flex;
    /* 文本不换行，确保宽度由内容决定 */
    white-space: nowrap;
    transition: all 0.2s ease;
    > span {
      margin-left: 6px;
      /* color: #676767;
      font-size: 18px; */
    }
  }

  .file-category {
    width: 200px;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    padding: 10px;
    border-radius: 8px;
    margin-right: 10px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }

  // 分类项样式优化
  .category-item {
    cursor: pointer;
    padding: 10px 12px;
    margin-bottom: 4px;
    border-radius: 6px;
    display: inline-flex;
    align-items: center; /* 垂直居中对齐 */
    white-space: nowrap;
    transition: all 0.25s ease;
    font-size: 14px;
    color: #334155;
    line-height: 1; /* 确保行高一致 */

    &:hover {
      background-color: #f1f5f9;
      transform: translateX(2px);
    }
  }

  // 图标样式
  .folder-icon {
    color: #94a3b8;
    transition: color 0.25s ease;
  }

  // 文件夹名称样式
  .folder-name {
    margin-left: 8px; /* 增加图标与文字间距 */
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: calc(100% - 30px); /* 限制最大宽度，防止溢出 */
  }

  // 活跃状态样式
  .category-item.active {
    background-color: #eff6ff;
    color: #2563eb;
    font-weight: 500;

    .folder-icon {
      color: #2563eb;
    }
  }
  .boxs {
    width: calc(100% - 220px);
  }
}
</style>
