<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" label-width="80px">
            <el-form-item label="文件名称" prop="materialsName">
              <el-input v-model="queryParams.materialsName" placeholder="请输入文件名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 330px">
              <el-date-picker
                clearable
                v-model="queryParams.createTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </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>

        <el-card shadow="never" class="mt-[10px]">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5" v-if="!hasExpert">
                <el-button type="primary" plain icon="Plus" @click="handleImport" v-hasPermi="['zjk:productSummarize:add']">新增</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="extractLogList">
            <el-table-column type="index" width="50px" label="序号"></el-table-column>
            <el-table-column
              :label="label"
              :align="align || 'center'"
              :min-width="minWidth || '100px'"
              v-for="{ label, prop, align, minWidth } in headers"
              :key="prop"
            >
              <template #default="{ row }">
                <span v-if="prop == 'materialsName'" class="show-file" @click="openFile(row.materialsUrl, row.materialsId)">{{
                  row.materialsName || '-'
                }}</span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="!hasExpert" label="操作" fixed="right" class-name="small-padding fixed-width">
              <template #default="{ row }">
                <el-button link type="primary" @click="DelFile(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" :total="page.total" v-model:page="page.pageNum" v-model:limit="page.pageSize" @pagination="getList" />
        </el-card>
        <!-- 培训学习上传文件对话框 -->
        <el-dialog v-model="upload.open" :title="upload.title" width="500px" append-to-body>
          <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".pdf, .mp4"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            drag
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="text-center el-upload__tip">
                <span>仅允许导入pdf、mp4格式文件。</span>
              </div>
            </template>
          </el-upload>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script setup name="CreditTrain" lang="ts">
import { getData, addFile, delFile, logLearn } from '@/api/credit/train';
import { globalHeaders } from '@/utils/request';
import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();
const roles = computed(() => userStore.roles);
const hasExpert = computed(() => roles.value.includes('expert'));

const extractLogList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const route = useRoute();

const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}
const headers = ref<Header[]>([
  {
    label: '文件名称',
    prop: 'materialsName'
  },
  {
    label: '创建人',
    prop: 'createName'
  },
  {
    label: '创建时间',
    prop: 'createTime'
  }
]);

const statusOptions = {
  0: '停用',
  1: '启用'
};
const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  materialsName: '',
  createTime: []
});

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  let params = { ...queryParams.value, ...page.value };
  params.startTime = params.createTime[0] || '';
  params.endTime = params.createTime[1] || '';
  delete params.createTime;
  delete params.total;
  const res = await getData(params);
  extractLogList.value = res.rows;
  loading.value = false;
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/* 导入 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const handleImport = () => {
  upload.title = '培训学习文件上传';
  upload.open = true;
};
const uploadRef = ref<ElUploadInstance>();
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
const fileData = ref(null);
const fileValue = ref({
  fileName: '',
  ossId: '',
  url: ''
});
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  if (response.code != 200) {
    ElNotification({
      title: `${file.name}上传失败`,
      message: response.msg,
      type: 'error'
    });
    uploadRef!.clearFiles();
    return;
  }
  fileValue.value = response.data;
  fileData.value = file;
};

/** 提交上传文件 */
const submitFileForm = async () => {
  let params = { materialsId: fileValue.value.ossId, materialsName: fileValue.value.fileName, materialsUrl: fileValue.value.url };
  let res = await addFile(params);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  ElNotification({
    title: '提示',
    message: '上传成功',
    type: 'success'
  });
  uploadRef.value?.handleRemove(fileData.value);
  fileData.value = null;
  upload.open = false;
  upload.isUploading = false;
  getList();
};
const DelFile = (row) => {
  ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await delFile(row.id);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: '删除成功',
        type: 'success'
      });
      getList();
    })
    .catch(() => {});
};
const openFile = async (url, id) => {
  if (hasExpert.value) {
    await logLearn(id);
  }
  window.open(url, '__blank');
};
onActivated(() => {
  getList();
});
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scpoed>
.show-file {
  &,
  &:hover,
  &:active,
  &:focus,
  &:visited {
    cursor: pointer;
    color: var(--el-color-primary);
  }
}
</style>
