<template>
  <div class="p-2 add-main">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <el-card class="h-[100%]" shadow="never">
        <template #header>
          <el-page-header @back="Cancel">
            <template #content>
              <span class="text-large font-600 mr-3"> 我的推荐 </span>
            </template>
          </el-page-header>
        </template>
        <div class="flex gap-[20px] h-[100%]">
          <el-form ref="formRef" :model="form" :rules="rules" class="flex-1 h-[100%] overflow-auto" label-width="120px">
            <el-form-item label="内容名称：" prop="suggestName">
              <el-input v-model="form.suggestName" :maxlength="20" placeholder="请输入内容名称" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="内容分享：" prop="suggestContent">
              <el-input
                v-model="form.suggestContent"
                :maxlength="200"
                :rows="5"
                placeholder="请输入内容分享"
                resize="none"
                show-word-limit
                type="textarea"
              ></el-input>
            </el-form-item>
            <el-form-item label="附件上传：" prop="file">
              <el-upload
                :action="upload.url"
                :auto-upload="true"
                :headers="upload.headers"
                :before-upload="handleBeforeUpload"
                :limit="1"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                class="upload-demo"
                drag
                style="flex: 1"
                :file-list="fileLists"
                :timeout="60000"
              >
                <el-icon class="el-icon--upload">
                  <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖动到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <div class="text-right flex-1">
                <el-button @click="Cancel">取消</el-button>
                <el-button type="primary" @click="submit">提交</el-button>
              </div>
            </el-form-item>
          </el-form>
          <div class="flex-1 h-[100%]">
            <el-card class="h-[100%] log-main" shadow="never">
              <template #header>
                <span class="text-large font-600 mr-3 lh-[24px]"> 推荐历史记录 </span>
              </template>
              <div v-for="(item, index) in logList">
                <el-divider v-if="index > 0" />
                <div>
                  <div class="flex justify-between center lh-[20px]">
                    <span class="text-[16px] font-600"> {{ item.suggestName }} </span>
                    <span class="text-[12px] color-[#999]"> {{ item.time }} </span>
                  </div>
                  <p class="text-[14px] content" :title="item.suggestContent">{{ item.suggestContent }}</p>
                  <div v-if="item.file && item.file.originalName" class="mt-[10px] mb-[10px] text-[14px] color-[#666]">附件：{{ item.file.originalName }}</div>
                  <div class="text-right">
                    <el-button link type="primary" @click="DelLog(item)">删除</el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>
    </transition>
  </div>
</template>
<script lang="ts" setup>
import { setRecommend, getLogs, delRecommend } from '@/api/study/studyRecommend';
import { globalHeaders } from '@/utils/request';
import { getFile } from '@/api/filemanage';
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const fileLists = ref([]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const formRef = ref();
const form = reactive({
  suggestName: '', //内容名称
  suggestContent: '', //内容分享
  fileId: '' //附件上传
});
const rules = {
  suggestName: [{ required: true, message: '请输入内容名称', trigger: 'blur' }],
  suggestContent: [{ required: true, message: '请输入内容分享', trigger: 'blur' }],
  fileId: [{ required: true, message: '请上传附件', trigger: 'change' }]
};
const Cancel = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace({
      path: '/study/studyRecommend'
    });
  });
};
const submit = () => {
  formRef.value.validate(async (valid: any) => {
    if (!valid) return;
    let res = await setRecommend(form);
    if (res.code === 200) {
      ElNotification({
        title: '提示',
        message: '新增成功',
        type: 'success'
      });
      Cancel()
      return;
    }
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
  });
};
const handleRemove = () => {
  form.fileId = '';
};
const handleBeforeUpload = (file: any) => {
  if (file.size > 1024 * 1024 * 100) {
    proxy?.$modal.msgWarning('文件大小不能超过100M');
    return false;
  }
  return true;
};
const handleSuccess = (res) => {
  form.fileId = res.data.ossId;
};
const handleExceed = (file: any) => {
  proxy?.$modal.msgWarning('最多只能上传1个附件');
};
const logList = ref([]);
const getLogList = async () => {
  const res = await getLogs();
  logList.value = res.data || []
  if(logList.value.length == 0) return;
  let hasFiles = logList.value.filter((item) => item.fileId);
  let ossids = hasFiles.map((e) => e.fileId).join(',');

  let fileRes = await getFile(ossids);
  if (fileRes.code != 200) {
    ElNotification({
      title: '提示',
      message: fileRes.msg,
      type: 'error'
    });
  }
  logList.value.forEach((e) => {
    e.file = fileRes.data.find((item) => item.ossId === e.fileId) || null;
  });
};
const DelLog = ({ id, suggestName }) => {
  ElMessageBox.confirm(`确定要删除 “${suggestName}” 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await delRecommend(id);
      if (res.code === 200) {
        ElNotification({
          title: '提示',
          message: '删除成功',
          type: 'success'
        });
        getLogList();
        return;
      }
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
  });
};
onMounted(() => {
  getLogList();
});
</script>

<style lang="scss" scoped>
.add-main {
  height: calc(100vh - 84px);
}

:deep(.el-card__body) {
  height: calc(100% - 46px);
}

.log-main {
  :deep(.el-card__body) {
    overflow: auto;
  }
}

.content {
  /*超出三行省略*/
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  box-orient: vertical;
}
</style>
