<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- <el-form-item label="子项ID" prop="designSubitemId">
              <el-input v-model="queryParams.designSubitemId" placeholder="请输入设计子项ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <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">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['design:volumeCatalog:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['design:volumeCatalog:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['design:volumeCatalog:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="volumeCatalogList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="子项ID" align="center" prop="designSubitemId" />
        <el-table-column label="子项名称" align="center" prop="designSubitemName" />
        <el-table-column label="设计状态" align="center" prop="designState">
          <template #default="scope">
            <dict-tag :options="design_state" :value="scope.row.designState" />
          </template>
        </el-table-column>
        <el-table-column label="专业" align="center" prop="specialty" />
        <el-table-column label="负责人" align="center" prop="principal" />
        <el-table-column label="卷册号" align="center" prop="volumeNumber" />
        <el-table-column label="资料名称" align="center" prop="documentName" />
        <el-table-column label="计划完成时间" align="center" prop="planCompleteTime" />

        <el-table-column label="文件" align="center" prop="fileVoList" width="180">
          <template #default="scope">
            <el-link
              v-for="item in scope.row.fileVoList"
              :key="item.fileId"
              :href="item.fileUrl"
              target="_blank"
              :type="item.status == '1' ? 'primary' : 'info'"
              :underline="false"
              @click="lookFile(scope.row.design)"
            >
              {{ item.fileName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="上传说明" align="center" prop="explainText">
          <template #default="scope">
            {{ scope.row.fileVoList[0]?.explainText }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['design:volumeCatalog:edit']">修改</el-button>
            <el-button link type="primary" icon="Upload" @click="handleUpload(scope.row)">上传</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['design:volumeCatalog:remove']"
              >删除</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>
    <!-- 添加或修改卷册目录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="volumeCatalogFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="子项ID" prop="designSubitemId">
          <el-input v-model="form.designSubitemId" placeholder="请输入设计子项ID" />
        </el-form-item>
        <el-form-item label="子项" prop="designSubitem">
          <el-input v-model="form.designSubitem" placeholder="请输入设计子项" />
        </el-form-item>
        <el-form-item label="专业" prop="specialty">
          <el-input v-model="form.specialty" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-input v-model="form.principal" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="计划完成时间" prop="plannedCompletion">
          <el-date-picker v-model="form.plannedCompletion" type="date" value-format="YYYY-MM-DD" placeholder="请选择计划完成时间" />
        </el-form-item>
        <el-form-item label="设计状态" prop="designState">
          <el-select v-model="form.designState" placeholder="请选择设计状态">
            <el-option :value="item.value" v-for="item in design_state" :key="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="卷册号" prop="volumeNumber">
          <el-input v-model="form.volumeNumber" placeholder="请输入卷册号" />
        </el-form-item>
        <el-form-item label="资料名称" prop="documentName">
          <el-input v-model="form.documentName" placeholder="请输入资料名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传文件对话框 -->
    <el-dialog title="上传卷册文件" v-model="uploadVisible" width="500px" append-to-body>
      <el-form :model="uploadForm" label-width="80px" :inline="false">
        <el-form-item label="查阅人员" prop="userId">
          <el-select v-model="uploadForm.userIds" placeholder="请选择查阅人员" clearable multiple>
            <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="作废文件" prop="cancellationIds">
          <el-select v-model="uploadForm.cancellationIds" placeholder="这里可以选择作废已上传的文件" clearable multiple>
            <el-option v-for="user in uploadForm.fileList" :key="user.id" :label="user.fileName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="fileId">
          <file-upload v-model="uploadForm.fileId"></file-upload>
        </el-form-item>
        <el-form-item label="说明" prop="explainText">
          <el-input v-model="uploadForm.explainText" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="buttonLoading">确定</el-button>
          <el-button @click="uploadVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="VolumeCatalog" lang="ts">
import {
  listVolumeCatalog,
  getVolumeCatalog,
  delVolumeCatalog,
  addVolumeCatalog,
  updateVolumeCatalog,
  uploadVolumeFile,
  getVolumeCatafileList,
  lookViewerFile
} from '@/api/design/volumeCatalog';
import { VolumeCatalogVO, VolumeCatalogQuery, VolumeCatalogForm } from '@/api/design/volumeCatalog/types';
import { useUserStoreHook } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { design_state } = toRefs(proxy?.useDict('design_state'));

const volumeCatalogList = ref<VolumeCatalogVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = 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 dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const uploadForm = reactive({
  userIds: [],
  volumeCatalogId: undefined,
  fileId: undefined,
  explainText: '',
  fileList: [],
  cancellationIds: [] // 用于存储已作废的文件ID
});

const userList = ref([]);

const initFormData: VolumeCatalogForm = {
  design: undefined,
  projectId: currentProject.value?.id || '',
  designSubitemId: undefined,
  volumeNumber: undefined,
  documentName: undefined,

  remark: undefined
};
const data = reactive<PageData<VolumeCatalogForm, VolumeCatalogQuery>>({
  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 getList = async () => {
  loading.value = true;
  try {
    const res = await listVolumeCatalog(queryParams.value);
    volumeCatalogList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  volumeCatalogFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: VolumeCatalogVO[]) => {
  ids.value = selection.map((item) => item.design);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加卷册目录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: VolumeCatalogVO) => {
  reset();
  const _id = row?.design || ids.value[0];
  const res = await getVolumeCatalog(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改卷册目录';
};

/** 上传文件按钮操作 */
const uploadVisible = ref(false);
const handleUpload = async (row?: any) => {
  resetUploadForm();
  uploadForm.volumeCatalogId = row.design;
  userList.value = row.noViewerList;
  const res = await getVolumeCatafileList(row.design);
  uploadForm.fileList = res.data.filter((item) => item.status == '1') || [];
  uploadVisible.value = true;
};

/** 查看文件 */
const lookFile = (fileId: string) => {
  lookViewerFile(fileId);
};

/** 重置上传表单 */
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 onSubmit = async () => {
  buttonLoading.value = true;
  try {
    await uploadVolumeFile(uploadForm);
    proxy?.$modal.msgSuccess('文件上传成功');
    uploadVisible.value = false;
    await getList();
  } catch (error) {
    console.error('上传文件失败:', error);
  } finally {
    buttonLoading.value = false;
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: VolumeCatalogVO) => {
  const _ids = row?.design || ids.value;
  await proxy?.$modal.confirm('是否确认删除卷册目录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delVolumeCatalog(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'design/volumeCatalog/export',
    {
      ...queryParams.value
    },
    `volumeCatalog_${new Date().getTime()}.xlsx`
  );
};

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

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

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