<template>
  <div class="h-full">
    <div class="noticeNav">
      <div class="noticNav_title">创建办事记录</div>
      <el-button type="primary" @click="submitTodo">提交</el-button>
    </div>
    <div class="noticeBox">
      <el-form label-position="top">
        <el-form-item label="需求方姓名">
          <el-input placeholder="请输入姓名" v-model="noticForm.seekName"></el-input>
        </el-form-item>
        <el-form-item label="办事时间">
          <el-date-picker
            v-model="noticForm.handleTime"
            type="datetime"
            clearable
            placeholder="年-月-日 时:分"
            value-format="YYYY-MM-DD HH:mm"
            format="YYYY-MM-DD HH:mm"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="办事内容">
          <el-input type="textarea" v-model="noticForm.content" :rows="2" placeholder="请输入办事内容"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            :auto-upload="false"
            class="upload-demo"
            :file-list="fileList"
            :action="uploadUrl"
            :multiple="true"
            ref="uploadRef"
            name="files"
            :limit="9"
            :headers="headerToken()"
            :show-file-list="true"
            :on-remove="handleAvatarRemove"
            :on-change="handleProgress"
          >
            <div class="uploadBtn flex flex-items-center">
              <el-icon><Upload /></el-icon>
              <span>上传文件</span>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { addHandleLog, uploadAttachments } from '@/api/system/HandleLog';
import { useUserStore } from '@/store/modules/user';
import { UploadFiles, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus';
import { Upload } from '@element-plus/icons-vue';

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/handleLog/uploadAttachments';
const noticForm = ref({
  content: '',
  seekName: '',
  phone: '',
  handleTime: '',
  handlePosition: '',
  handleLogFileList: [] //附件列表
});
const fileList = ref<UploadUserFile[]>([]);
const uploadRef = ref();
function headerToken() {
  const useStore = useUserStore();
  return {
    Authorization: 'Bearer ' + useStore.token
  };
}
const blockedExts = ['.exe', '.bat', '.cmd', '.msi'];
const allowExts = [
  // word
  '.doc',
  '.docx',
  '.dot',
  '.dotx',
  // excel
  '.xls',
  '.xlsx',
  '.xlsm',
  '.xlsb',
  // img
  '.jpg',
  '.jpeg',
  '.png',
  '.gif',
  '.bmp',
  '.webp',
  // 专业/矢量图
  '.psd',
  '.ai',
  '.svg',
  '.tif',
  '.tiff'
];
const handleAvatarRemove: UploadProps['onRemove'] = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  fileList.value = uploadFiles;
};
const handleProgress: UploadProps['onChange'] = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  const ext = uploadFile.name.toLowerCase().slice(uploadFile.name.lastIndexOf('.'));
  if (blockedExts.includes(ext)) {
    ElMessage.warning(`禁止上传 ${ext} 文件`);
    uploadRef.value.handleRemove(uploadFile);
    return;
  }
  if (!allowExts.includes(ext)) {
    ElMessage.warning('只允许上传word,excel和图片文件');
    uploadRef.value.handleRemove(uploadFile);
    return;
  }
  fileList.value = uploadFiles;
};

const btnloading = ref(false);
function submitTodo() {
  btnloading.value = true;
  noticForm.value.handleLogFileList = [];
  if (fileList.value.length > 0) {
    const formData = new FormData();
    fileList.value.forEach((item) => {
      formData.append('files', item.raw);
    });
    uploadAttachments(formData).then((res) => {
      if (res.data.success.length > 0) {
        res.data.success.forEach((item) => {
          const obj = {
            fileName: item.fileName,
            filePath: item.url,
            ossId: item.ossId
          };
          noticForm.value.handleLogFileList.push(obj);
        });
      }
      addHandleLog(noticForm.value)
        .then(() => {
          ElMessage.success('添加成功');
          resetTodo();
        })
        .finally(() => (btnloading.value = false));
    });
  } else {
    addHandleLog(noticForm.value)
      .then(() => {
        ElMessage.success('添加成功');
        resetTodo();
      })
      .finally(() => (btnloading.value = false));
  }
}

function resetTodo() {
  noticForm.value = {
    content: '',
    seekName: '',
    phone: '',
    handleTime: '',
    handlePosition: '',
    handleLogFileList: [] //附件列表
  };
  fileList.value = [];
  uploadRef.value && uploadRef.value.clearFiles();
}
</script>

<style lang="scss" scoped>
.noticeNav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  & .noticNav_title {
    font-size: 1rem;
  }
}
.noticeBox {
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 100%;
  }
  .upload-demo,
  :deep(.el-upload.el-upload--text) {
    width: 100%;
  }

  .upload-demo {
    &:deep(.el-upload-list) {
      max-height: 120px;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }

  .uploadBtn {
    height: 30px;
    line-height: 20px;
    border-radius: 5px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    padding-left: 20px;
    font-size: 14px;
    border: 1px solid rgba(204, 204, 204, 1);
    width: 100%;
    border: 1px solid #ccc;
    span {
      margin-left: 10px;
    }
  }
}
</style>
