<template>
  <a-drawer
    :visible="addtestVisible"
    class="drawerStyle addtestDrawer"
    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="examinationName">
              <a-input
                v-model:value="formState.examinationName"
                style="width: 424px; height: 32px;margin-left: 35px;"
                autocomplete="off"
                placeholder="请输入考试名称"
                maxlength="20"/>
              </a-form-item>
            </div>
          </div>
          <div class="main_item2">
            <a-form-item has-feedback label="考试说明" name="examinationExplain">
              <a-textarea
                v-model:value="formState.examinationExplain"
                placeholder="请输入考试说明"
                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="choosedTest">
              <a-select
                dropdownClassName="dropdown-style"
                style="width: 424px;margin-left: 35px;"
                placeholder="请输入考试名称"
                :options="options1"
                v-model:value="formState.choosedTest"
                allowClear
                showSearch
              />
            </a-form-item>
 
            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <a-form-item has-feedback label="考试时间" name="choosedTime">

              <a-range-picker
              v-model:value="formState.choosedTime"
              format="YYYY-MM-DD"
                style="width: 424px;margin-left: 35px;"
                :placeholder="['      开始时间', '        结束时间']"
              />
            </a-form-item>
            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <a-form-item has-feedback label="考试时长" name="examinationDuration">

              <a-input
                v-model:value="formState.examinationDuration"
                type="number"
                style="width: 388px; height: 32px;
                margin-left: 35px;"
              />
              
            </a-form-item>
            <span style="transform: translateY(-50%)">分钟</span>
            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <span style="margin-right: 43px">考试限制</span>
              <a-form-item has-feedback label="允许重复考试" name="examinationLimit">

              <a-input-number
                :min="-1" :precision="0"
                type="number"
                v-model:value="formState.examinationLimit"
                style="width: 88px; height: 32px;
                border-radius: 8px;overflow: hidden;"
              />
              <span style="margin-left: 8px">次</span>
              <span style="margin-left: 24px; color: #999999"
                >-1表示无限制</span>
            </a-form-item>
              
              
            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <a-form-item has-feedback label="显示答案" name="showAnswers">

              <a-radio-group style="margin-left: 35px;margin-right: 12px;" v-model:value="formState.showAnswers">
                <a-radio v-model:checked="checked" :value="1" @click="cloradio1">允许查看</a-radio>
                <a-radio v-model:checked="checked" :value="2" @click="cloradio1"
                  >不允许查看</a-radio
                >
              </a-radio-group>
            </a-form-item>

            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <a-form-item has-feedback label="显示解析" name="showAnalysis">

              <a-radio-group style="margin-left: 35px;margin-right: 12px;" v-model:value="formState.showAnalysis">
                <a-radio v-model:checked="checked" :value="1" @click="cloradio2">允许查看</a-radio>
                <a-radio v-model:checked="checked" :value="2" @click="cloradio2"
                  >不允许查看</a-radio
                >
              </a-radio-group>
            </a-form-item>

            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <a-form-item has-feedback label="评分模式" name="scoringModel">

                <a-radio-group style="margin-left: 35px;margin-right: 12px;" v-model:value="formState.scoringModel">
                  <a-radio v-model:checked="checked" :value="1" @click="cloradio3"
                    >最高一次</a-radio
                  >
                  <a-radio v-model:checked="checked" :value="2" @click="cloradio3"
                    >最后一次</a-radio
                  >
                </a-radio-group>
              </a-form-item>
            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <a-form-item has-feedback label="及格线" name="passLine">

              <a-input
                v-model:value="formState.passLine"
                type="number"
                style="width: 88px; height: 32px;margin-left: 35px;"
              />
            </a-form-item>

              <span style="margin-left: 8px">分</span>
            </div>
          </div>
          <div class="main_item">
            <div class="btnbox">
              <a-form-item has-feedback label="作业要求" name="questionArrangement">

              <a-radio-group
              style="margin-right:12px;"
              v-model:value="formState.questionArrangement">
                <a-radio v-model:checked="checked" :value="1" @click="cloradio4">试题乱序</a-radio>
                <a-radio v-model:checked="checked" :value="2" @click="cloradio4">试题排序</a-radio>
                <a-radio v-model:checked="checked" :value="3" @click="cloradio4">全部乱序</a-radio>
              </a-radio-group>
            </a-form-item>

            </div>
          </div>
        </div>
      </div>
      <div class="main_btns">
        <a-button class="btn1" @click="closeDrawer">取消</a-button>
        <a-button class="btn2" html-type="submit" >确定</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 {createExamination,queryExaminationDetailById,updateExamination} from "@/api/indexExam"
import { ProjectEditTask, RouterEditTask } from "@/api/indexTask"

import  dayjs from 'dayjs';
const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
});
export default {
  name: "AddTest",
  // components: {
  // },
  props: {
    addtestVisible: {
      type: Boolean,
      default: false,
    },
    EditTestId: { // 要编辑的考试id
      type: Number,
      default: -1,
    },
    isactive: {
      type: Number,
      default: null,
    },
    routerId: {
      type: Number,
      default: null,
    },
    projectId: {
      type: Number,
      default: null,
    },
    routerTaskId: {
      type: Number,
      default: null,
    },
    chooseStageId: {
      type: Number,
      default: null,
    },
    isLevel: { // 是否是关卡页面触发
      type: Boolean,
      default: null,
    },
    projectTaskId: { // 要编辑的projectId 
      type: Number,
      default: null,
    },
    edit: { //
      type: Boolean,
      default: null,
    },
  },
  setup(props, ctx) {
    const formState = reactive({
      examinationName:'',
      examinationDuration:"",
      examinationLimit:"",
      passLine:60,
      examinationEndTime:"",
      examinationExplain:"",
      questionArrangement:1,
      scoringModel:2,
      showAnalysis:2,
      showAnswers:2,
      choosedTime:'',
    });
    const state = reactive({
      addLoading: false,
    })
    const formRef = ref();
    let checkExaminationName = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入考试名称');
      }
    };
    let checkExaminationExplain = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入考试说明');
      }
    };
    let checkChoosedTest = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请选择考试');
      }
    };
    let checkChoosedTime = async (_rule, value) => {
      if (!value.length) {
        return Promise.reject('请选择时间');
      }
    };
    let checkExaminationDuration = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入考试时长');
      }
    };
    let checkLimit = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入考试限制');
      }
    };
    let checkShowAnswers = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入作业名称');
      }
    };
    let checkShowAnalysis = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入作业名称');
      }
    };
    let checkScoringModel = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入作业名称');
      }
    };
    let checkPassLine = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入及格线');
      }
    };
    let checkQuestionArrangement = async (_rule, value) => {
      if (!value) {
        return Promise.reject('请输入作业名称');
      }
    };
    const rules = {
      examinationName: [{
        required: true,
        validator: checkExaminationName,
        trigger: 'change',
      }],
      examinationExplain: [{
        validator: checkExaminationExplain,
        trigger: 'change',
      }],
      choosedTest: [{
        required: true,
        validator: checkChoosedTest,
        trigger: 'change',
      }],
      choosedTime: [{
        required: true,
        validator: checkChoosedTime,
        trigger: 'change',
      }],
      examinationDuration: [{
        required: true,
        validator: checkExaminationDuration,
        trigger: 'change',
      }],
      limit: [{
        required: true,
        validator: checkLimit,
        trigger: 'change',
      }],
      showAnswers: [{
        validator: checkShowAnswers,
        trigger: 'change',
      }],
      showAnalysis: [{
        validator: checkShowAnalysis,
        trigger: 'change',
      }],
      scoringModel: [{
        validator: checkScoringModel,
        trigger: 'change',
      }],
      passLine: [{
        required: true,
        validator: checkPassLine,
        trigger: 'change',
      }],
      questionArrangement: [{
        validator: checkQuestionArrangement,
        trigger: 'change',
      }],
    };

    const options1 = ref([
      {
        label:'math',
        value:'math',
      },
      {
        label:'eng',
        value:'eng',
      },
    ])
    const handleFinish = values => {
      console.log(values);
      updateTest();
    };

    const handleFinishFailed = errors => {
      console.log(errors);
      // message.error("handleFinishFailed");
    };

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

    const handleValidate = (...args) => {
      console.log(args);
    };
    const closeDrawer = () => {
      resetForm();
      formState.choosedTime = '';
      ctx.emit("update:addtestVisible", false);
      ctx.emit("update:edit", false);
    };
    const afterVisibleChange = (bool) => {
      console.log(props.edit);
      if (props.addtestVisible && props.edit) { // 该页面显示同时 edit为true 时，发送查询请求, 
        queryTest()
      }
      console.log("formState", bool);
    };
    const queryTest = () => {
      state.addLoading = true;
      console.log(props.EditTestId);
      queryExaminationDetailById({examinationId:props.EditTestId}).then((res) => {
        formState.examinationName = res.data.data.examinationName;
        formState.workRequirement = res.data.data.workRequirement;
        formState.examinationDuration = res.data.data.examinationDuration;
        formState.examinationLimit = Number(res.data.data.examinationLimit) || -1;
        formState.passLine = res.data.data.passLine;
        formState.examinationExplain = res.data.data.examinationExplain;
        formState.questionArrangement = Number(res.data.data.questionArrangement) || 1;
        formState.scoringModel = Number(res.data.data.scoringModel) || 1;
        formState.showAnalysis = Number(res.data.data.showAnalysis) || 1;
        formState.showAnswers = Number(res.data.data.showAnswers )|| 1;
        if(res.data.data.examinationEndTime && res.data.data.examinationStartTime){
          formState.choosedTime= [dayjs(res.data.data.examinationStartTime,"YYYY-MM-DD"),dayjs(res.data.data.examinationEndTime,"YYYY-MM-DD")]
          state.addLoading = false;
        } else { formState.choosedTime=[] }
        console.log(res);
      }).catch(() => {
        message.error(`查询失败`)
      })
    }
    const updateTest = () => {
      state.addLoading = true;
        if(props.edit) { // 编辑任务
          myUpdateExamination()
        }else { // 创建任务
          myCreateExamination()
        }
    }
    
    const myUpdateExamination = () => {
      let obj = {
            "createTime": "",
            "createUser": 0,
            "examinationDuration": formState.examinationDuration,
            "examinationEndTime": dayjs(formState.choosedTime[1]).format("YYYY-MM-DD"),
            "examinationExplain": formState.examinationExplain,
            "examinationFlag": "",
            "examinationId":  props.EditTestId,
            "examinationLimit": formState.examinationLimit,
            "examinationName": formState.examinationName,
            "examinationPaperId": 0,
            "examinationPaperName": formState.choosedTest,
            "examinationStartTime": dayjs(formState.choosedTime[0]).format("YYYY-MM-DD"),
            "examinationTag": "",
            "passLine": formState.passLine,
            "questionArrangement": formState.questionArrangement,
            "scoringModel": formState.scoringModel,
            "showAnalysis": formState.showAnalysis,
            "showAnswers": formState.showAnswers,
            "updateTime": "",
            "updateUser": 0
      }
      updateExamination(obj).then((res)=>{
        console.log(res);
        // 如果是关卡页面进入 ---------------------------------
        if(props.isLevel) {
          myRouterEditTask(res.data.data.examinationId)
        }else { 
          myProjectEditTask(res.data.data.examinationId)
        }
      }).catch(()=>{
        message.error(`编辑失败`)
      })

    }
    const myCreateExamination = () => {
      let obj = {
            "createTime": "",
            "createUser": 0,
            "examinationDuration": formState.examinationDuration,
            "examinationEndTime": dayjs(formState.choosedTime[1]).format("YYYY-MM-DD"),
            "examinationExplain": formState.examinationExplain,
            "examinationFlag": "",
            "examinationId":  0,
            "examinationLimit": formState.examinationLimit,
            "examinationName": formState.examinationName,
            "examinationPaperId": 0,
            "examinationPaperName": formState.choosedTest,
            "examinationStartTime": dayjs(formState.choosedTime[0]).format("YYYY-MM-DD"),
            "examinationTag": "",
            "passLine": formState.passLine,
            "questionArrangement": formState.questionArrangement,
            "scoringModel": formState.scoringModel,
            "showAnalysis": formState.showAnalysis,
            "showAnswers": formState.showAnswers,
            "updateTime": "",
            "updateUser": 0
      }
      createExamination(obj).then((res)=>{
        if(props.isLevel) {
          myRouterEditTask(res.data.data.examinationId)
        }else { 
          myProjectEditTask(res.data.data.examinationId)
        }
      }).catch((err)=>{
        message.error(`添加失败${err}`)
      })
    }
    const myProjectEditTask = (testId) => {
      let editObj = {
        "courseId": testId,
        "duration": 50,
        "flag": true,
        "name": formState.examinationName,
        "projectId": props.projectId,
        "projectTaskId": props.projectTaskId || null,
        "stageId": props.chooseStageId,
        "type": 5
      }
       // 新增编辑或新增项目
       ProjectEditTask(editObj).then(res => {
        console.log(` 编辑项目成功的打印 ${res}`);
        message.success(`${props.EditTestId? '编辑' : '新增'}阶段任务成功`)
        ctx.emit("changeData", false);
        state.addLoading = false;
        closeDrawer();
      }).catch(err => {
        message.error(`${props.EditTestId? '编辑' : '新增'}阶段任务失败`)
        console.log(` 编辑项目失败的打印 ${err}`);
      })
    }

    const myRouterEditTask = (testId) => {
      let editObj1 = {
            "chapterId": props.isactive,
            "courseId": testId,
            "duration": 30,
            "flag": true,
            "name": formState.examinationName,
            "routerId": props.routerId,
            "routerTaskId":  props.routerTaskId || 0,
            "type": 5
          }

          RouterEditTask(editObj1).then(res => {
            console.log(` 编辑关卡成功的打印 ${res}`);
            message.success(`${props.edit ? '编辑' : '新增'}关卡任务成功`)
            ctx.emit("changeData", false);
            state.addLoading = false;
            closeDrawer();
          }).catch(err => {
            message.error(`${props.edit ? '编辑' : '新增'}关卡任务失败`)
            console.log(` 编辑关卡失败的打印 ${err}`);
          })
    }

    const cloradio1 = (value) => {
      if (value != "") {
        formState.showAnswers = "";
      }
    }
    const cloradio2 = (value) => {
      if (value != "") {
        formState.showAnalysis = "";
      }
    }
    const cloradio3 = (value) => {
      if (value != "") {
        formState.scoringModel = "";
      }
    }
    const cloradio4 = (value) => {
      if (value != "") {
        formState.questionArrangement = "";
      }
    }
    return {
      formState,
      afterVisibleChange,
      closeDrawer,
      rowSelection,
      cloradio1,
      cloradio2,
      cloradio3,
      cloradio4,
      options1,
      handleFinish,
      handleFinishFailed,
      resetForm,
      handleValidate,
      formRef,
      // layout,
      rules,
      updateTest,
      queryTest,
      ...toRefs(state)
    };
  },
};
</script>
  <style lang="scss">
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa !important;
}
.addtestDrawer {
  .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;
        .main_item {
          display: flex;
          align-items: center;
          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 {
      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>
  