<template>
    <el-dialog v-model="AISpeakingVisible" :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-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-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="最少时长"  style="width=300px">
        <el-input-number
          v-model="newAssignmentInfo.minDuration"
          :min="1"
          :max="120"
          placeholder="请输入最少分钟数"
          style="width:200px"
         />
        </el-form-item>
         <!-- 最少交流次数 -->
        <el-form-item label="最少交流">
          <el-input-number
            v-model="newAssignmentInfo.minInteraction"
            :min="1"
            :max="50"
            placeholder="请输入最少交流数"
            style="width:200px"
          />
        </el-form-item>
         <!-- 调查问卷链接 -->
         <el-form-item label="问卷链接">
          <div v-for="(link, index) in newAssignmentInfo.surveyLinks" :key="index" class="link-item">
            <el-input
              v-model="newAssignmentInfo.surveyLinks[index]"
              placeholder="请输入调查问卷链接"
              style="width: 150%; margin-right: 10px"
            ></el-input>
            <el-icon @click="removeSurveyLink(index)"
              :disabled="newAssignmentInfo.surveyLinks.length === 1"><Delete/></el-icon>
          </div>
          <el-button type="primary" @click="addSurveyLink">添加链接</el-button>
        </el-form-item>
        <el-form-item label="投放间隔">
          <el-input-number
            v-model="newAssignmentInfo.surveyDuration"
            :min="1"
            :max="50"
            placeholder="请输入问卷投放间隔（分钟）"
            style="width:300px"
          />
        </el-form-item>
        <div class="dialog-footer" style="margin-top:40px;margin-left: 40%">
          <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>
      </el-form>
    </el-dialog>
  </template>
  
    
    <script lang="ts" setup>
  import { reactive,ref, defineProps, watch, onMounted, inject } from "vue";
  import type { AssignmentDTO, AISpeakingAssignmentDTO } from '@/types/dto';
  import useApis from "@/apis";
  import aiSpeakingApis from "@/apis/ai_speaking_assignment"
  import { Delete} from "@element-plus/icons-vue"; // 引入图标
  import {
    ElMessage,
    ElNotification,
    type UploadFile,
    type UploadFiles,
    type UploadProps,
    type UploadUserFile,
    ElMessageBox
  } from "element-plus";
  import {useFormatDate} from "@/hooks/useFormatDate";
  const {formatDate} = useFormatDate()
  const apis = useApis();
  import {useStore} from "@/store";
  const store = useStore()
  const doRefresh:Function = inject("reload")
  const props = defineProps({
      AISpeakingVisible: Boolean,
      dialogConfig: Object,
      courseId: Number,
      assignmentId: Number
    });
  const AISpeakingVisible = ref(false)
  let uploadDescribeRef = ref()
  const describeFileList = ref([]);
  
  const newAssignmentInfo = reactive<AISpeakingAssignmentDTO>({
    assignmentName: "",
    description: "",
    descriptionFile: '',
    type: "",
    startTime: "",
    endTime: "",
    minDuration:null,
    minInteraction:null,
    surveyLinks:[''],
    surveyDuration:null
  });
  
  const initializeDialog = () => {
      if (props.dialogConfig.type === 'edit') {
        aiSpeakingApis.getAiSpeakingAssignmentById(props.dialogConfig.assignmentId).then((res) => {
          const assignment = res.data.data
          Object.assign(newAssignmentInfo, {
            assignmentName: assignment.assignmentName,
            description: assignment.description,
            descriptionFile:assignment.descriptionFile,
            type: assignment.type,
            startTime: assignment.startTime,
            endTime: assignment.endTime,
            minDuration: assignment.minDuration,
            minInteraction :assignment.minInteraction,
            surveyLinks: assignment.surveyLinks || [""], // 确保 surveyLinks 不为空
            surveyDuration:assignment.surveyDuration
      });
        });
      } else {
        cleanNewAssignmentInfo();
      }
    };
  
    const cleanNewAssignmentInfo = () => {
      Object.assign(newAssignmentInfo, {
        assignmentName: '',
        description: '',
        descriptionFile:'',
        type: '',
        startTime: '',
        endTime: '',
        minDuration:null,
        minInteraction: null,
        surveyLinks:[''],
        surveyDuration:null
      });
    };

    // 添加问卷链接
const addSurveyLink = () => {
  newAssignmentInfo.surveyLinks.push(""); // 添加一个空链接
};

// 删除问卷链接
const removeSurveyLink = (index) => {
  if (newAssignmentInfo.surveyLinks.length > 1) {
    newAssignmentInfo.surveyLinks.splice(index, 1); // 删除指定索引的链接
  }
};

const handleDescribeSuccess = (response: any) => {
    newAssignmentInfo.descriptionFile = response.data;
  };
  
  const handleDescribeError = () => {
    ElMessage.error('上传描述文件失败');
  };
  
  
  const handleDescribeExceed = (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 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);
    newAssignmentInfo.type = 'AI口语'
      if(props.dialogConfig.type == 'add'){
        aiSpeakingApis.createAiSpeakingAssignment(props.courseId, newAssignmentInfo)
        .then((res)=>{
          if(res.data.code === 200){
            ElNotification({
              title: '新增成功',
              type: 'success',
            }) 
            location.reload()
          } else {
            ElNotification({
              title: '新增失败',
              type: 'error',
            })
          }
          AISpeakingVisible.value = false
        })
        .catch((err)=> {
          console.log(err);
          ElNotification({
              title: `新增失败${err}`,
              type: 'error',
            })
            AISpeakingVisible.value = false
        })
      }else if (props.dialogConfig.type === 'edit') {
        aiSpeakingApis.updateAiSpeakingAssignment(props.dialogConfig.assignmentId, newAssignmentInfo)
        .then((res)=>{
          if(res.data.code === 200){
            ElNotification.success('修改成功')
            location.reload()
          } else {
            ElNotification.error('修改失败')
          }
          AISpeakingVisible.value = false
        })
        .catch((err)=> {
          console.log(err);
          ElNotification.error(`新增失败 ${err}`)
          AISpeakingVisible.value = false
        })
      }
      AISpeakingVisible.value = false;
      
    }

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

  const deleteAssignment = () => {
    aiSpeakingApis.deleteAiAssignmentById(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 emit = defineEmits(['update:AISpeakingVisible']);
  const closeDialog = () => {
    AISpeakingVisible.value = false;
    cleanNewAssignmentInfo();
    emit('update:AISpeakingVisible', false); // 触发父组件更新
  };
  
  // 监听父组件传递的 AISpeakingVisible 值
  watch(() => props.AISpeakingVisible, (newVal) => {
    AISpeakingVisible.value = newVal; // 同步父组件的值
    if (newVal) {
      initializeDialog();  // 弹出对话框时初始化
    } else {
      cleanNewAssignmentInfo();  // 关闭时清理数据
    }
  });
  
  onMounted(() => {
    AISpeakingVisible.value = props.AISpeakingVisible; // 初始值同步
  });
  
  
  </script>
    
  <style scoped>
  .link-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  margin-right:100px;
}

.link-item .el-button {
  margin-left: 10px;
} 
  </style>
  
  <script lang="ts">
  export default {
    name: "AISpeakingAssignmentDialogue"
  }
</script>