<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <div class="org_header" style="padding: 15px 32px">
          <span class="subject">{{ title }}</span>
          <div class="header_btn_box"></div>
        </div>
        <div style="padding: 20px 0 20px">
          <el-button
            type="primary"
            v-show="isDisable && !isEdit"
            @click="disabledChange()"
            size="mini"
            >创建副本</el-button
          >
          <el-button
            type="primary"
            v-show="isEdit && isDisable"
            @click="disabledChange()"
            size="mini"
            >再次编辑</el-button
          >
        </div>
        <div style="margin: 24px; width: 420px">
          <el-form :model="taskForm" ref="taskForms" label-width="100px">
            <el-form-item
              prop="name"
              label="任务名称"
              style="font-weight: bold; padding-top: -30px"
              :rules="[
                { required: true, message: '请输入任务名称', trigger: 'blur' },
              ]"
            >
              <el-input
                :disabled="isDisable"
                v-model="taskForm.name"
                style="width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="课程表列表" style="font-weight: bold" prop="">
              <div class="courseTip" v-if="taskForm.scheduleList.length != 0">
                拖拽可调整顺序
              </div>
              <draggable
                v-model="taskForm.scheduleList"
                @update="dataDragEnd"
                :options="{ animation: 500 }"
              >
                <transition-group>
                  <template
                    v-if="
                      taskForm.scheduleList.length != 0 &&
                      taskForm.scheduleList != null
                    "
                  >
                    <div
                      v-for="(i, d) in taskForm.scheduleList"
                      :key="d"
                      style="cursor: move; margin-bottom: 6px"
                    >
                      <div>
                        <el-popover
                          :ref="coursesPopover + i.id"
                          placement="right"
                          width="400"
                          trigger="manual"
                          v-model="i.isDetail"
                          :offset="200"
                          :title="i.name"
                        >
                          <div class="userlist">
                            <span>已选择</span
                            ><span
                              v-show="!isDisable"
                              style="margin-right: 70px"
                              >拖拽可调整顺序</span
                            >
                          </div>
                          <div
                            class="overflowBox"
                            style="margin: 10px 0; height: 200px"
                          >
                            <draggable
                              v-model="i.courseIDList"
                              @update="coursesDetailDragEnd"
                              :options="{ animation: 500 }"
                            >
                              <transition-group>
                                <template
                                  v-if="
                                    taskForm.scheduleList.length != 0 &&
                                    taskForm.scheduleList != null
                                  "
                                >
                                  <div
                                    v-for="item in i.courseIDList"
                                    :key="item.id"
                                    style="cursor: move"
                                  >
                                    <div
                                      class="course-item"
                                      style="padding: 8px 10px"
                                    >
                                      {{ item.name }}

                                      {{ !item.published ? "（未发布）" : "" }}
                                    </div>
                                    <i
                                      v-show="!isDisable"
                                      class="el-icon-remove"
                                      style="cursor: pointer"
                                      @click="delDetail(i, item)"
                                    ></i>
                                  </div>
                                </template>
                              </transition-group>
                            </draggable>
                          </div>
                          <div
                            v-show="!isDisable"
                            style="
                              padding-top: 10px;
                              border-top: 1px solid #eee;
                            "
                          >
                            <span>未选择</span>
                            <div
                              class="overflowBox"
                              style="padding-top: 10px; height: 200px"
                            >
                              <div
                                v-for="(item, k) in coursesDetailList"
                                :key="k"
                                style="cursor: move"
                              >
                                <div
                                  class="course-item"
                                  style="padding: 8px 10px"
                                >
                                  {{ item.name }}
                                </div>
                                <i
                                  class="el-icon-circle-plus"
                                  style="cursor: pointer"
                                  @click="pushDetail(i, item)"
                                ></i>
                              </div>
                            </div>
                          </div>
                          <div style="text-align: right; margin: 10px 40px">
                            <el-button
                              size="mini"
                              @click.native="cancelCoursesDetail(i)"
                              >取消</el-button
                            >
                            <el-button
                              v-show="!isDisable"
                              type="primary"
                              size="mini"
                              @click.native="confirmCoursesDetail(i)"
                              >确定</el-button
                            >
                          </div>
                          <div
                            class="course-item"
                            @click="selectCoursesContent(i)"
                            slot="reference"
                          >
                            {{ i.name }}
                            <i class="el-icon-arrow-right"></i>
                          </div>
                        </el-popover>
                        <i
                          v-show="!isDisable"
                          class="el-icon-error"
                          style="cursor: pointer"
                          @click="clearCourse(i)"
                        ></i>
                      </div>
                    </div>
                  </template>
                </transition-group>
              </draggable>
              <span
                v-show="!isDisable"
                @click.prevent="addCourses()"
                style="color: #1e5aff; display: block; cursor: pointer"
                ><i class="el-icon-circle-plus-outline"></i> 添加课程表</span
              >
            </el-form-item>
            <el-form-item label="接收部门" style="font-weight: bold" prop="">
              <div v-for="(i, d) in taskForm.departmentList" :key="d">
                <el-popover
                  :ref="refNamePopover + i.id"
                  placement="right"
                  width="429"
                  trigger="manual"
                  v-model="i.isDept"
                  :offset="200"
                  :title="i.name"
                >
                  <div
                    class="overflowBox"
                    style="margin: 10px 0; height: 300px"
                    v-if="deptDetailList.length > 0"
                  >
                    <el-checkbox-group
                      v-model="checkedDeptEmployeesList"
                      id="checked"
                      @change="changeEmployees"
                    >
                      <el-checkbox
                        :disabled="isDisable"
                        class="checkedLine"
                        v-for="(it, k) in deptDetailList"
                        :key="k"
                        :label="it.id"
                      >
                        <p>{{ it.name }}</p>
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                  <p
                    v-else
                    style="
                      margin: 10px 0;
                      height: 300px;
                      text-align: center;
                      line-height: 300px;
                    "
                  >
                    暂无人员
                  </p>
                  <div style="text-align: right; margin: 0 40px">
                    <el-button size="mini" @click.stop="cancelDelete(i.id)"
                      >取消</el-button
                    >
                    <el-button
                      v-show="!isDisable"
                      type="primary"
                      size="mini"
                      @click.stop="confirmEmployees(i)"
                      >确定</el-button
                    >
                  </div>
                  <div
                    class="course-item"
                    @click="selectDeptContent(i)"
                    slot="reference"
                  >
                    {{ i.name }}
                    <i class="el-icon-arrow-right"></i>
                  </div>
                </el-popover>
                <i
                  v-show="!isDisable"
                  class="el-icon-error"
                  style="cursor: pointer"
                  @click="clearDept(i)"
                ></i>
              </div>
              <span
                v-show="!isDisable"
                @click.prevent="addDept()"
                style="color: #1e5aff; display: block; cursor: pointer"
                ><i class="el-icon-circle-plus-outline"></i> 添加部门</span
              >
            </el-form-item>
            <el-form-item
              prop="dueTime"
              label="截止时间"
              style="font-weight: bold"
              :rules="[
                {
                  message: '请选择截止时间',
                  trigger: 'change',
                },
              ]"
            >
              <el-date-picker
                v-model="taskForm.dueTime"
                :disabled="isDisable"
                type="datetime"
                style="width: 300px"
                placeholder="选择日期"
                default-time="23:59:59"
                @change="selectDate"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                id="noHover"
                :disabled="isDisable"
                @click="onSubmit"
                size="mini"
                >确定</el-button
              >
              <el-button size="mini" @click="pushTask()">返回</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 选择 -->
        <el-dialog
          :title="dialog.title"
          :visible.sync="dialog.dialog"
          :width="dialog.width"
          @close="closeDialog"
          :close-on-click-modal="false"
        >
          <div slot="title" class="dialog-title">
            <div class="dialog-icon mr20"></div>
            <span class="dialog-tip mr20">{{ dialog.title }}</span>
          </div>
          <div class="chooseBox">
            <div class="dialog_box">
              <el-row :gutter="10">
                <el-col :span="12">
                  <h3>选择:</h3>
                  <div class="side_left">
                    <div class="mb10" v-if="dialog.isCourses">
                      <el-input
                        prefix-icon="el-icon-search"
                        v-model="queryCourses.keyword"
                        placeholder="输入关键字搜索"
                        clearable
                        @keyup.enter.native="searchType()"
                        @clear="clearSearch()"
                      ></el-input>
                    </div>
                    <!-- <div class="mb10" v-if="dialog.isDept">
                      <el-input
                        prefix-icon="el-icon-search"
                        v-model="filterObj.filter"
                        placeholder="输入关键字搜索"
                        clearable
                        @keyup.enter.native="searchDept()"
                      ></el-input>
                    </div> -->
                    <div class="leftData mb10">
                      <div class="overflowBox" v-if="dialog.isCourses">
                        <ul
                          v-for="i in coursesList"
                          :key="i.id"
                          class="over-ul"
                        >
                          <li class="flexDiv">
                            <div>
                              <el-checkbox-group
                                class="flexDiv"
                                v-model="checkedCoursesList"
                              >
                                <el-checkbox
                                  :disabled="i.courseCount == 0"
                                  :key="i.id"
                                  :label="i.id"
                                  @change="(val) => handleCheckedChange(val, i)"
                                  >{{ i.name
                                  }}{{
                                    i.courseCount == 0 ? "（空）" : ""
                                  }}</el-checkbox
                                >
                              </el-checkbox-group>
                            </div>
                          </li>
                        </ul>
                      </div>
                      <div class="more" v-if="dialog.isCourses">
                        <p @click="loadMore()">
                          {{
                            courseTotal == coursesList.length
                              ? "没有更多了"
                              : "加载更多"
                          }}
                          <i
                            v-if="courseTotal > coursesList.length"
                            class="el-icon-bottom"
                          ></i>
                        </p>
                      </div>
                      <div v-if="dialog.isDept">
                        <el-checkbox
                          :indeterminate="isIndeterminate"
                          v-model="allChecked"
                          @change="handleCheckAllChange"
                          >全选</el-checkbox
                        >
                      </div>
                      <div class="overflowBox" v-if="dialog.isDept">
                        <el-tree
                          :data="deptList"
                          :default-checked-keys="checkedDeptIDList"
                          show-checkbox
                          default-expand-all
                          node-key="id"
                          ref="tree"
                          highlight-current
                          :props="defaultProps"
                          @check="clickDept"
                        >
                        </el-tree>
                      </div>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12" v-if="dialog.isCourses">
                  <h3>己选:</h3>
                  <div class="side_right">
                    <ul v-if="courseToData.length != 0">
                      <li v-for="(n, j) in courseToData" :key="j">
                        <div class="userlist">
                          <div>{{ n.name }}</div>
                          <div @click="removeItem(n)">
                            <i class="el-icon-error"></i>
                          </div>
                        </div>
                      </li>
                    </ul>
                  </div>
                </el-col>
                <el-col :span="12" v-if="dialog.isDept">
                  <h3>己选:</h3>
                  <div class="side_right">
                    <ul v-if="toData.length != 0">
                      <li v-for="(n, j) in toData" :key="j">
                        <div class="userlist">
                          <div>{{ n.name }}</div>
                          <div @click="removeItem(n)">
                            <i class="el-icon-error"></i>
                          </div>
                        </div>
                      </li>
                    </ul>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
          <div slot="footer" class="dialog-footer pt5" v-if="dialog.isCourses">
            <el-button type="primary" size="mini" @click="confirmCoursesForm()"
              >确 定</el-button
            >
            <el-button size="mini" @click="closeCoursesDialog()"
              >取 消</el-button
            >
          </div>
          <div slot="footer" class="dialog-footer pt5" v-if="dialog.isDept">
            <el-button type="primary" size="mini" @click="confirmDeptForm()"
              >确 定</el-button
            >
            <el-button size="mini" @click="closeDeptDialog()">取 消</el-button>
          </div>
        </el-dialog>
      </el-card>
    </template>
  </BasicLayout>
</template>
<script>
import * as fecha from "element-ui/lib/utils/date";
import draggable from "vuedraggable";
import { listLearningTable, getLearningTable } from "@/api/learningTable";
import {
  deptEmployees,
  createLearningTask,
  getLearningTask,
  learningTaskStatus,
} from "@/api/learning";
import { listDepartments } from "@/api/jobs";
import moment from "moment";
export default {
  name: "taskAdd",
  components: {
    draggable,
  },
  data() {
    return {
      courseTotal: "",
      courseToData: [],
      copy: false,
      pageIndex: 1,
      refNamePopover: "popover-", // popover ref名称前缀
      coursesPopover: "popover-", // popover ref名称前缀
      coursesIndex: {},
      deptIndex: {},
      breadList: [],
      treeKey: [],
      currentNode: "",
      isCurrentCheck: [],
      // 选择课程表
      coursesDetailList: [],
      deptDetailList: [],
      coursesDetail: {
        title: "",
        dialog: false,
        width: "400px",
        top: "600px",
      },
      // 选择课程表
      coursesList: [],
      // 选择部门
      deptList: [],
      toData: [],
      // 选择课程id列表
      checkedCoursesList: [],
      checkedDeptIDList: [],
      checkedDeptEmployeesList: [],
      CoursesListDetail: [],
      DeptEmployeesList: [],
      filterObj: {
        filter: "",
      },
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: false,
      },
      // 选择课程&& 部门
      dialog: {
        title: "选择课程表",
        dialog: false,
        width: "890px",
        isCourses: false,
        isDept: false,
      },
      // 查询课程表参数
      queryCourses: {
        keyword: "", //关键字
        orderBy: "createdTime", //时间字段
        order: "desc",
        offset: 0,
        limit: 10,
        timeRangeBy: "createdTime",
        timeRangeStart: "",
        timeRangeEnd: "",
      },
      title: "新建任务",
      taskForm: {
        name: "",
        scheduleList: [],
        departmentList: [],
        dueTime:'',
      },
      isIndeterminate: true,
      allChecked: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      isDisable: false,
      isEdit: false,
      lastCourseIDList: [],
      lastCourseDetailList: [],
      noChecked: [],
      allList: [],
    };
  },
  created() {
    // 已发布已过期 创建副本   1    创建副本是从列表名称点击
    // 已发布未过期 创建副本   2    创建副本是从列表名称点击
    // 未发布已过期 创建副本   3    创建副本是从列表名称点击
    // 未发布未过期 编辑       4    不允许创建副本
    // 不完善                5
    this.getListDepartments();
    this.getListLearningTable();
    if (this.$route.params.status && this.$route.params.id) {
      getLearningTask(this.$route.params.id).then((res) => {
        this.taskForm.name = res.data.name;
        if(res.data.dueTime!=''){
          this.taskForm.dueTime = fecha.format(
            new Date(res.data.dueTime),
            "yyyy-MM-dd HH:mm:ss"
          );
        }
        
        if (res.data.scheduleList != null) {
          this.taskForm.scheduleList = res.data.scheduleList;
          this.taskForm.scheduleList.forEach((val) => {
            val.courseIDList = val.courseList;
          });
        }
        if (res.data.departmentList != null) {
          this.taskForm.departmentList = res.data.departmentList;
        }
      });
    }
  },
  mounted() {
    if (
      this.$route.params.status == 2 ||
      this.$route.params.status == 3 ||
      this.$route.params.status == 1 && !this.$route.params.title
    ) {
      this.isDisable = true;
      this.copy = true;
      this.title = "查看任务";
    } else if (
      this.$route.params.status == 5 ||
      this.$route.params.status == 4 && !this.$route.params.title
    ) {
      this.copy = true;
      this.title = "编辑任务";
      this.isEdit = true;
      this.isDisable = true;
    }else if(this.$route.params.title){
      this.copy = true;
      this.title = "查看任务";
      this.isEdit = true;
      this.isDisable = true;
    }
  },
  watch: {
    isDisable(val) {
      this.isDisable = val;
    },
  },
  methods: {
    pushTask() {
      this.$router.push({ name: "task" });
    },
    disabledChange(){
      if(this.$route.params.status < 4){
        this.title = '创建任务副本';
      }else{
        this.title = '编辑任务';
      }
      this.isDisable = false
      this.isEdit = true
    },
    selectDate() {
      // this.taskForm.dueTime = this.taskForm.dueTime.slice(0,-8)+'23:59:59'
      this.taskForm.departmentList.filter((val) => val.isDept = false);
      this.taskForm.scheduleList.filter((val) => val.isDetail = false);
      this.taskForm.dueTime = moment(this.taskForm.dueTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      console.log(this.taskForm.dueTime)
    },
    loadMore() {
      this.pageIndex++;
      this.queryCourses.offset = (this.pageIndex - 1) * this.queryCourses.limit;
      this.getListLearningTable();
    },
    getListLearningTable() {
      listLearningTable(this.queryCourses).then((res) => {
        this.courseTotal = res.data.total;
        if (res.data.scheduleList != null) {
          this.coursesList = this.coursesList.concat(res.data.scheduleList);
        }
      });
    },
    closeDeptDialog() {
      this.dialog.dialog = false;
      this.dialog.isDept = false;
      this.dialog.title = "";
    },
    // 全选
    handleCheckAllChange(val) {
      if (val == true) {
        this.allChecked = true;
        this.isIndeterminate = false;
        this.toData = this.deptList;
        this.checkedDeptIDList = this.deptList;
        let list = this.toData.map((v) => v.id);
        this.$refs.tree.setCheckedKeys(list);
      } else {
        this.allChecked = false;
        this.isIndeterminate = true;
        this.toData = [];
        this.checkedDeptIDList = [];
        for (var i = 0; i < this.deptList.length; i++) {
          this.uniteChildSame(this.deptList[i], false);
        }
      }
    },
    uniteChildSame(treeList, isSelected) {
      this.$refs.tree.setChecked(treeList.id, isSelected);
      if (treeList.children) {
        for (let i = 0; i < treeList.children.length; i++) {
          this.uniteChildSame(treeList.children[i], isSelected);
        }
      }
    },
    clickDept(data, Status) {
      this.toData = this.getSimpleCheckedNodes(this.$refs.tree.store);
    },
    getSimpleCheckedNodes(store) {
      // 定义数组
      const checkedNodes = [];
      // 判断是否为全选，若为全选状态返回被全选的节点，不为全选状态正常返回被选中的节点
      const traverse = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes;
        childNodes.forEach((child) => {
          if (child.checked) {
            checkedNodes.push(child.data);
          }
          if (child.indeterminate) {
            traverse(child);
          }
        });
      };
      traverse(store);
      return checkedNodes;
    },
    getListDepartments() {
      listDepartments().then((res) => {
        if (res.code && res.code != 0) {
          this.msgError(res.msg);
        } else {
          this.deptList = res.root.children;
        }
      });
    },
    // 删除课程内容
    delDetail(i, item) {
      this.coursesDetailList.push(item);
      var index = i.courseIDList.indexOf(item);
      if (index !== -1) {
        i.courseIDList.splice(index, 1);
      }
    },
    pushDetail(i, item) {
      i.courseIDList.push(item);
      var index = this.coursesDetailList.indexOf(item);
      if (index !== -1) {
        this.coursesDetailList.splice(index, 1);
      }
    },
    clearCourse(item) {
      this.$confirm("确定删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          var index = this.taskForm.scheduleList.indexOf(item);
          if (index !== -1) {
            this.taskForm.scheduleList.splice(index, 1);
          }
          this.msgSuccess("删除成功!");
        })
        .catch(() => {});
    },
    clearDept(item) {
      this.$confirm("确定删除该接受部门, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          var index = this.taskForm.departmentList.indexOf(item);
          if (index !== -1) {
            this.taskForm.departmentList.splice(index, 1);
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    //课程拖拽
    dataDragEnd(evt) {
      evt.preventDefault();
      console.log("拖动前的索引 :" + evt.oldIndex);
      console.log("拖动后的索引 :" + evt.newIndex);
      console.log(this.taskForm.scheduleList);
    },

    //课程详情拖拽
    coursesDetailDragEnd(evt) {
      evt.preventDefault();
      console.log("拖动前的索引 :" + evt.oldIndex);
      console.log("拖动后的索引 :" + evt.newIndex);
      let index = this.taskForm.scheduleList.findIndex((v) => {
        return v.isDetail == true;
      });
      this.$set(
        this.taskForm.scheduleList,
        index,
        this.taskForm.scheduleList[index]
      );
    },
    // 部门详情员工
    selectDeptContent(item) {
      this.taskForm.scheduleList.filter((val) => {
        val.isDetail = false;
      });
      this.taskForm.departmentList.filter((val) => {
        if (val.id === item.id) {
          item.isDept = true;
        } else {
          val.isDept = false;
        }
      });
      if (!item.employeeIDList) {
        deptEmployees({ deptID: item.id }).then((res) => {
          this.deptDetailList = [];
          if (res.employeeList != null) {
            this.deptDetailList = res.employeeList;
            this.$set(
              item,
              "employeeIDList",
              res.employeeList.map((v) => v.id)
            );
            this.checkedDeptEmployeesList = res.employeeList.map((v) => v.id);
          }
        });
      } else {
        deptEmployees({ deptID: item.id }).then((res) => {
          this.checkedDeptEmployeesList = item.employeeIDList;
          if (res.employeeList != null) {
            this.deptDetailList = res.employeeList;
          }
        });
      }
    },
    changeEmployees() {},
    // 确定员工
    confirmEmployees(i) {
      i.employeeIDList = this.checkedDeptEmployeesList;
      let refName = this.refNamePopover + i.id;
      this.$refs[refName][0].doClose();
    },
    cancelDelete(id) {
      let refName = this.refNamePopover + id;
      this.$refs[refName][0].doClose();
    },
    cancelCoursesDetail(item) {
      if (this.lastCourseDetailList.length == 0) {
        this.lastCourseDetailList = this.noChecked;
        item.courseIDList = this.noChecked;
      } else {
        item.courseIDList = this.allList.filter(
          (x) => !this.noChecked.some((item) => x.id === item.id)
        );
      }
      let refName = this.coursesPopover + item.id;
      this.$refs[refName][0].doClose();
    },
    confirmCoursesDetail(item) {
      this.noChecked = this.noChecked.filter(
        (x) => !this.lastCourseDetailList.some((item) => x.id === item.id)
      );
      let refName = this.coursesPopover + item.id;
      this.$refs[refName][0].doClose();
    },
    // 课程表详情
    selectCoursesContent(item) {
      this.taskForm.departmentList.filter((val) => {
        val.isDept = false;
      });
      this.taskForm.scheduleList.filter((val) => {
        if (val.id === item.id) {
          item.isDetail = true;
        } else {
          val.isDetail = false;
        }
      });
      if (item.courseIDList == undefined) {
        this.lastCourseDetailList = [];
        getLearningTable(item.id).then((res) => {
          if (res.data.courseList != null) {
            this.noChecked = res.data.courseList;
          }
        });
      } else {
        this.lastCourseDetailList = item.courseIDList;
        getLearningTable(item.id).then((res) => {
          if (res.data.courseList != null) {
            this.noChecked = res.data.courseList.filter(
              (x) => !item.courseIDList.some((item) => x.id === item.id)
            );
          }
        });
      }
      this.coursesDetail.dialog = true;
      this.coursesDetail.title = item.name;
      if (!item.courseIDList) {
        this.coursesDetailList = [];
        getLearningTable(item.id).then((res) => {
          if (res.data.courseList != null) {
            this.$set(item, "courseIDList", res.data.courseList);
          }
        });
      } else {
        this.coursesDetailList = [];
        getLearningTable(item.id).then((res) => {
          if (res.data.courseList != null) {
            this.coursesDetailList = res.data.courseList.filter(
              (x) => !item.courseIDList.some((item) => x.id === item.id)
            );
          }
        });
      }
      getLearningTable(item.id).then((res) => {
        if (res.data.courseList != null) {
          this.allList = res.data.courseList;
        }
      });
    },
    closeDialog() {},
    confirmDeptForm() {
      this.taskForm.departmentList = this.toData;
      this.toData.forEach((val) => {
        this.DeptEmployeesList.push({
          id: val.id,
          employeeIDList: [],
          isDept: false,
        });
      });
      this.dialog.isDept = false;
      this.dialog.dialog = false;
      this.dialog.title = "";
    },

    handleCheckedChange(flag, data) {
      this.taskForm.scheduleList = this.taskForm.scheduleList.filter((x) =>
        this.lastCourseIDList.some((item) => x.id === item)
      );
      if (flag) {
        this.courseToData.push(data);
        if (this.courseToData.length != 0) {
          let deWeightThree = () => {
            let map = new Map();
            for (let item of this.courseToData) {
              if (!map.has(item.id)) {
                map.set(item.id, item);
              }
            }
            return [...map.values()];
          };
          this.courseToData = deWeightThree();
        }
      } else {
        this.deleteItem(data.id, this.courseToData);
      }
    },
    confirmCoursesForm() {
      this.taskForm.scheduleList = this.courseToData;
      this.taskForm.scheduleList.forEach((val) => {
        this.CoursesListDetail.push({
          id: val.id,
          courseIDList: [],
          isDetail: false,
        });
      });
      this.courseToData = [];
      this.checkedCoursesList = [];
      this.dialog.dialog = false;
      this.dialog.isCourses = false;
    },
    //右侧移除用户
    removeItem(id) {
      this.courseToData = this.courseToData.filter((item) => {
        return item.id != id.id;
      });
      if (this.dialog.isDept == true) {
        this.checkedDeptIDList = this.checkedDeptIDList.filter((item) => {
          return item != id.id;
        });
        this.uniteChildSame(id, false);
      } else {
        this.checkedCoursesList = this.checkedCoursesList.filter((item) => {
          return item != id.id;
        });
      }
    },
    deleteItem(item, list) {
      for (var key in list) {
        if (list[key].id === item) {
          list.splice(key, 1);
        }
      }
    },
    searchType() {
      this.pageIndex = 1;
      this.queryCourses.offset = (this.pageIndex - 1) * this.queryCourses.limit;
      listLearningTable(this.queryCourses).then((res) => {
        if (res.data.scheduleList != null) {
          this.coursesList = res.data.scheduleList;
        }
      });
    },
    clearSearch() {
      this.queryCourses.keyword = "";
      this.pageIndex = 1;
      this.queryCourses.offset = (this.pageIndex - 1) * this.queryCourses.limit;
      listLearningTable(this.queryCourses).then((res) => {
        if (res.data.scheduleList != null) {
          this.coursesList = res.data.scheduleList;
        }
      });
    },
    closeCoursesDialog() {
      this.checkedCoursesList = [];
      this.dialog.dialog = false;
      this.dialog.isCourses = false;
    },
    addCourses() {
      this.queryCourses.keyword = "";
      this.pageIndex = 1;
      this.queryCourses.offset = (this.pageIndex - 1) * this.queryCourses.limit;
      listLearningTable(this.queryCourses).then((res) => {
        this.coursesList = res.data.scheduleList;
      });
      if (this.taskForm.scheduleList.length > 0) {
        this.courseToData = this.taskForm.scheduleList;
        this.checkedCoursesList = this.taskForm.scheduleList.map((val) => {
          return val.id;
        });
        this.lastCourseIDList = this.checkedCoursesList;
      } else {
        this.courseToData = [];
        this.checkedCoursesList = [];
      }
      this.dialog.dialog = true;
      this.dialog.isCourses = true;
    },
    addDept() {
      this.checkedDeptIDList = this.taskForm.departmentList.map((v) => v.id);
      if (this.taskForm.departmentList.length > 0) {
        this.toData = this.taskForm.departmentList;
      } else {
        this.toData = [];
      }
      this.dialog.dialog = true;
      this.dialog.isDept = true;
      this.dialog.title = "选择部门";
    },
    onSubmit() {
      this.$refs.taskForms.validate((valid) => {
        // return false;
        if (valid) {
          let list = [];
          let employeesList = [];
          this.taskForm.scheduleList.forEach((val) => {
            list.push({
              id: val.id,
              courseIDList:
                val.courseIDList && val.courseIDList.length > 0
                  ? val.courseIDList.map((v) => v.id)
                  : null,
            });
          });
          this.taskForm.departmentList.forEach((val) => {
            employeesList.push({
              id: val.id,
              employeeIDList:
                val.employeeIDList && val.employeeIDList.length > 0
                  ? val.employeeIDList
                  : null,
            });
          });
          let data = {
            name: this.taskForm.name,
            departmentList: employeesList,
            scheduleList: list,
            dueTime: this.taskForm.dueTime,
          };
          if (
            this.$route.params.status == 4 ||
            (this.$route.params.status == 5 && this.copy)
          ) {
            learningTaskStatus(data, this.$route.params.id).then((res) => {
              if (res.error == null) {
                this.msgSuccess("编辑成功!");
                this.$router.push({ name: "task" });
              } else {
                this.msgError(res.error);
              }
            });
          } else {
            createLearningTask(data).then((res) => {
              if (res.error == null) {
                this.msgSuccess("创建成功!");
                this.$router.push({ name: "task" });
              } else {
                this.msgError(res.error);
              }
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.more {
  text-align: center;
  color: #1e5aff;
  cursor: pointer;
}
.overflowBox {
  height: 230px;
  overflow-y: auto;
}
.chooseBox ::v-deep .el-dialog__body {
  padding: 10px 20px !important;
  margin-left: 10px;
}
::v-deep .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 192px;
}
::v-deep .dialog-footer {
  text-align: center;
}
.side_left,
.side_right {
  background: #f2f6fc;
  padding: 15px;
  height: 350px;
  box-sizing: border-box;
}
.side_right {
  overflow-y: scroll;
}
.flexLeft {
  cursor: pointer;
  width: 100%;
  height: 30px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  font-size: 14px;
  padding-right: 8px;
}
.choosebox ::v-deep .el-checkbox {
}
.el-checkbox {
  display: block !important;
  height: 30px;
  line-height: 30px;
}
ul,
li {
  list-style: none;
  padding-inline-start: 0;
  margin-block-start: 0;
  margin-block-end: 0;
}
li {
  height: 30px;
  line-height: 30px;
  padding: 0 20px;
}
.userlist {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.org_header {
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;

  align-items: center;
  padding: 0 32px;
  margin-left: -32px;
  margin-right: -32px;
  margin-top: -26px;
}
.subject {
  color: $titleBlue;
  font-weight: bold;
}
.header_btn_box {
  padding: 10px 0 10px;
  display: flex;
}
@media only screen and (max-width: 470px) {
  .message-delete {
    width: 300px;
  }
  .el-message {
    min-width: 300px;
  }
  .el-dialog {
    margin-top: 54vh !important;
  }
}
.course-item {
  margin-bottom: 15px;
  margin-right: 5px;
  width: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  position: relative;
  color: #666;
  display: inline-block;
  font-weight: normal !important;
  padding: 0 10px;
  .el-icon-arrow-right {
    position: absolute;
    right: 10px;
    top: 10px;
  }
}
.courseTip {
  margin-right: 70px;
  font-size: 12px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #999;
  margin-top: -20px;
}
#noHover:hover {
  background: #1e5aff;
}
</style>
