<template>
  <a-drawer
    :visible="addhomeworkVisible"
    class="drawerStyle addhomeworkDrawer"
    width="80%"
    placement="right"
    @after-visible-change="afterVisibleChange"
  >
    <div class="drawerMain">
      <div class="header">
        <div class="headerTitle">{{ edit ? "编辑" : "添加" }}作业</div>
        <img
          style="width: 29px; height: 29px; cursor: pointer"
          src="../../assets/images/basicinfo/close.png"
          @click="closeDrawer"
        />
      </div>
      <a-form
        ref="formRef"
        name="custom-validation"
        :model="formState"
        :rules="rules"
        v-bind="layout"
        @finish="handleFinish"
        @validate="handleValidate"
        @finishFailed="handleFinishFailed"
      >
        <div class="contentMain">
          <div class="main_left">
            <div class="main_item">
              <div class="btnbox">
                <a-form-item has-feedback label="作业名称" name="workName">
                  <a-input
                    v-model:value="formState.workName"
                    style="width: 424px; height: 32px; margin-left: 35px"
                    placeholder="请输入作业名称"
                    autocomplete="off"
                  />
                </a-form-item>
              </div>
            </div>
            <div class="main_item2">
              <a-form-item has-feedback label="作业要求" name="workRequirement">
                <a-textarea
                  v-model:value="formState.workRequirement"
                  placeholder="请输入作业要求"
                  autocomplete="off"
                  allow-clear
                  style="margin-left: 35px"
                  maxlength="150"
                />
              </a-form-item>
            </div>
            <div class="main_item">
              <div class="btnbox">
                <a-form-item has-feedback label="提交时间" name="choosedTime">
                  <a-range-picker
                    style="width: 424px; margin-left: 35px"
                    v-model:value="formState.choosedTime"
                    format="YYYY-MM-DD"
                    :placeholder="['      开始时间', '        结束时间']"
                  />
                </a-form-item>
              </div>
            </div>
            <div class="main_item">
              <div class="signbox">
                <div class="sign">
                  <img
                    src="@/assets/images/coursewareManage/enclosure.png"
                    alt=""
                  />
                </div>
                <span style="margin-right: 3px">附件：</span>
              </div>
              <div class="btnbox">
                <a-upload
                  v-model:file-list="fileList"
                  name="file"
                  action="/manageApi/file/upload"
                  @change="handleChange"
                >
                  <button class="xkbtn" type="button">上传附件</button>
                </a-upload>
              </div>
            </div>
            <div class="main_item" style="margin-top: -25px">
              <div class="signbox"></div>
              <div class="btnbox">
                <span style="color: #999999"
                  >支持：pdf.ppt.pptx.doc.docx.xls.xlsx.jpeg.png.gif.zip</span
                >
              </div>
            </div>
          </div>
        </div>
        <div class="main_btns">
          <a-button class="btn1" @click="closeDrawer">取消</a-button>
          <a-button class="btn2" html-type="submit" @click="cle">确定</a-button>
        </div>
      </a-form>
    </div>
    <!--  加载动画 -->
    <div class="aeLoading" :style="{ display: addLoading ? 'flex' : 'none' }">
      <a-spin :spinning="addLoading" tip="添加中..." />
    </div>
  </a-drawer>
</template>
<script>
import { reactive, ref, toRefs } from "vue";
import { message } from "ant-design-vue";
import {
  createWorkTask,
  queryWorkDetailById,
  updateWorkTaskUsing,
} from "@/api/indexWork";
import { ProjectEditTask, RouterEditTask } from "@/api/indexTask";
import dayjs from "dayjs";
import { addTempTask } from "../../api/indexTaskadd";

export default {
  name: "AddHomework",
  props: {
    addhomeworkVisible: {
      type: Boolean,
      default: false,
    },
    edit: {
      //  是否为编辑
      type: Boolean,
      default: null,
    },
    projectId: {
      type: Number,
      default: null,
    },
    chooseStageId: {
      type: Number,
      default: null,
    },
    routerTaskId: {
      type: Number,
      default: 0,
    },
    isLevel: {
      // 是否是关卡页面触发
      type: Number,
      default: null,
    },
    EditWorkId: {
      // 要编辑的workId
      type: Number,
      default: null,
    },
    projectTaskId: {
      // 要编辑的projectId
      type: Number,
      default: null,
    },
    routerId: {
      type: Number,
      default: null,
    },
    isactive: {
      type: Number,
      default: null,
    },
    faceLevel: {
      type: Boolean,
      default: false,
    },
    projectTemplateId:{
      type: Number,
      default: null,
    },
  },
  setup(props, ctx) {
    const formState = reactive({
      workName: "",
      workRequirement: "",
      choosedTime: "",
    });
    const state = reactive({
      addLoading: false,
    });
    const formRef = ref();

    let checkWorkName = async (_rule, value) => {
      if (!value) {
        return Promise.reject("请输入作业名称");
      }
    };

    let checkWorkRequirement = async (_rule, value) => {
      if (!value) {
        return Promise.reject("请输入作业要求");
      }
    };

    let checkTime = async (_rule, value) => {
      if (!value.length) {
        return Promise.reject("请选择时间");
      }
    };

    const rules = {
      workName: [
        {
          required: true,
          validator: checkWorkName,
          trigger: "change",
        },
      ],
      workRequirement: [
        {
          required: true,
          validator: checkWorkRequirement,
          trigger: "change",
        },
      ],
      choosedTime: [
        {
          required: true,
          validator: checkTime,
          trigger: "change",
        },
      ],
    };
    // const layout = {
    //   labelCol: {
    //     span: 4,
    //   },
    //   wrapperCol: {
    //     span: 14,
    //   },
    // };
    const handleFinish = () => {
      updteHomeWork();
    };

    const handleFinishFailed = () => {
      message.error("handleFinishFailed");
    };

    const resetForm = () => {
      formRef.value.resetFields();
    };

    const handleValidate = (...args) => {
      console.log(args);
    };
    const handleChange = (info) => {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }

      if (info.file.status === "done") {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 文件上传失败.`);
      }
    };

    const fileList = ref([]);
    const closeDrawer = () => {
     
     
      formState.choosedTime = "";
      ctx.emit("update:addhomeworkVisible", false);
      ctx.emit("update:edit", false);
      ctx.emit("update:EditWorkId", state.EditWorkId);
      console.log("state.EditWorkId==============",state.EditWorkId);
      localStorage.setItem("stageId", props.chooseStageId);
      localStorage.setItem("chapterId", props.isactive);
      fileList.value = [];
      resetForm();
    };
    const afterVisibleChange = () => {
      if (props.EditWorkId >0) {
        state.EditWorkId = props.EditWorkId;  
        queryWork();
      }
    };

    // 新增任务
    const updteHomeWork = () => {
      let obj = {
        submitEndTime: dayjs(formState.choosedTime[1]).format("YYYY-MM-DD"),
        submitStartTime: dayjs(formState.choosedTime[0]).format("YYYY-MM-DD"),
        workEnclosureAddress: "",
        workId: props.edit ? props.EditWorkId : 0,
        workName: formState.workName,
        workRequirement: formState.workRequirement,
      };
      if (props.EditWorkId >0) {
        updateWorkTaskUsing(obj)
          .then((res) => {
            updateTask(res);
            ctx.emit("changeData", false);
            closeDrawer();
          })
          .catch((err) => {
            message.destroy();
            message.error(`添加失败${err}`);
          });
      } else {
        createWorkTask(obj)
          .then((res) => {
            updateTask(res);
            ctx.emit("changeData", false);
            closeDrawer();
          })
          .catch((err) => {
            message.destroy();
            message.error(`添加失败${err}`);
          });
      }
    };

    // 查询任务
    const queryWork = () => {
      state.addLoading = true;
      queryWorkDetailById({ workId: props.EditWorkId })
        .then((res) => {
          formState.workName = res.data.data.workName;
          formState.workRequirement = res.data.data.workRequirement;
          formState.choosedTime = [
            dayjs(res.data.data.submitStartTime, "YYYY-MM-DD"),
            dayjs(res.data.data.submitEndTime, "YYYY-MM-DD"),
          ];
          state.addLoading = false;
        })
        .catch(() => {
          //message.error(`查询失败`);
        });
    };
    // 新增编辑或新增项目任务
    const updateTask = (res) => {
     
      if(props.faceLevel){
        state.EditWorkId = res.data.data.workId
       
      }else{
        if (props.isLevel == 1) {
              let editObj1 = {
                chapterId: props.isactive,
                courseId: res.data.data.workId,
                name: res.data.data.workName,
                routerId: props.routerId,
                routerTaskId: props.routerTaskId || 0,
                type: 4,
              };

              RouterEditTask(editObj1)
                .then(() => {
                  //message.success(`${props.EditWorkId > 0 ? "编辑" : "新增"}关卡任务成功`);
                 
                  state.addLoading = false;
                })
                .catch(() => {
                  //message.error(`${props.EditWorkId > 0 ? "编辑" : "新增"}关卡任务失败`);
                });
            } else if (props.isLevel == 2) {
              let editObj = {
                courseId: res.data.data.workId,
                name: res.data.data.workName,
                projectId: props.EditWorkId > 0 ? props.projectId : 0,
                projectTaskId: props.projectTaskId || 0,
                stageId: props.chooseStageId || 0 ,
                type: 4,
              };
              ProjectEditTask(editObj)
                .then(() => {
                  //message.success(`${props.EditWorkId > 0 ? "编辑" : "新增"}阶段任务成功`);
                 
                  state.addLoading = false;
                })
                .catch(() => {
                  //message.error(`${props.EditWorkId > 0 ? "编辑" : "新增"}阶段任务失败`);
                });
            } else if (props.isLevel == 3) {
              console.log("projectTemplateId,===",props.projectTemplateId);
              addTempTask({
                courseId: res.data.data.workId,
                name: res.data.data.workName,
                projectTemplateId:props.projectTemplateId,
                projectTaskId: props.projectTaskId || 0,
                stageId: props.chooseStageId || 0,
                type: 4,
              })
                .then(() => {
                  //message.success(`${props.EditWorkId > 0 ? "编辑" : "新增"}阶段任务成功`);
                 
                  state.addLoading = false;
                })
                .catch(() => {
                  //message.error(`${props.EditWorkId > 0 ? "编辑" : "新增"}阶段任务失败`);
                });
            }
      }
     
    };

    const cle = () => {
      console.log("xx", formState);
      let obj = {
        submitEndTime: dayjs(formState.choosedTime[1]).format("YYYY-MM-DD"),
        submitStartTime: dayjs(formState.choosedTime[0]).format("YYYY-MM-DD"),
        workEnclosureAddress: "",
        workId: props.EditWorkId > 0 ? props.EditWorkId : 0,
        workName: formState.workName,
        workRequirement: formState.workRequirement,
      };
      if (props.face) {
        createWorkTask(obj).then((res) => {
          ctx.emit("getWork", res.data.data);
        });
      }
    };

    return {
      afterVisibleChange,
      closeDrawer,
      handleChange,
      fileList,
      formState,
      handleFinish,
      handleFinishFailed,
      resetForm,
      handleValidate,
      formRef,
      // layout,
      rules,
      cle,
      ...toRefs(state),
    };
  },
};
</script>
<style lang="scss">
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa !important;
}

.addhomeworkDrawer {
  .drawerMain {
    .header {
      height: 73px;
      border-bottom: 1px solid #e8e8e8;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-shrink: 0;

      .headerTitle {
        font-size: 18px;
        font-weight: 600;
        color: #333333;
        line-height: 25px;
        margin-left: 24px;
      }
    }

    .contentMain {
      display: flex;
      justify-content: space-between;

      .main_left {
        padding-right: 30px;
        flex: 1;
        border-right: 1px solid #e8e8e8;
        margin-top: 32px;

        .main_item {
          display: flex;
          align-items: center;
          margin-top: 32px;
          margin-bottom: 32px;

          .signbox {
            width: 120px;
            display: flex;
            justify-content: end;
            align-items: center;

            .sign {
              margin-right: 5px;
            }
          }

          .btnbox {
            display: flex;
            flex: 1;
            align-items: center;

            .xkbtn {
              cursor: pointer;
              width: 130px;
              height: 40px;
              background: #388be1;
              border-radius: 8px;
              border: 0;
              margin-right: 8px;
              color: #fff;
            }
          }
        }

        .main_item2 {
          display: flex;
          align-items: flex-start;
          margin-bottom: 32px;

          .signbox {
            width: 120px;
            display: flex;
            justify-content: end;
            align-items: center;

            .sign {
              margin-right: 5px;
            }
          }

          .kqszbox {
            .qdqtbox {
              margin-left: 56px;
            }

            .setbox {
              display: flex;
              flex-wrap: wrap;
              margin-top: 10px;
              margin-bottom: 24px;

              .timerbox {
                margin-top: 6px;
                margin-right: 32px;
                display: flex;
                align-items: center;
                flex-wrap: nowrap;
              }
            }
          }

          .btnbox2 {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;

            .xkbtn {
              cursor: pointer;
              width: 130px;
              height: 40px;
              background: #388be1;
              border-radius: 8px;
              border: 0;
              margin-right: 16px 8px 32px 0;
              color: #fff;
              margin-top: 16px;
              margin-bottom: 60px;
            }
          }
        }
      }
    }

    .main_btns {
      position: absolute;
      height: 72px;
      width: 100%;
      bottom: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0px 1px 35px 0px rgba(118, 136, 166, 0.16);

      .btn1 {
        width: 100px;
        height: 40px;
        border: 1px solid #4ea6ff;
        border-radius: 8px;
        color: #4ea6ff;
        background-color: #fff;
        cursor: pointer;
      }

      .btn2 {
        cursor: pointer;
        width: 100px;
        height: 40px;
        background: #4ea6ff;
        border-radius: 8px;
        border: 0;
        margin-left: 15px;
        color: #fff;
      }
    }
  }
}
</style>

