<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="用户姓名" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入用户姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="班组" prop="teamId">
              <el-select v-model="queryParams.teamId" clearable placeholder="全部">
                <el-option v-for="item in ProjectTeam" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </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-tooltip placement="top" effect="dark">
              <template #content>
                注:上传压缩包内的文件夹名称需设置为【姓名-身份证-满分-得分-及格分】， <br />
                例如:小明-5130112333654X-100-59-60
              </template>
              <file-upload
                :limit="1"
                v-model:model-value="filePath"
                isImportInfo
                :fileType="['zip']"
                uploadUrl="/safety/questionUserAnswer/upload/zip"
                :file-size="5000"
                :data="{ projectId: currentProject.id }"
                ><el-button type="success" plain icon="Upload">上传线下安全考试</el-button></file-upload
              >
            </el-tooltip>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Download" :disabled="single" @click="handleDownload()">批量下载试卷</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="questionUserAnswerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="及格线/总分" align="center" prop="pass" />
        <el-table-column label="得分" align="center" prop="score" />
        <el-table-column label="计划时间" align="center" prop="examTime" />
        <el-table-column label="用时时间" align="center" prop="takeTime" />
        <el-table-column label="考试时间" align="center" prop="createTime" />
        <el-table-column label="类型" align="center" prop="examType">
          <template #default="scope">
            <dict-tag :options="user_exam_type" :value="scope.row.examType" />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link type="primary" :underline="false" :href="scope.row.fileUrl[0]" target="_blank">
              <el-button link type="primary" icon="View">预览试卷</el-button>
            </el-link>

            <el-button link type="primary" icon="Download" @click="downloadOssOne(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>
</template>

<script setup name="QuestionUserAnswer" lang="ts">
import {
  listQuestionUserAnswer,
  getQuestionUserAnswer,
  delQuestionUserAnswer,
  addQuestionUserAnswer,
  updateQuestionUserAnswer,
  uploadQuestionUserAnswer
} from '@/api/safety/questionUserAnswer';
import { QuestionUserAnswerVO, QuestionUserAnswerQuery, QuestionUserAnswerForm } from '@/api/safety/questionUserAnswer/types';
import { downLoadOss } from '@/api/system/oss';
import download from '@/plugins/download';

import { useUserStoreHook } from '@/store/modules/user';
import { blobValidate } from '@/utils/ruoyi';
import FileSaver from 'file-saver';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { user_exam_type } = toRefs<any>(proxy?.useDict('user_exam_type'));

// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const ProjectTeam = computed(() => userStore.ProjectTeamList);

const questionUserAnswerList = ref<QuestionUserAnswerVO[]>([]);
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);
const filePath = ref<string>('');
const queryFormRef = ref<ElFormInstance>();
const questionUserAnswerFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: QuestionUserAnswerForm = {
  id: undefined,
  projectId: currentProject.value.id,
  userId: undefined,
  bankId: undefined,
  answer: undefined,
  userName: undefined,
  score: undefined,
  examTime: undefined,
  takeTime: undefined,
  pass: undefined,
  file: undefined,
  teamId: undefined
};
const data = reactive<PageData<QuestionUserAnswerForm, QuestionUserAnswerQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    examType: undefined,
    teamId: undefined,
    projectId: currentProject.value.id,
    userName: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目id不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户试卷存储列表 */
const getList = async () => {
  loading.value = true;
  const res = await listQuestionUserAnswer(queryParams.value);
  questionUserAnswerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

/** 修改按钮操作 */
// const handleUpdate = async (row?: QuestionUserAnswerVO) => {
//   reset();
//   const _id = row?.id || ids.value[0];
//   const res = await getQuestionUserAnswer(_id);
//   Object.assign(form.value, res.data);
//   dialog.visible = true;
//   dialog.title = '修改用户试卷存储';
// };

/** 批量下载按钮操作 */
const handleDownload = async () => {
  const _ids = ids.value;
  await downLoadOss({ idList: _ids }, '/safety/questionUserAnswer/exportFile', '安全考试.zip');
};
/** 下载单个按钮操作 */
const downloadOssOne = async (row?: QuestionUserAnswerVO) => {
  await download.oss(row?.file);
};

// const fileWatch = watch(
//   () => filePath.value,
//   (nid, oid) => {
//     uploadQuestionUserAnswer({ file: filePath.value, projectId: currentProject.value.id }).then((res) => {
//       console.log(res);
//     });
//   }
// );

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

onUnmounted(() => {
  listeningProject();
});

onMounted(() => {
  getList();
});
</script>
