<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="learningToolFormRef" :model="form" :rules="formRules" label-width="150px">
        <!-- <el-form-item label="应用工具编号" prop="id">
          <el-input v-model="form.id" placeholder="请输入应用工具编号" />
        </el-form-item> -->
        <el-form-item label="应用工具名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入应用工具名称" />
        </el-form-item>
        <el-form-item label="附件" prop="attachment">

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

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

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

        </el-form-item>
        <el-form-item label="应用工具简介" prop="remark">
          <el-input type="textarea" :rows="5" v-model="form.remark" placeholder="请输入应用工具简介" />
        </el-form-item>

        <!-- <el-form-item v-if="type != 'add' && type != 'edit'" label="发布状态" prop="status">
          <el-select v-model="form.status" placeholder="此处选择单位类型" clearable>
            <el-option v-for="dict in is_publish" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item> -->

        <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, UploadProps, UploadRawFile} from "element-plus";
import FileOrImage from '@/components/FileOrImage/index.vue';
import { getLearningTool, updateLearningTool, addLearningTool } from '@/api/study/tool';
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { give_course_type, resource_status, course_type } = toRefs<any>(proxy?.useDict('give_course_type', 'resource_status', 'course_type'));
const type = computed(() => proxy.$route.query.type);
const _id = computed(() => proxy.$route.query.id);
const buttonLoading = ref(false)
const router = useRouter();
const { is_publish } = toRefs<any>(proxy?.useDict('is_publish'));
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 learningToolFormRef = ref<ElFormInstance>();
const uploadLWRef = ref<ElUploadInstance>()
const attachment = ref([])
const initForm = {
  id: undefined,
  name: undefined,
  attachment: undefined,
  status: undefined,
  remark: undefined,
}
const form = ref({ ...initForm });
//提交
const submitForm = async () => {

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

          form.value.status = '1';

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

        } else if (type.value == 'edit') {
          const res = await updateLearningTool(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 handleAvatarSuccess = (res: any) => {
  console.log(`handleAvatarSuccess..`, res);

  // 如果上传成功
  if (res.code === 200) {
    // form.value.coursePic = res.data.url;
    proxy?.$modal.closeLoading();
  } else {
    proxy?.$modal.msgError('图片插入失败');
    proxy?.$modal.closeLoading();
  }
}

//上传失败
const handleUploadError = (err: any) => {
  proxy?.$modal.msgError('上传文件失败');
};
//上传之前
const beforeAvatarUpload = (file: any) => {
  const type = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg'];
  const isJPG = type.includes(file.type);
  //检验文件格式
  if (!isJPG) {
    proxy?.$modal.msgError(`图片格式错误!`);
    return false;
  }
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 10;
  if (!isLt) {
    proxy?.$modal.msgError(`上传图片大小不能超过 10 MB!`);
    return false;
  }
  proxy?.$modal.loading('正在上传文件，请稍候...');
  return true;
}
//重置表单
const reset = () => {
  form.value = { ...initForm };
  learningToolFormRef.value?.resetFields();
}
//取消
const cancel = () => {
  router.back();
  reset();
}
//获取数据详情
const getData = async () => {
  attachment.value = []
  if (_id.value.toString() == '' || null) {
    return
  }
  const res = await getLearningTool(_id.value.toString());
  if (res.data.originalName) {
    attachment.value = [{
      url: res.data.url,
      name: res.data.originalName
    }]
  }
  // if (res.data.coursePic) {
    // form.value.coursePic = res.data.coursePic;
  // }
  Object.assign(form.value, res.data);

}

const handleExceedUpload: 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.attachment = 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({
  name: [{ required: true, message: '工具名称不能为空', trigger: 'blur' }],
  attachment: [{ 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 {
  margin-top: 1vh;
  width: 60%;
  margin: 0 auto;
  display: flex;
  justify-content: space-evenly;

  .el-button {
    width: 30%;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-upload) {
  border: 1px dashed #3d3d3d;
  //border-radius: 1vw;
}
</style>
