<template>
  <div>
    <div class="header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> 资源详情 </span>
        </template>
      </el-page-header>
    </div>

    <div class="content">
      <el-form ref="resourceFormRef" :model="form" :rules="formRules" label-width="11vw">

        <el-form-item label="资源名称：" prop="resourceName">
          <el-input :disabled="false" v-model="form.resourceName" placeholder="此处输入资源名称" />
        </el-form-item>

        <el-form-item label="资源类型：" prop="resourceClassify">
          <el-select v-model="form.resourceClassify" placeholder="此处选择资源类型" clearable>
            <el-option v-for="dict in source_classify" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="资源分类：" prop="resourceType">
          <el-select v-model="form.resourceType" placeholder="此处选择资源分类" clearable>
            <el-option v-for="dict in source_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="资源简介：" prop="resourceBrief">
          <el-input type="textarea" :rows="5" :disabled="false" v-model="form.resourceBrief" placeholder="此处输入资源简介" />
        </el-form-item>

        <el-form-item label="发表时间：" prop="resourceTime">
          <el-date-picker value-format="YYYY-MM-DD" style="width: 100%;" v-model="form.resourceTime" type="date"
            placeholder="请选择发表时间" size="default" />
        </el-form-item>

        <el-form-item label="作者：" prop="author">
          <el-input :disabled="false" v-model="form.author" placeholder="此处输入作者" />
        </el-form-item>

        <el-form-item label="发表期刊：" prop="publishJournal">
          <el-input :disabled="false" v-model="form.publishJournal" placeholder="此处输入发表期刊" />
        </el-form-item>

        <el-form-item label="期刊号：" prop="journalNo">
          <el-input :disabled="false" v-model="form.journalNo" placeholder="此处输入期刊号" />
        </el-form-item>

        <el-form-item label="论文标题：" prop="paperTitle">
          <el-input :disabled="false" v-model="form.paperTitle" placeholder="此处输入论文标题" />
        </el-form-item>

        <el-form-item label="论文附件" prop="paperAccessory">

          <el-upload v-if="type == 'add' || type == 'edit'"
                     ref="uploadLWRef"
                     v-model:file-list="fileList"
                     :limit="1"
                     accept=".pdf, .doc, .docx, .xlsx, .xls"
                     :headers="upload.headers"
                     :action="upload.url"
                     :on-success="handleUpload"
                     :on-exceed="handleExceedUploadSuccess"
                     :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、doc、docx、xls、xlsx格式文件。</span>
              </div>
            </template>
          </el-upload>

          <el-empty v-else-if="form.paperAccessory == '' || form.paperAccessory == null"></el-empty>

          <FileOrImage v-else :data="form.paperAccessory" :isEdit="false" width="120px" :dataList=[form.paperAccessory]
            height="100px" objectFit="cover">
          </FileOrImage>


        </el-form-item>

        <div v-if="type != 'add' && type != 'edit'">

          <el-form-item label="操作人：">
            <span>{{ form.userName }}</span>
          </el-form-item>

          <el-form-item label="创建时间：">
            <span>{{ form.createTime }}</span>
          </el-form-item>

          <el-form-item v-if="form.status != '1'" :label="form.status == '2' ? '上架时间：' : form.status == '3' ? '下架时间：' : ''">
            <span v-if="form.takedownTime">{{ form.takedownTime }}</span>
            <span v-else>{{ form.createTime }}</span>
          </el-form-item>

        </div>

        <div class="btn">
          <el-button v-if="type == 'edit' || type == 'add'" :loading="buttonLoading" type="primary"
            @click="submitForm">提交</el-button>
          <el-button type="danger" @click="cancel">取消</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile,UploadUserFile } from 'element-plus'
import FileOrImage from '@/components/FileOrImage/index.vue';
import { getLearningResource, updateLearningResource, addLearningResource } from '@/api/study/resource';
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { source_classify, resource_status, source_type } = toRefs<any>(proxy?.useDict('source_classify', 'resource_status', 'source_type'));
const type = computed(() => proxy.$route.query.type);
const _id = computed(() => proxy.$route.query.id);
const buttonLoading = ref(false)
const router = useRouter();
const route = useRoute();
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const goBack = () => {
  router.back();
}
const resourceFormRef = ref<ElFormInstance>();
const uploadLWRef = ref<UploadInstance>()
const fileList = ref<UploadUserFile[]>([])
const initForm = {
  resourceName: '',
  resourceClassify: '',
  resourceType: '',
  resourceBrief: "",
  resourceTime: "",
  author: "",
  publishJournal: "",
  journalNo: "",
  paperTitle: "",
  paperAccessory: "",
  status: "",
  remark: null,
  userName: "",
  createTime: "",
  takedownTime: "",
}
const form = ref({ ...initForm });
//提交
const submitForm = async () => {

  ElMessageBox.confirm('确认提交以上信息吗', {
    title: '系统确认',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    resourceFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (type.value == 'add') {

          form.value.status = '1';

          const res = await addLearningResource(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("提交成功");
            router.back();
          }

        } else if (type.value == 'edit') {
          const res = await updateLearningResource(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("修改成功");
            router.back();
          }
        }
        // const res = await addExpertRecommend(form.value).finally(() => { buttonLoading.value = false });
        // if (res.code == 200) {
        //   proxy?.$modal.msgSuccess("提交成功");
        //   router.back();
        // }
        reset();

      }

    });
  }).catch(() => {

  })

}
//重置表单
const reset = () => {
  fileList.value = []
  form.value = { ...initForm };
  resourceFormRef.value?.resetFields();
}
//取消
const cancel = () => {
  router.back();
  reset();
}

const getData = async () => {
  fileList.value = []
  if (_id.value.toString() == '' || null) {
    return
  }
  const res = await getLearningResource(_id.value.toString());
  fileList.value = [{
    name: res.data?.originalName,
    url: res.data?.url
  }]
  Object.assign(form.value, res.data);

}
// 附件上传成功处理上传覆盖
const handleExceedUploadSuccess: UploadProps['onExceed'] = (files) => {
  uploadLWRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadLWRef.value!.handleStart(file)
  uploadLWRef.value!.submit()
}
/** 附件上传成功处理 */
const handleUpload = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {

  form.value.paperAccessory = response.data.ossId;

  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '上传论文结果', {
    dangerouslyUseHTMLString: true
  });
};
onActivated(() => {
  if (type.value == 'add') {
    reset();
    return
  }
  getData();

})
onMounted(() => {
  if (type.value == 'add') {
    reset();
    return
  }
  getData();
})

const formRules = ref({
  resourceName: [{ required: true, message: '资源名称不能为空', trigger: 'blur' }],
  resourceClassify: [{ required: true, message: '资源类型不能为空', trigger: 'blur' }],
  resourceType: [{ required: true, message: '资源分类不能为空', trigger: 'blur' }],
  resourceBrief: [{ required: true, message: '资源简介不能为空', trigger: 'blur' }],
  resourceTime: [{ required: true, message: '发表时间不能为空', trigger: 'blur' }],
  author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
  publishJournal: [{ required: true, message: '发表期刊不能为空', trigger: 'blur' }],
  journalNo: [{ required: true, message: '期刊号不能为空', trigger: 'blur' }],
  paperTitle: [{ required: true, message: '论文标题不能为空', trigger: 'blur' }],
  paperAccessory: [{ required: true, message: '论文附件不能为空', trigger: 'blur' }],
})
</script>

<style lang="scss" scoped>
.header {
  margin: 1vh 0 0 2vw;

}

.el-form {
  margin-top: 2vh;
  margin-left: 2vw;
  width: 40%;
}

.btn {
  width: 60%;
  margin: 1vh auto 2vh;
  display: flex;
  justify-content: space-evenly;

  .el-button {
    width: 30%;
  }
}
</style>
