<template>
    <el-dialog v-model="writingVisible" :title="dialogConfig.title"  
    @close="closeDialog"
    :before-close="closeDialog">
      <el-form :model="newAssignmentInfo" label-width="auto">
        <el-form-item label="作业名称">
          <el-input v-model="newAssignmentInfo.assignmentName" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="作业描述">
          <el-input v-model="newAssignmentInfo.description" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="newAssignmentInfo.startTime" type="datetime" placeholder="开始时间" style="width: 180px"/>
        </el-form-item>
        <el-form-item label="截止时间">
          <el-date-picker v-model="newAssignmentInfo.endTime" type="datetime" placeholder="截止时间" style="width: 180px"/>
        </el-form-item>
        <el-form-item label="描述文件">
          <el-upload
            ref="uploadDescribeRef"
            action="/api/file"
            multiple
            v-model:file-list="describeFileList"
            :limit="1"
            :on-success="handleDescribeSuccess"
            :on-error="handleDescribeError"
            :on-exceed="handleDescribeExceed"
            :on-change="handleDescribeChange"
            accept=".doc, .docx"
            :auto-upload="false"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                doc/docx 文件不大于 500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            ref="uploadPictureRef"
            action="/api/file"
            multiple
            v-model:file-list="pictureFileList"
            :limit="1"
            :on-success="handlePictureSuccess"
            :on-error="handlePictureError"
            :on-exceed="handlePictureExceed"
            :on-change="handlePictureChange"
            accept=".doc, .docx"
            :auto-upload="false"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                doc/docx 文件不大于 500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
                  <!-- TODO:有点问题 总是删除失败 -->
          <el-button v-if="dialogConfig.type==='edit'" type="danger" @click="confirmDelete()">删除作业</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, watch, defineProps, defineEmits, onMounted, inject } from 'vue';
  import { dialogEmits, ElMessage, ElNotification, ElMessageBox } from 'element-plus';
  import { AssignmentDTO } from '@/types/dto';
  import useApis from "@/apis";
  import {useFormatDate} from "@/hooks/useFormatDate";
  const {formatDate} = useFormatDate()
  import {useStore} from "@/store";
  const apis = useApis()
  const store = useStore()
  const doRefresh:Function = inject("reload")
  const props = defineProps({
    writingVisible: Boolean,
    dialogConfig: Object,
    courseId: Number
  });
  let uploadDescribeRef = ref()
  let uploadPictureRef = ref()
  const writingVisible = ref(false)
  const newAssignmentInfo = reactive<AssignmentDTO>({
    assignmentName: '',
    description: '',
    type: '',
    descriptionFile: '',
    attachments: [''],
    startTime: '',
    endTime: '',
  });
  
  const describeFileList = ref([]);
  const pictureFileList = ref([]);
  
  const initializeDialog = () => {
    if (props.dialogConfig.type === 'edit') {
      // 通过 ID 获取作业详细信息并填充
      apis.getAssignmentById(props.dialogConfig.assignmentId).then((res) => {
      const assignment = res.data.data
        Object.assign(newAssignmentInfo, {
          assignmentName: assignment.assignmentName,
          description: assignment.description,
          type: assignment.type,
          descriptionFile: assignment.descriptionFile,
          attachments: assignment.attachments,
          startTime: assignment.startTime,
          endTime: assignment.endTime,
    });
      });
    } else {
      cleanNewAssignmentInfo();
    }
  };
  
  const handleDescribeSuccess = (response: any) => {
    newAssignmentInfo.descriptionFile = response.data;
  };
  
  const handlePictureSuccess = (response: any) => {
    newAssignmentInfo.attachments[0] = response.data;
  };
  
  const handleDescribeError = () => {
    ElMessage.error('上传描述文件失败');
  };
  
  const handlePictureError = () => {
    ElMessage.error('上传附件失败');
  };
  
  const handleDescribeExceed = (files: any) => {
    ElMessage.error('上传文件超过限制');
  };
  
  const handlePictureExceed = (files: any) => {
    ElMessage.error('上传文件超过限制');
  };
  
  //选择文件
  const handleDescribeChange = (file,fileList) => {
    // console.log(file)
    const fileImgType = file.name.match(/\.([^\.]+)$/)[1];  //匹配文件格式（最后一个'.'后的格式）或者匹配file.raw.type
    const isImageType = ['doc','docx'];
    const isLt500KB = file.size / 1024  < 500;  //判断图片格式与大小
    if (isImageType.indexOf(fileImgType)==-1) {
      ElMessage.error('文件仅支持png、jpg格式')  //限制文件类型
      uploadDescribeRef.value.clearFiles()  //清空上传文件
      return false;
    }
    if (!isLt500KB) {
      ElMessage.error('文件不能超过500kb!')  //限制文件大小
      uploadDescribeRef.value.clearFiles()  //清空上传文件
      return false;
    }
    apis.uploadFile(file.raw)
        .then((res) => {
          newAssignmentInfo.descriptionFile = res.data.data
        })
        .catch((err) => {
          console.log(err)
        })
  }
   
  
  const handlePictureChange = (file,fileList) => {
    // console.log(file)
    const fileImgType = file.name.match(/\.([^\.]+)$/)[1];  //匹配文件格式（最后一个'.'后的格式）或者匹配file.raw.type
    // const isImageType = ['png','jpg'];
    const isImageType = ['doc','docx'];
    const isLt500KB = file.size / 1024  < 500;  //判断图片格式与大小
    if (isImageType.indexOf(fileImgType)==-1) {
      ElMessage.error('文件仅支持png、jpg格式')  //限制文件类型
      uploadDescribeRef.value.clearFiles()  //清空上传文件
      return false;
    }
    if (!isLt500KB) {
      ElMessage.error('文件不能超过500kb!')  //限制文件大小
      uploadDescribeRef.value.clearFiles()  //清空上传文件
      return false;
    }
    apis.uploadFile(file.raw)
        .then((res) => {
          newAssignmentInfo.attachments[0] = res.data.data
        })
        .catch((err) => {
          console.log(err)
        })
  }
  
  const handleSubmit = async () => {
    if(newAssignmentInfo.assignmentName === '') {
      ElNotification({title: '作业名称不得为空',type: 'error',})
      return
    }
    if(newAssignmentInfo.description === '') {
      ElNotification({title: '作业描述不得为空',type: 'error',})
      return
    }

    if(newAssignmentInfo.startTime === '') {
      ElNotification({title: '开始时间不得为空',type: 'error',})
      return
    }
    if(newAssignmentInfo.endTime === '') {
      ElNotification({title: '结束时间不得为空',type: 'error',})
      return
    }
    if(newAssignmentInfo.startTime >= newAssignmentInfo.endTime) {
      ElNotification({title: '结束时间不得在起始时间之前',type: 'error',})
      return
    }
    newAssignmentInfo.endTime = formatDate(newAssignmentInfo.endTime);
    newAssignmentInfo.startTime = formatDate(newAssignmentInfo.startTime);
    if (props.dialogConfig.type === 'add') {
      newAssignmentInfo.type = '写作'
      apis.createAssignment(props.courseId, newAssignmentInfo)
      .then((res)=>{
        if(res.data.code === 200){
          ElNotification({
            title: '新增成功',
            type: 'success',
          })
          location.reload()
        } else {
          ElNotification({
            title: '新增失败',
            type: 'error',
          })
        }
        writingVisible.value = false
      })
      .catch((err)=> {
        console.log(err);
        ElNotification({
            title: `新增失败${err}`,
            type: 'error',
          })
          writingVisible.value = false
      })
    } else if (props.dialogConfig.type === 'edit') {
      apis.updateAssignment(props.dialogConfig.assignmentId, newAssignmentInfo)
      .then((res)=>{
        if(res.data.code === 200){
          ElNotification.success('修改成功')
          location.reload()
        } else {
          ElNotification.error('修改失败')
        }
        writingVisible.value = false
      })
      .catch((err)=> {
        console.log(err);
        ElNotification.error(`新增失败 ${err}`)
        writingVisible.value = false
      })
    }
    writingVisible.value = false;
  };

  //传teacherId:number, assignmentId:number
  const confirmDelete = () => {
    ElMessageBox.confirm('确定要删除这个作业吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteAssignment();
    }).catch(() => {
      // 用户选择取消，什么都不做
    });
  };

  const deleteAssignment = () => {
    apis.deleteAssignmentById(store.user.id,props.dialogConfig.assignmentId)
      .then((res: any) => {
        if (res.data.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          });
          // 这里可以调用刷新数据的方法
          doRefresh();
        } else {
          ElMessage({
            type: 'error',
            message: '删除失败!'+res.data.message
          });
        }
      })
      .catch((err) => {
        console.log(err);
        ElMessage({
          type: 'error',
          message: '请求出错!'
        });
      });
  };
  
  const cleanNewAssignmentInfo = () => {
    Object.assign(newAssignmentInfo, {
      assignmentName: '',
      description: '',
      type: '',
      descriptionFile: '',
      attachments: [''],
      startTime: '',
      endTime: '',
    });
  };
  const emit = defineEmits(['update:writingVisible']);
  const closeDialog = () => {
    writingVisible.value = false;
    cleanNewAssignmentInfo()
    emit('update:writingVisible', false); 
  };
 
  watch(() => props.writingVisible, (newVal) => {
  writingVisible.value = newVal;  // 监听父组件的 visible 变化，确保同步
  if (newVal) {
    initializeDialog();  // 每次弹出对话框时初始化
  } else {
    cleanNewAssignmentInfo();  // 关闭时清理数据
  }
});
  onMounted (()=>{
    writingVisible.value = props.writingVisible
  })
  </script>
  
  <style scoped>
  .dialog-footer {
    text-align: right;
  }
  
  </style>

  <script lang="ts">
  export default {
    name: "WritingAssignmentDialogue"
  }
</script>


  