<template>
  <a-drawer
    :visible="openCourseVisible"
    class="drawerStyle growth-open-course"
    :width="1000"
    title="开课"
    placement="right"
  >
    <div class="drawerMain">
      <div class="header">
        <div class="headerTitle">{{ title }}</div>
        <img
          style="width: 29px; height: 29px; cursor: pointer"
          src="../../assets/images/basicinfo/close.png"
          @click="closeDrawer"
        />
      </div>
      <div v-show="step == 1">
        <div class="contentMain">
          <div class="main_items">
            <div class="mi_ipts">
              <div class="mii_ipt">
                <div class="ipt_name"></div>
                <div class="fi_input">
                  <a-input
                    v-model:value="params.name"
                    style="width: 220px; height: 40px; border-radius: 8px"
                    placeholder="请输入创建人"
                    maxlength="20"
                  />
                </div>
              </div>
              <div class="mii_ipt">
                <div class="ipt_name"></div>
                <div class="fi_input">
                  <a-input
                    v-model:value="params.teacher"
                    style="width: 220px; height: 40px; border-radius: 8px"
                    placeholder="请输入教师名称"
                    maxlength="20"
                  />
                </div>
              </div>
              <div class="mii_ipt">
                <div class="ipt_name"></div>
                <div class="fi_input">
                  <RangePicker
                    ref="resetTime"
                    v-model:beginTime="params.createBeginTime"
                    v-model:endTime="params.createEndTime"
                  />
                </div>
              </div>
            </div>
            <div class="mi_btns" style="margin-left: 0">
              <div class="btn btn2" @click="search">
                <div class="search"></div>
                <div class="btnText">搜索</div>
              </div>
              <div class="btn btn2" @click="reset">
                <div class="search"></div>
                <div class="btnText">重置</div>
              </div>
            </div>
          </div>
          <div class="main_item">
            <button class="xkbtn" @click="createNewCourse">新建开课</button>
          </div>
          <div class="main_table">
            <div class="drawerbox">
              <BaseTable
                ref="tableRef"
                :url="COURSE_PLAN_PAGE"
                v-model:params="params"
                :columns="columns"
                :request="useRowsPageNoInit"
              />
            </div>
          </div>
        </div>
        <div class="main_btns">
          <button @click="closeDrawer" class="btn2">取消</button>
          <button @click="confirm" class="btn2">确定</button>
        </div>
      </div>

      <template v-if="step == 2">
        <div class="createschooltime">
          <div class="cst_main">
            <div class="cstm_title">
              <span>面授名称：{{ courseName }}</span>
            </div>
            <div class="cstm_items" style="align-items: flex-start">
              <div class="signbox" style="position: relative; top: 11px">
                <div class="sign">
                  <img
                    src="@/assets/images/coursewareManage/asterisk.png"
                    alt=""
                  />
                </div>
                <span style="margin-right: 3px">开课名称</span>
              </div>
              <div class="b_input">
                <NameInput
                  maxlength="30"
                  v-model:value="formData.name"
                  v-model:validated="validated"
                  :id="formData.id"
                  show-count
                  :onceName="onceName"
                  :type="5"
                  style="width: 440px; height: 40px; border-radius: 8px"
                  placeholder="请输入开课名称"
                  :disabled="editBeginClass"
                  :changeName="changeName"
                ></NameInput>
              </div>
            </div>
            <div class="cstm_items">
              <div class="signbox">
                <div class="sign">
                  <img
                    src="@/assets/images/coursewareManage/asterisk.png"
                    alt=""
                  />
                </div>
                <span style="margin-right: 3px">面授时间</span>
              </div>
              <div class="select fitems">
                <!-- <a-range-picker
                style="width: 88%; height: 40px; border-radius: 8px"
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm"
                v-model:value="dateTime"
                @change="timeChange"
                separator="至"
                :placeholder="['        开始时间', '        结束时间']"
                :disabled="editBeginClass"
              /> -->
                <a-date-picker
                  style="width: 41%; height: 40px; border-radius: 8px"
                  :show-time="{ format: 'HH:mm' }"
                  :format="['YYYY-MM-DD HH:mm', 'YYYY/MM/DD HH:mm']"
                  valueFormat="YYYY-MM-DD HH:mm"
                  v-model:value="dateTime[0]"
                  @change="timeChange"
                  :placeholder="'        开始时间'"
                  :disabled="editBeginClass"
                  @blur="onBlurStart"
                  @focus="onFocusStart"
                  @select="onDateSelect"
                  :open="openStart"
                  @ok="onOkStart"
                  ref="datePicker"
                />

                <span style="margin: 0 10px">至</span>
                <!-- 第二个日期选择器，用于结束时间 -->
                <a-date-picker
                  style="width: 41%; height: 40px; border-radius: 8px"
                  :show-time="{ format: 'HH:mm' }"
                  :format="['YYYY-MM-DD HH:mm', 'YYYY/MM/DD HH:mm']"
                  valueFormat="YYYY-MM-DD HH:mm"
                  v-model:value="dateTime[1]"
                  @change="timeChangeEnd"
                  :placeholder="'        结束时间'"
                  :disabled="editBeginClass"
                  @focus="onFocusEnd"
                  @blur="onBlurEnd"
                  @select="onDateEnd"
                  :open="openEnd"
                  @ok="onOkEnd"
                  :disabled-date="disabledDate"
                  :disabled-time="disabledDateTime"
                />
              </div>
            </div>

            <div class="cstm_items" style="align-items: flex-start">
              <div class="signbox" style="position: relative; top: 11px">
                <div class="sign">
                  <img
                    src="@/assets/images/coursewareManage/asterisk.png"
                    alt=""
                  />
                </div>
                <span style="margin-right: 3px">授课教师</span>
              </div>
              <div
                class="teacher_input select"
                style="display: flex; flex-wrap: wrap; width: 74.5%"
              >
                <div
                  v-for="(item, index) in formData.offteachers"
                  :key="index"
                  style="display: flex; margin-bottom: 10px; width: 100%"
                >
                  <ProjectManager
                    v-model:value="item.teacherId"
                    v-model:name="item.teacherName"
                    :disabled="editBeginClass"
                  ></ProjectManager>
                  <a-input-number
                    :min="0"
                    @change="inputWeightChange(index)"
                    v-model:value="item.weight"
                    placeholder="%"
                  />
                  <span style="margin-top: 10px; width: 34px">权重</span>
                  <div style="display: flex">
                    <!-- <a-button v-if="index===0" shape="circle" class="btn-circle btn-add" @click="inputAdd">+</a-button> -->
                    <a-button
                      shape="circle"
                      class="btn-circle"
                      @click="inputRemove(index)"
                      :disabled="formData.offteachers.length == 1"
                      ><template #icon
                        ><delete-outlined class="custom-icon" /></template
                    ></a-button>
                  </div>
                </div>
                <a-button
                  shape="circle"
                  class="btn-circle btn-add"
                  @click="inputAdd"
                  >+</a-button
                >
              </div>
            </div>
            <div class="cstm_items">
              <div class="signbox">
                <!--                    <div class="sign">-->
                <!--                        <img src="@/assets/images/coursewareManage/asterisk.png" alt=""/>-->
                <!--                    </div>-->
                <span style="margin-right: 3px">持续时间</span>
              </div>
              <div class="b_input">
                <a-input-number
                  :min="0"
                  :max="999999"
                  :precision="0"
                  :placeholder="durationText"
                  style="
                    width: 88%;
                    height: 32px;
                    border-radius: 8px;
                    overflow: hidden;
                  "
                  v-model:value="formData.duration"
                ></a-input-number>
                <div class="inp_num" style="right: 96px; line-height: 12px">
                  <span style="color: #c7cbd2">分钟</span>
                </div>
              </div>
            </div>
            <div class="cstm_items">
              <div class="signbox">
                <div class="sign"></div>
                <span style="margin-right: 3px">地点</span>
              </div>
              <div class="b_input">
                <a-input
                  v-model:value="formData.address"
                  maxlength="50"
                  style="width: 88%; height: 40px; border-radius: 8px"
                  placeholder="请输入详细地点"
                />
                <div class="inp_num" style="right: 90px">
                  <span style="color: #c7cbd2"
                    >{{ formData.address.length || 0 }}/50</span
                  >
                </div>
              </div>
            </div>
            <div class="cstm_items">
              <div class="signbox">
                <span style="margin-right: 3px">考勤设置</span>
              </div>
              <div style="display: flex; align-items: center; width: 88%">
                <div style="margin-right: 24px">签到</div>
                <div
                  style="display: flex; align-items: center; margin-right: 20px"
                >
                  <span>开始前：</span>
                  <a-input-number
                    :min="0"
                    :max="999999"
                    :precision="0"
                    style="
                      width: 100px;
                      height: 32px;
                      border-radius: 8px;
                      overflow: hidden;
                    "
                    v-model:value="formData.beforeStart"
                  ></a-input-number>
                  <span style="color: #999999; margin-left: 8px">分钟</span>
                </div>
                <div style="display: flex; align-items: center">
                  <span>开始后：</span>
                  <a-input-number
                    :min="0"
                    :max="999999"
                    :precision="0"
                    style="
                      width: 100px;
                      height: 32px;
                      border-radius: 8px;
                      overflow: hidden;
                    "
                    v-model:value="formData.afterStart"
                  ></a-input-number>
                  <span style="color: #999999; margin-left: 8px">分钟</span>
                </div>
              </div>
            </div>
            <!-- <div class="cstm_items">
            <div class="signbox">
              <span style="margin-right: 3px">报名设置</span>
            </div>
            <div class="b_input" style="width: 88%;">
              <CheckBox v-model="formData.applyFlag"
                        :check-value="1"
                        :un-check-value="0">
                <span style="color: #6d7584">是否允许公开报名</span>
              </CheckBox>
            </div>
          </div> -->

            <div class="cstm_items" style="align-items: flex-start">
              <div class="signbox">
                <span style="margin-right: 3px">现场参与</span>
              </div>
              <div
                class="b_input"
                style="width: 88%; display: flex; flex-direction: column"
              >
                <CheckBox
                  v-model="formData.projectSignFlag"
                  :check-value="1"
                  :un-check-value="0"
                  @change="toggleCheckboxes('projectSignFlag')"
                >
                  <span style="color: #6d7584"
                    >允许项目内人员临时到场参加(不在本场次培训的人员可以临时签到评估)</span
                  >
                </CheckBox>
                <CheckBox
                  v-model="formData.outSignFlag"
                  :check-value="1"
                  style="margin-left: 0px"
                  :un-check-value="0"
                  @change="toggleCheckboxes('outSignFlag')"
                >
                  <span style="color: #6d7584">允许项目外人员临时到场参加</span>
                </CheckBox>
              </div>
            </div>

            <div class="cstm_items">
              <div class="signbox">
                <span style="margin-right: 3px">评估设置</span>
              </div>
              <div class="b_input" style="width: 88%">
                <CheckBox
                  v-model="formData.evalFlag"
                  :disabled="editBeginClass"
                  :checkValue="1"
                  :un-checkValue="0"
                >
                  <span style="color: #6d7584">是否需要评估</span>
                </CheckBox>
              </div>
            </div>
            <div v-if="formData.evalFlag" class="cstm_items main_item">
              <div class="signbox"></div>
              <div class="btnbox" style="display: flex">
                <button
                  @click="step = 3"
                  class="xkbtn"
                  style="margin-bottom: 0; margin-top: 0"
                >
                  选择评估
                </button>

                <div v-if="formData.assessmentId > 0">
                  <a-tag
                    :closable="!editBeginClass"
                    @close="removePG"
                    color="processing"
                  >
                    <span style="font-size: 14px; line-height: 33px">
                      {{ formData.assessmentName }}
                    </span>
                  </a-tag>
                </div>
              </div>
            </div>

            <div class="cstm_items main_item">
              <div class="signbox"></div>
              <div class="btnbox" style="display: flex">
                <button
                  @click="step = 4"
                  class="xkbtn"
                  style="margin-bottom: 0; margin-top: 0"
                >
                  配置作业
                </button>
                <div v-if="formData?.workInfo?.workName">
                  <a-tag closable @close="logW" color="processing">
                    <span style="font-size: 14px; line-height: 33px">
                      {{ formData?.workInfo?.workName }}
                    </span>
                  </a-tag>
                </div>
              </div>
            </div>
            <div class="cstm_items main_item" style="margin-bottom: 0">
              <div class="signbox"></div>
              <div class="btnbox" style="display: flex">
                <button
                  @click="step = 5"
                  class="xkbtn"
                  style="margin-bottom: 0; margin-top: 0"
                >
                  配置考试
                </button>
                <div v-if="formData?.examInfo?.examinationName">
                  <a-tag closable @close="logT" color="processing">
                    <span style="font-size: 14px; line-height: 33px">
                      {{ formData.examInfo?.examinationName }}
                    </span>
                  </a-tag>
                </div>
              </div>
            </div>
            <div class="cstm_items items_fj">
              <div class="signbox">
                <span style="margin-right: 3px"></span>
              </div>
              <div class="b_input">
                <FJUpload
                  v-model:value="formData.attach"
                  @changevalue="changevalue"
                />
              </div>
            </div>

            <div class="items_btn">
              <div class="cstm_btn btn6" @click="handleCancelStu">
                <div class="btnText">取消</div>
              </div>
              <a-button
                class="cstm_btn btn6"
                @click="coursePlanConfirm"
                :loading="validated === 1"
              >
                确定
              </a-button>
            </div>
          </div>
        </div>
      </template>
      <template v-if="step == 3">
        <GrowthAssessment
          :selectId="formData.assessmentId"
          @confirm="growthAssessmentConfirm"
          :disabled="editBeginClass"
        >
        </GrowthAssessment>
      </template>
      <template v-if="step == 4">
        <CommonHomework v-model:info="formData.workInfo" @close="step = 2">
        </CommonHomework>
      </template>
      <template v-if="step == 5">
        <CommonTest
          ref="CommonTestRef"
          v-model:info="formData.examInfo"
          @close="step = 2"
          @nextStep="commonTestNextStep"
        >
        </CommonTest>
      </template>
    </div>
    <!--新建开课页面 -->
    <a-modal
      v-model:visible="offCourseNewVisiable"
      style="margin-top: 400px"
      @cancel="handleCancelStu"
    >
    </a-modal>
  </a-drawer>
</template>
<script setup lang="jsx">
import {
  defineProps,
  ref,
  nextTick,
  computed,
  defineEmits,
  onMounted,
  watch,
} from "vue";
import { Form, message } from "ant-design-vue";
import FJUpload from "@/components/common/FJUpload";
import CheckBox from "@/components/common/CheckBox";
import RangePicker from "@/components/common/RangePicker";
import ProjectManager from "@/components/project/ProjectManagerNewTeacher";
import CommonHomework from "@/components/growthpath/CommonHomework.vue";
import CommonTest from "@/components/growthpath/CommonTest.vue";
import NameInput from "@/components/project/NameInputNew";
import GrowthAssessment from "@/components/growthpath/GrowthAssessment.vue";
import {
  COURSE_PLAN_EDIT,
  COURSE_PLAN_PAGE,
  DEL_PLAN,
  EXAM_DETAIL,
  WORK_DETAIL,
  PROJECT_DETAIL_MODIFY,
  PROJECT_RELEASE,
  ROUTER_DETAIL_MODIFY,
} from "@/api/apis";
import dayjs from "dayjs";
import { GetRouterDraftDetail, releaseRouter } from "@/api/indexTask";
import BaseTable from "@/components/common/BaseTable";
import { request, useRowsPageNoInit } from "@/api/request";
import dialog from "@/utils/dialog";
import { useResetRef } from "@/utils/useCommon";
import { validateName } from "@/api/index1";
import moment from "moment";
import * as api from "../../api/indexTaskadd";
import { useRoute } from "vue-router";
import { DeleteOutlined } from "@ant-design/icons-vue";
// 步骤数
const step = ref(1);

// 弹框名称
const title = computed(() => {
  if (step.value == 1) {
    return "开课";
  } else if (step.value == 2) {
    return formData.value.id ? "编辑开课" : "新建开课";
  } else if (step.value == 3) {
    return "选择评估";
  } else if (step.value == 4) {
    return "配置作业";
  } else if (step.value == 5) {
    return "配置考试";
  }
});
// 选择评估确认
const growthAssessmentConfirm = (select) => {
  formData.value.assessmentName = select.assessmentName;
  formData.value.assessmentId = select.id;
  // 返回编辑开课
  step.value = 2;
};

const commonTestStep = ref(1);
// 选择试卷内步骤操作
const commonTestNextStep = (val) => {
  commonTestStep.value = val;
};
const changeName = ref(false);
const props = defineProps({
  type: Number,
});
const openCourseVisible = ref(false);
const offCourseNewVisiable = ref(false);
const tableRef = ref();
const toggleCheckboxes = (checkedName) => {
  if (checkedName === "projectSignFlag") {
    if (formData.value.projectSignFlag) {
      formData.value.outSignFlag = !formData.value.projectSignFlag;
    }
  } else if (checkedName === "outSignFlag") {
    if (formData.value.outSignFlag) {
      formData.value.projectSignFlag = !formData.value.outSignFlag;
    }
  }
};
const columns = ref([
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    width: "20%",
    ellipsis: true,
  },
  {
    title: "场地",
    dataIndex: "address",
    key: "address",
    width: "20%",
    align: "center",
  },
  {
    title: "开始时间",
    dataIndex: "beginTime",
    key: "beginTime",
    width: "20%",
    align: "center",
  },
  {
    title: "教师",
    dataIndex: "teacher",
    key: "teacher",
    width: "20%",
    align: "center",
    customRender: ({ record }) => {
      // const teachers = record.offteachers;
      // return teachers.map((teacher, index) => {
      //   // 如果需要显示为列表形式
      //   return (
      //     <div key={index}>
      //       {teacher.teacherName}
      //       {index !== teachers.length - 1 && ', '}
      //     </div>
      //   );
      // });
      return record.offteachers.map((item) => item.teacherName).join(",");
    },
  },
  {
    title: "学员数",
    dataIndex: "studentCnt",
    key: "studentCnt",
    width: "20%",
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    width: "20%",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "createTime",
    key: "createTime",
    width: "20%",
    align: "center",
    customRender: ({ record }) => {
      return (
        <div class="opa">
          <a style="margin-right:10px;" onClick={() => planEdit(record)}>
            编辑
          </a>
          <a onClick={() => del(record.id, record)}>删除</a>
        </div>
      );
    },
  },
]);
const params = ref({
  type: props.type,
  offcourseId: "",
  draftTaskId: "",
  taskId: "",
  createBeginTime: "",
  createEndTime: "",
  offteachers: [
    {
      teacherId: "",
      teacherName: "",
      weight: "",
    },
  ],
});
const validated = ref(0);
const dateTime = ref([]);
const courseName = ref();
const onceName = ref("");
const formData = useResetRef({
  name: "",
  address: "",
  teacherId: "",
  // teacher: "",
  beforeValue: "",
  afterStartValue: "",
  applyFlag: 0,
  projectSignFlag: 0,
  signFlag: 0,
  evalFlag: 0,
  assessmentName: "",
  assessmentId: "",
  duration: "",
  workInfo: {},
  examInfo: {},
  attach: "",
  type: props.type,
  offcourseId: "",
  draftTaskId: "",
  taskId: "",
  offteachers: [
    {
      teacherId: "",
      teacherName: "",
      weight: "",
    },
  ],
});
const formDataRule = {
  name: [
    {
      required: true,
      message: "请输入开课名称",
    },
  ],
  // beginTime: [
  //   {
  //     required: true,
  //     message: "请选择开始时间",
  //   },
  // ],
  // endTime: [
  //   {
  //     required: true,
  //     message: "请选择结束时间",
  //   },
  // ],
  offteachers: [
    {
      validator: (rule, value, callback) => {
        if (!value.every((item) => item.teacherName)) {
          callback(new Error("请填写教师名称和设置权重"));
        } else {
          callback();
        }
      },
      message: "请填写教师名称和设置权重",
      fields: {
        teacherName: [
          {
            required: true,
            message: "请填写教师名称和设置权重",
          },
        ],
      },
    },
  ],
};
const { validate } = Form.useForm(formData, formDataRule);
const durationText = computed(() =>
  dateTime.value?.length
    ? dayjs(dateTime.value[1]).diff(dayjs(dateTime.value[0]), "minute")
    : "请输入持续时间"
);
const nums = ref(0);
watch(durationText, (val) => {
  nums.value++;
  if (nums.value > 1) {
    formData.value.duration = val;
  }
});
function inputAdd() {
  formData.value.offteachers.push({
    teacherId: "",
    teacherName: "",
    weight: "",
  });
}
function inputRemove(index) {
  dialog({
    content: "确定删除此授课教师吗？",
    ok: async () => {
      formData.value.offteachers.splice(index, 1);
      message.success("删除成功");
    },
  });
}
const totalWeightSum = ref(0);
function inputWeightChange(index) {
  let totalWeight = 0;
  formData.value.offteachers.forEach((item) => {
    totalWeight += Number(item.weight);
  });
  if (totalWeight > 100) {
    message.info("权重值最大为100%");
    formData.value.offteachers[index].weight -= totalWeight - 100;
    totalWeight = 100;
  }
  totalWeightSum.value = totalWeight;
}
function timeChange(timeStr) {
  console.log(timeStr, "timeStr");
  formData.value.beginTime = timeStr;
  // formData.value.duration = durationText.value
  // formData.value.duration || (formData.value.duration = dayjs(timeStr[1]).diff(dayjs(timeStr[0]),'minute'))
}
function onDateSelect(date) {
  const month = String(date.$M + 1).padStart(2, "0");
  const day = String(date.$D).padStart(2, "0");
  const hour = String(date.$H).padStart(2, "0");
  const minute = String(date.$m).padStart(2, "0");
  dateTime.value[0] =
    date.$y + "-" + month + "-" + day + " " + hour + ":" + minute;
}
const openStart = ref(false);
const onOkStart = () => {
  openStart.value = false;
};
function onBlurStart(e) {
  dateTime.value[0] = e.target.value;
  openStart.value = false;
}
function onFocusStart() {
  openStart.value = true;
  if (!dateTime.value[0]) {
    // dateTime.value[0] = moment().format('YYYY-MM-DD HH:mm')
    //   let now=new Date()
    //   let start=new Date(now.setFullYear(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0))
    //   dateTime.value = [
    //     moment(start).format('YYYY-MM-DD HH:mm'),
    //     dateTime.value[1]
    //   ];
  }
}
function timeChangeEnd(timeStr) {
  formData.value.endTime = timeStr;
}
const openEnd = ref(false);
const onOkEnd = () => {
  openEnd.value = false;
};
function onBlurEnd(e) {
  dateTime.value[1] = e.target.value;
  openEnd.value = false;
}
function onDateEnd(date) {
  const month = String(date.$M + 1).padStart(2, "0");
  const day = String(date.$D).padStart(2, "0");
  const hour = String(date.$H).padStart(2, "0");
  const minute = String(date.$m).padStart(2, "0");
  dateTime.value[1] =
    date.$y + "-" + month + "-" + day + " " + hour + ":" + minute;
  if (dateTime.value[0] == dateTime.value[1]) {
    const minute = String(date.$m + 1).padStart(2, "0");
    dateTime.value[1] =
      date.$y + "-" + month + "-" + day + " " + hour + ":" + minute;
  }
}
function onFocusEnd() {
  openEnd.value = true;
  // if(!dateTime.value[1]){
  //   let now=new Date()
  //      let start=new Date()
  //      let end=new Date(now.setFullYear(now.getFullYear()))
  //      dateTime.value = [
  //      dateTime.value[0],
  //       moment(end).format('YYYY-MM-DD HH:mm')
  //   ];
  // }
}
function search() {
  tableRef.value.fetch();
}

const resetTime = ref();
function reset() {
  tableRef.value.reset({
    type: props.type,
    offcourseId: params.value.offcourseId,
    draftTaskId: params.value.draftTaskId,
  });
  resetTime.value.resetTime();
}
const CommonTestRef = ref(null);
// 关闭步骤
const closeDrawer = () => {
  // 如果不是第一步则退到新增
  if (step.value > 2 && commonTestStep.value == 1) {
    step.value = 2;
  } else if (step.value > 2 && commonTestStep.value == 6) {
    // 配置考试
    // commonTestStep = 6，说明在配置考试组件内，展示页面为选择试卷
    // 主弹框不退步，配置考试组件内退一步
    CommonTestRef.value.setStep(1);
    commonTestStep.value = 1;
  } else if (step.value == 2 && commonTestStep.value == 7) {
    // commonTestStep = 7，说明在配置考试组件内，展示页面为新增试卷
     // 主弹框不退步，配置考试组件内退一步
    CommonTestRef.value.setStep(2);
    commonTestStep.value = 6;
  } else if (step.value == 2) {
    step.value = 1;
  } else {
    openCourseVisible.value = false;
    tableRef.value.reset({
      type: props.type,
      offcourseId: params.value.offcourseId,
      draftTaskId: params.value.draftTaskId,
    });
  }
};
const route = useRoute();
const projectInfo = ref({});
const emit = defineEmits(["call-parent-method"]);
const confirm = async () => {
  closeDrawer();
  if (route.query.projectId) {
    await api.getDraftTask({ projectId: route.query.projectId }).then((res) => {
      projectInfo.value = res.data.data;
    });
    request(PROJECT_DETAIL_MODIFY, { ...projectInfo.value });
    if (projectInfo.value.projectInfo.status == 3) {
      request(PROJECT_RELEASE, { projectId: route.query.projectId });
    }
    emit("call-parent-method");
  }
  if (route.query.routerId) {
    await GetRouterDraftDetail(route.query.routerId).then((res) => {
      projectInfo.value = res.data.data;
    });
    request(ROUTER_DETAIL_MODIFY, { ...projectInfo.value });
    if (projectInfo.value.routerInfo.status == 1) {
      await releaseRouter(route.query.routerId);
    }
    emit("call-parent-method");
  }
};

const createNewCourse = () => {
  changeName.value = true;
  editBeginClass.value = false;
  formData.reset({
    type: props.type,
    offcourseId: params.value.offcourseId,
    draftTaskId: params.value.draftTaskId,
    name: courseName.value,
  });
  dateTime.value = [moment().format("YYYY-MM-DD HH:mm"), ""];
  validated.value = 0;
  onceName.value = "";
  formData.value.offteachers = [
    {
      teacherId: "",
      teacherName: "",
      weight: "",
    },
  ];
  // 第二步新增课程
  step.value = 2;
};
const handleCancelStu = () => {
  changeName.value = false;
  offCourseNewVisiable.value = false;
};

const expenseStatus = {
  A10: true,
  S00: true,
};
const del = (id, record) => {
  console.log(record, "删除");
  if (record.expenseStatus && !expenseStatus[record.expenseStatus]) {
    return message.warning("该开课已在审批流程中，不可进行删除!");
  }
  dialog({
    content: "确定删除此开课吗？",
    ok: async () => {
      message.success("删除成功");
      tableRef.value.toLoading();
      await request(DEL_PLAN(id));
      tableRef.value.fetch();
    },
  });
};

async function coursePlanConfirm() {
  if (!dateTime.value[0]) {
    message.info("开始时间未填写");
    return;
  }
  if (!dateTime.value[1]) {
    message.info("结束时间未填写");
    return;
  }
  await validate().catch(({ errorFields }) => {
    message.warning(errorFields[0].errors.join());
    throw Error("数据校验不通过");
  });
  inputWeightChange();
  if (formData.value.offteachers.length == 1 && totalWeightSum.value != 100) {
    message.error("单名教师您设置的权重应该是100%");
    return;
  } else if (
    formData.value.offteachers.length > 1 &&
    totalWeightSum.value != 100
  ) {
    console.log(totalWeightSum.value, "权重值不为100%");
    message.error("多名教师权重合计值为100%");
    return;
  }
  const teacherNames = new Set(
    formData.value.offteachers.map((item) => item.teacherName)
  );
  if (teacherNames.size !== formData.value.offteachers.length) {
    message.error("教师重复，请检查");
    return;
  }
  if (formData.value.offteachers.some((item) => item.weight == 0)) {
    message.error("权重值不能为0%");
    return;
  }
  if (editBeginClass.value) {
    message.info("讲师费已进入审批阶段，无法编辑");
    return;
  }
  if (dateTime.value.length < 2) {
    message.info("请选择开始时间和结束时间");
    return;
  }
  if (durationText.value < 0) {
    message.info("结束时间不能小于开始时间，请重新填写");
    return;
  }
  await validate().catch(({ errorFields }) => {
    message.warning(errorFields[0].errors.join());
    throw Error("数据校验不通过");
  });
  const offName = await validateName({
    name: formData.value.name,
    type: 5,
    id: formData.value.id,
  }).then((res) => {
    console.log(res, res.data.data);
    return res.data.data === 1;
  });
  if (offName) {
    message.destroy();
    message.warning("开课名称重复，请重新填写");
    return;
  }
  offCourseNewVisiable.value = false;
  tableRef.value.toLoading();
  // TODO 当点击选择了是否评估按钮 点击保存的时候没有选择评估 则是否需要评估重置为 0 不需要
  formData.value.evalFlag = formData.value.assessmentName ? 1 : 0;
  formData.value.duration = formData.value.duration
    ? formData.value.duration
    : durationText.value;
  formData.value.outSignFlag = formData.value.outSignFlag ? 1 : 0;
  formData.value.projectSignFlag = formData.value.projectSignFlag ? 1 : 0;
  formData.value.beginTime = dateTime.value[0];
  formData.value.endTime = dateTime.value[1];
  await request(COURSE_PLAN_EDIT, { ...formData.value });
  if (route.query.projectId) {
    await api.getDraftTask({ projectId: route.query.projectId }).then((res) => {
      projectInfo.value = res.data.data;
    });
    request(PROJECT_DETAIL_MODIFY, { ...projectInfo.value });
    if (projectInfo.value.projectInfo.status == 3) {
      request(PROJECT_RELEASE, { projectId: route.query.projectId });
    }
    emit("call-parent-method");
  }
  if (route.query.routerId) {
    await GetRouterDraftDetail(route.query.routerId).then((res) => {
      projectInfo.value = res.data.data;
    });
    console.log(projectInfo.value, "ite2545m");
    request(ROUTER_DETAIL_MODIFY, { ...projectInfo.value });
    if (projectInfo.value.routerInfo.status == 1) {
      await releaseRouter(route.query.routerId);
    }
    emit("call-parent-method");
  }
  handleCancelStu();
  tableRef.value.fetch();
}

const editBeginClass = ref(false);
function planEdit(record) {
  nums.value = 0;
  editBeginClass.value = false;
  if (record.expenseStatus && !expenseStatus[record.expenseStatus]) {
    editBeginClass.value = true;
    console.log(editBeginClass.value);
  }
  onceName.value = record.name;
  formData.value = { ...record };
  // formData.value.duration = ''
  console.log({ ...record }, "{ ...record }");
  validated.value = 0;
  formData.value.homeWorkId &&
    request(WORK_DETAIL(formData.value.homeWorkId), {}).then(
      (res) => (formData.value.workInfo = res.data)
    );
  formData.value.testId &&
    request(EXAM_DETAIL(formData.value.testId), {}).then(
      (res) => (formData.value.examInfo = res.data)
    );
  dateTime.value = [formData.value.beginTime, formData.value.endTime];
  offCourseNewVisiable.value = true;
}
function openDrawer(row) {
  openCourseVisible.value = true;
  params.value.offcourseId = row.taskId;
  params.value.draftTaskId = row.id;
  formData.value.offcourseId = row.taskId;
  formData.value.draftTaskId = row.id;
  courseName.value = row.taskName;
  setTimeout(() => {
    nextTick(tableRef?.value.fetch);
  });
}
const range = (start, end) => {
  const result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
};
// const disabledDate = (current) => current && current < dayjs(dateTime.value[0]);
const disabledDateTime = () => {
  // const dateOnlyStart = new Date(dateTime.value[0].split(' ')[0]);
  // const dateOnlyEnd = new Date(dateTime.value[1].split(' ')[0]);
  // if(dateOnlyStart.getTime()==dateOnlyEnd.getTime()){
  //   const currentMinute = dayjs(dateTime.value[0]).minute();
  //   return {
  //     disabledHours: () => range(0, dayjs(dateTime.value[0]).hour()).splice(0, dayjs(dateTime.value[0]).hour()),
  //     disabledMinutes: () => range(0, currentMinute+1).splice(0, currentMinute+1),
  //   };
  // }
};
// 删除文件返回参数
const changevalue = (e) => {
  let arr = formData.value.attach.split(",");
  let newarr = [];
  for (let i = 0; i < arr.length; i++) {
    if (i !== e) {
      newarr.push(arr[i]);
    }
  }
  if (newarr.length == 0) {
    formData.value.attach = "";
  } else {
    formData.value.attach = newarr.toString();
  }
  console.log("changevalue", e, newarr, formData.value.attach);
};

const logT = () => {
  formData.value.examInfo = {};
};
const removePG = () => {
  formData.value.assessmentId = null;
  formData.value.assessmentName = "";
  // state.isEvaluate = "0";
};

defineExpose({ openDrawer });
</script>
<style lang="scss">
.growth-open-course > .ant-drawer-content-wrapper {
  width: 1300px !important;
  min-width: 1300px !important;
}

.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa !important;
}

.fitems {
  width: 88%;
}
.contentMain {
  .main_items {
    margin: 20px 0 !important;
    .mi_ipts,
    .mi_btns {
      margin-bottom: 0 !important;
    }
  }
  .main_item {
    .xkbtn {
      margin: 0 0 20px 0;
    }
  }
}

.createschooltime {
  .cst_main {
    width: 100%;
    overflow-y: auto;
    position: relative;

    .cstm_title {
      margin: 10px auto 20px 0;
      font-weight: bold;
    }

    .cstm_items {
      display: flex;
      margin: auto;
      align-items: center;
      margin-bottom: 23px;
      .teacher_input {
        .ant-input-number {
          width: 15%;
          height: 40px !important;
          border-radius: 8px !important;
          border: 1px solid #c7cbd2 !important;
          margin: 0 10px 0 10px;
          padding-top: 3px;
        }
      }
      .btn-add {
        margin: 0 10px 0 10px;
      }
      .btn-circle {
        text-align: center;
        line-height: 100%;
        margin-top: 5px;
        .custom-icon {
          font-size: 20px;
          svg {
            margin: auto;
          }
        }
        span {
          width: 100%;
          height: 100%;
          font-size: 33px;
        }
      }
      .signbox {
        display: flex;
        justify-content: end;
        width: 100px;
        margin-right: 6px;

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

      .b_input {
        flex: 1;
        position: relative;

        .upload_box {
          display: flex;
          cursor: pointer;

          .upload_icon {
            width: 16px;
            height: 16px;
            margin-right: 5px;
          }
        }

        .inp_num {
          position: absolute;
          top: 9px;
          right: 10px;
        }
      }
    }

    .items_fj {
      margin-bottom: 1px;

      .fujian {
        display: none;
      }

      .mbl_items12 {
        width: 440px;
        margin-right: 56px;

        .i12_box1 {
          display: flex;
          align-items: center;
          padding: 17px 0 17px 21px;
          border: 1px solid #eff4fc;
          border-radius: 8px;
          margin-bottom: 10px;

          .file_img {
            width: 27px;
            height: 32px;
            background-image: url(@/assets/images/coursewareManage/imgs.png);
            margin-right: 22px;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .file_detail {
            width: 250px;
            margin-right: 21px;

            .file_updata {
              display: flex;
              align-items: center;

              .updatabox {
                position: relative;
                width: 230px;
                height: 5px;
                background-color: rgba(192, 192, 192, 0.25);
                border-radius: 3px;

                .updatacolor {
                  position: absolute;
                  left: 0;
                  width: 100%;
                  height: 5px;
                  background-color: #57c887;
                  border-radius: 3px;
                }

                .updatacolor2 {
                  position: absolute;
                  left: 0;
                  width: 80%;
                  height: 5px;
                  background-color: #ff7474;
                  border-radius: 3px;
                }

                .updatacolor3 {
                  position: absolute;
                  left: 0;
                  width: 60%;
                  height: 5px;
                  background-color: #4ea6ff;
                  border-radius: 3px;
                }

                .updataxq {
                  position: absolute;
                  right: 2px;
                  top: -30px;
                  color: #57c887;
                }

                .updataxq2 {
                  position: absolute;
                  right: 2px;
                  top: -30px;
                  color: #ff7474;
                }

                .updataxq3 {
                  position: absolute;
                  right: 2px;
                  top: -30px;
                  color: #4ea6ff;
                }
              }
            }
          }

          .file_operation {
            display: flex;

            .fobox {
              margin-right: 5px;
              cursor: pointer;
            }
          }
        }
      }
    }

    .items_btn {
      display: flex;
      justify-content: center;
      margin-top: 20px;
      margin-bottom: 20px;

      .cstm_btn {
        width: 100px;
        height: 40px;
        background: rgba(64, 158, 255, 0);
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 14px;
        flex-shrink: 0;
        cursor: pointer;

        .btnText {
          font-size: 14px;
          font-weight: 400;
          line-height: 40px;
        }
      }

      .btn5 {
        border: 1px solid rgba(64, 158, 255, 1);
        color: #4ea6ff;
      }

      .btn6 {
        background-color: #4ea6ff;
        color: #ffffff;
      }
    }
  }
}
</style>
