<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <div class="org_header">
          <span class="subject">任务列表</span>
          <div class="header_btn_box">
            <el-button size="mini" @click="reTask">重置</el-button>
            <el-button type="primary" size="mini" @click="taskAdd">
              新建任务
            </el-button>
          </div>
        </div>
        <el-row
          :gutter="18"
          class="mt10 el-flex"
          justify="space-between"
          type="flex"
        >
          <el-col :span="18" class="mt10 selectOrg">
            <el-form :model="queryParams" :inline="true">
              <el-row :gutter="18">
                <el-col :span="24">
                  <el-form-item label="" prop="query">
                    <el-input
                      prefix-icon="el-icon-search"
                      v-model="queryParams.keyword"
                      placeholder="请输入关键字搜索"
                      clearable
                      size="small"
                      @keyup.enter.native="filterQuery"
                      @clear="reTask()"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="" prop="courses">
                    <el-cascader
                      placeholder="选择组织"
                      v-model="queryParams.toDeptIdList"
                      :options="coursesList"
                      @change="filterQuery"
                      clearable
                      size="small"
                      :props="{
                        value: 'id',
                        label: 'name',
                        checkStrictly: true,
                        emitPath: false,
                      }"
                    >
                      <template slot-scope="{ data }">
                        <span>{{ data.name }}</span>
                      </template>
                    </el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="18">
                <el-col :span="24">
                  <el-form-item label="创建时间" prop="date">
                    <el-date-picker
                      style="width: 260px"
                      size="small"
                      format="yyyy-MM-dd"
                      v-model="createDate"
                      type="daterange"
                      range-separator="至"
                      placeholder="选择创建日期"
                      @change="selectCreateDate(createDate)"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="截止时间" prop="date">
                    <el-date-picker
                      style="width: 260px"
                      size="small"
                      format="yyyy-MM-dd"
                      v-model="endDate"
                      type="daterange"
                      range-separator="至"
                      placeholder="选择截止日期"
                      @change="selectEndDate(endDate)"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
          <el-col :span="1.5" class="mb8 mt10">
            <el-dropdown class="m20" @command="searchType">
              <el-button type="primary" size="mini">
                筛选<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">全部</el-dropdown-item>
                <el-dropdown-item command="2">已过期任务</el-dropdown-item>
                <el-dropdown-item command="3">未过期任务</el-dropdown-item>
                <el-dropdown-item command="4">已发布任务</el-dropdown-item>
                <el-dropdown-item command="5">未发布任务</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="learningList"
          tooltip-effect="dark"
          style="width: 100%"
          v-loading="loading"
          @sort-change="handleSortChang"
        >
          <el-table-column prop="name" label="任务名称">
            <template slot-scope="scope">
              <el-link
                type="primary"
                style="color: #1e5aff"
                :underline="false"
                @click="pushAdd(scope.row)"
              >
                {{ scope.row.name }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="接收部门" align="left" prop="employeeIDList">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.departmentNameList != null
                    ? scope.row.departmentNameList[0]
                    : ""
                }}
              </div>
              <div>
                {{
                  scope.row.departmentNameList != null
                    ? scope.row.departmentNameList[1]
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="creatorName" label="发布人">
            <template slot-scope="scope">
              <span>{{ scope.row.creatorName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="left"
            prop="createdTime"
            :formatter="parseTime"
            sortable="custom"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="dueTime"
            label="截止时间"
            :formatter="compareTime"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.dueTime ? compareTime(scope.row.dueTime) : "(未设置截止时间)"
              }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="published" label="发布" align="center">
            <template slot-scope="scope">
              <div>
                <el-switch
                  v-model="scope.row.published"
                  @change="publishedChange(scope.row, scope.row.published)"
                >
                </el-switch>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-row
          :gutter="24"
          class="mb8 mt10"
          justify="space-between"
          type="flex"
        >
          <el-col :span="12"> </el-col>
          <el-col
            :span="12"
            class="mb8 mt10 selectOrg"
            style="justify-content: end"
          >
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="pageIndex"
              :limit.sync="queryParams.limit"
              @pagination="getListTask"
            />
          </el-col>
        </el-row>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import moment from "moment";
import * as fecha from "element-ui/lib/utils/date";
import { listDepartments } from "@/api/jobs";
import { listLearning, learningTaskStatus } from "@/api/learning";
export default {
  name: "task",
  components: {
    moment,
  },
  data() {
    return {
      createDate: [],
      endDate: [],
      moment,
      published: false,
      learningList: [],
      coursesList: [],
      orgList: [],
      loading: false,
      pageIndex: 1,
      // 总条数
      total: 0,
      //弹窗宽度
      width: "890px",
      // 查询参数
      queryParams: {
        keyword: "",
        offset: 0,
        limit: 10,
        orderBy: "createdTime",
        order: "desc",
        timeRangeBy: "",
        timeRangeStart: "",
        timeRangeEnd: "",
        toDeptIdList: "",
      },
    };
  },
  created() {
    this.getListOrg();
    this.getListTask();
  },
  methods: {
    reTask() {
      this.queryParams = {
        keyword: "",
        offset: 0,
        limit: 10,
        orderBy: "createdTime",
        order: "desc",
        timeRangeBy: "",
        timeRangeStart: "",
        timeRangeEnd: "",
        toDeptIdList: "",
      };
      this.createDate = "";
      this.endDate = "";
      this.pageIndex = 1;
      this.getListTask();
    },
    publishedChange(item, flag) {
      console.log(item);
      let data = {
        publish: flag,
      };
      // 已发布已过期 创建副本   1    创建副本是从列表名称点击
      // 已发布未过期 创建副本   2    创建副本是从列表名称点击
      // 未发布已过期 创建副本   3    创建副本是从列表名称点击
      // 未发布未过期 编辑       4    不允许创建副本
      // 不完善                5
      let day = new Date(item.dueTime);
      let now = new Date();
      // 当前状态已发布已过期
      if (item.dueTime == "") {
        this.$confirm("您未设置截至日期，请编辑后再发布?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
          .then(() => {
            this.$router.push({
              name: "taskAdd",
              params: { status: 5, id: item.id },
            });
          })
          .catch(() => {
            this.getListTask();
          });
      } else if (item.courseCount == 0 || item.employeeCount == 0) {
        this.$confirm("您即将发布的任务不完善，请编辑后再发布?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
          .then(() => {
            this.$router.push({
              name: "taskAdd",
              params: { status: 5, id: item.id },
            });
          })
          .catch(() => {
            this.getListTask();
          });
      } else {
        if (day.getTime() < now.getTime() && item.published) {
          this.$confirm(
            "当前任务已过期，您可创建任务副本并重新设置任务截至时间?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              center: true,
            }
          )
            .then(() => {
              this.$router.push({
                name: "taskAdd",
                params: { status: 2, id: item.id },
              });
            })
            .catch(() => {
              this.getListTask();
            });
        } else if (day.getTime() < now.getTime() && !item.published) {
          this.$confirm(
            "当前任务已过期，您可创建任务副本并重新设置任务截至时间?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              center: true,
            }
          )
            .then(() => {
              this.$router.push({
                name: "taskAdd",
                params: { status: 3, id: item.id },
              });
            })
            .catch(() => {
              this.getListTask();
            });
        }
        // 当前状态未发布未过期
        if (day.getTime() > now.getTime() && item.published) {
          this.$confirm("确定发布该任务吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true,
          })
            .then(() => {
              console.log(1);
              learningTaskStatus(data, item.id).then((res) => {
                console.log(res);
                if (res.code && res.code != 0) {
                } else {
                  this.msgSuccess("发布成功!");
                  this.getListTask();
                }
              });
            })
            .catch(() => {
              this.getListTask();
            });
        } else if (day.getTime() > now.getTime() && !item.published) {
          this.$confirm(
            "如果撤销发布，员工当前任务失效并消失确认操作吗？",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              center: true,
            }
          )
            .then(() => {
              learningTaskStatus(data, item.id).then((res) => {
                if (res.code && res.code != 0) {
                } else {
                  this.msgSuccess("撤销成功!");
                  this.getListTask();
                }
              });
            })
            .catch(() => {
              this.getListTask();
            });
        }
      }
    },
    compareTime(dueTime) {
      let status = "";
      let day = new Date(dueTime);
      let now = new Date();
      if (day.getTime() < now.getTime()) {
        status = `${moment(dueTime).format("YYYY-MM-DD HH:mm:ss")}(已过期)`;
      } else {
        status = moment(dueTime).format("YYYY-MM-DD HH:mm:ss");
      }
      return status;
    },
    // 创建时间
    selectCreateDate(date) {
      this.endDate = "";
      if (date != null) {
        let start = fecha.format(new Date(date[0]), "yyyy-MM-dd HH:mm:ss");
        let end = fecha.format(new Date(date[1]), "yyyy-MM-dd HH:mm:ss");
        console.log(start, end, "截止时间");
        this.queryParams.timeRangeBy = "createTime";
        this.queryParams.timeRangeStart = start;
        this.queryParams.timeRangeEnd = end;
        this.pageIndex = 1;
        this.getListTask();
      } else {
        this.reTask();
      }
    },
    // 截止时间
    selectEndDate(date) {
      this.createDate = "";
      if (date != null) {
        let start = fecha.format(new Date(date[0]), "yyyy-MM-dd HH:mm:ss");
        let end = fecha.format(new Date(date[1]), "yyyy-MM-dd HH:mm:ss");
        console.log(start, end, "截止时间");
        this.queryParams.timeRangeBy = "dueTime";
        this.queryParams.timeRangeStart = start;
        this.queryParams.timeRangeEnd = end.slice(0,-8) + '23:59:59';
        this.pageIndex = 1;
        this.getListTask();
      } else {
        this.reTask();
      }
    },
    searchType(index) {
      if (index == 2) {
        delete this.queryParams.published;
        this.queryParams.overDue = true;
      } else if (index == 3) {
        this.queryParams.overDue = false;
        delete this.queryParams.published;
      } else if (index == 4) {
        delete this.queryParams.overDue;
        this.queryParams.published = true;
      } else if (index == 5) {
        delete this.queryParams.overDue;
        this.queryParams.published = false;
      }
      this.pageIndex = 1;
      this.getListTask();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
      this.multiple = 0;
    },
    editSelectOcc() {},
    editSelectOccS() {},
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop;
      order = column.order;
      this.queryParams.orderBy = prop;
      if (order === "descending") {
        this.queryParams.order = "desc";
      } else if (order === "ascending") {
        this.queryParams.order = "asc";
      } else {
        this.queryParams.order = "desc";
      }
      this.getListTask();
    },
    // 关键字搜索
    filterQuery(value) {
      console.log(1);
      this.pageIndex = 1;
      this.queryParams.offset = (this.pageIndex - 1) * this.queryParams.limit;
      this.getListTask();
    },
    /**选择组织查询 */
    querySelectOrg(value) {
      this.isEdit = false;
      if (value != undefined) {
        this.queryParams.deptID = value.slice(-1).toString();
      }
      this.getListTask();
    },
    /**获取任务列表 */
    getListTask() {
      this.loading = true;
      this.queryParams.offset = (this.pageIndex - 1) * this.queryParams.limit;
      listLearning(this.queryParams).then((res) => {
        this.learningList = res.data.learningTaskList;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    /**获取任务 */
    getListOrg() {
      listDepartments().then((res) => {
        this.coursesList = res.root.children;
      });
    },
    /** 添加用户 */
    taskAdd(command) {
      // 已发布已过期 创建副本   1    创建副本是从列表名称点击
      // 已发布未过期 创建副本   2    创建副本是从列表名称点击
      // 未发布已过期 创建副本   3    创建副本是从列表名称点击  弹窗确定点击
      // 未发布未过期 编辑       4    不允许创建副本

      // 未发布
      this.$router.push({ name: "taskAdd", params: { published: 5 } });
    },
    pushAdd(item) {
      console.log(item);
      let day = new Date(item.dueTime);
      let now = new Date();
      if (item.dueTime == "") {
        this.$router.push({
          name: "taskAdd",
          params: {
            status: 4,
            id: item.id,
            published: item.published,
            dueTime: false,
            title:true
          },
        });
      } else if (day.getTime() > now.getTime() && item.published == false) {
        this.$router.push({
          name: "taskAdd",
          params: {
            status: 4,
            id: item.id,
            published: item.published,
            dueTime: false,
            title:true
          },
        });
      } else if (day.getTime() > now.getTime() && item.published == true) {
        this.$router.push({
          name: "taskAdd",
          params: { status: 3, id: item.id,title:true },
        });
      } else {
        this.$router.push({
          name: "taskAdd",
          params: { status: 2, id: item.id, published: item.published,title:true },
        });
      }
      // 已发布已过期 创建副本   1    创建副本是从列表名称点击
      // 已发布未过期 创建副本   2    创建副本是从列表名称点击
      // 未发布已过期 创建副本   3    创建副本是从列表名称点击  弹窗确定点击
      // 未发布未过期 编辑       4    不允许创建副本
    },
  },
};
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  line-height: 1.8;
}
@import "~@/styles/variables.scss";
.over-y {
  overflow-y: auto;
  height: 210px;
}
.flex-col {
  display: flex;
  justify-content: center;
  align-items: center;
}
.col-style {
  text-align: center;
  margin: 0;
  font-size: 14px;
  font-family: PingFangSC-Medium;
  line-height: 22px;
  color: #000;
}
.addForms {
  width: 1200px;
}
.center-box {
  width: 636px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e9e9e9;
  margin-bottom: 32px;
  .dialog-tip {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 24px;
    color: rgba(0, 0, 0, 0.85);
  }
}
.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;
}
.el-flex {
  background-color: #fff;
}
.selectOrg {
  display: flex;
}
.input_width {
  width: 468px;
}
.select_width {
  width: 136px;
}
.chooseBox ::v-deep .el-dialog__body {
  padding: 10px 20px !important;
}
::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;
}
.side_right {
  overflow-y: scroll;
}

.flexDiv {
  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;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.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;
}
::v-deep .el-table th > .cell {
  padding-left: 24px;
}
::v-deep .el-table .cell {
  padding-left: 24px;
}
::v-deep .el-link--inner {
  font-weight: 400;
  font-size: 14px;
  font-family: PingFang SC;
}
@media only screen and (max-width: 470px) {
  .message-delete {
    width: 300px;
  }
  .el-message {
    min-width: 300px;
  }
  .el-dialog {
    margin-top: 54vh !important;
  }
}
</style>
