<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <org-tree v-model="queryParams.orgId" @defaultKey="getDefaultKey" @checkChange="checkChange"
                  @click="clickTreeNode" businessTree></org-tree>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="100px">


          <el-form-item label="演练类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择演练类型" clearable>
              <el-option
                v-for="dict in dict.type.core_drill_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="任务时间" prop="rangen">
            <el-date-picker
              v-model="queryParams.range"
              type="daterange"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="演练状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择演练状态" clearable>
            <el-option
              v-for="dict in dict.type.drill_task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
      </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>

        </el-form>


        <el-table height="550px" v-loading="loading" :data="eduTaskList" @selection-change="handleSelectionChange">
          <el-table-column label="演练机构" align="center" prop="orgName"/>
          <el-table-column label="演练角色" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.taskRoleNameList  ">
                <el-tag size="mini" type="success"
                        v-for="(item, index) in (scope.row.taskRoleNameList || '').split(',')"
                        :key="index">
                  {{ item }}
                </el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="演练类型" align="center" prop="type">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.core_drill_type" :value="scope.row.type"/>
            </template>
          </el-table-column>

          <el-table-column label="开始日期" align="center" prop="startDate" width="180">
          </el-table-column>
          <el-table-column label="截止日期" align="center" prop="endDate" width="180">
          </el-table-column>
          <el-table-column label="指挥人" align="center" prop="hostName"/>
          <el-table-column label="演练地点" align="center" prop="drillSite"/>
          <el-table-column label="演练状态" align="center" prop="status" >
        <template slot-scope="scope">
            <dict-tag :options="dict.type.drill_task_status" :value="scope.row.status"/>
          </template>
      </el-table-column>
          <el-table-column label="评分" align="center" prop="commentScore"/>

          <el-table-column scoped-slot="comment" align="center" prop="comment" label="评语">
            <template slot-scope="scope">
              <div class="ellipsis" :title="scope.row.comment">{{ scope.row.comment }}</div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120px" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDetail(scope.row.id)"
                v-hasPermi="['core:drillTask:query']"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-document-add"
                v-if="canEvaluate(scope.row)"
                @click="handleRecorded(scope.row.id)"
                v-hasPermi="['core:drillTask:evaluate']"
              >评价</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-document-add"
                v-if="canPerform(scope.row)"
                @click="handleRecorded(scope.row.id)"
                v-hasPermi="['core:drillTask:edit']"
              >演练登记</el-button>
              <el-button type="text" v-if="scope.row.pdfUrl" @click="onDown(scope.row.pdfUrl)"
              >演练登记簿</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <dialog-info ref="infoDialog" @success="handleQuery(true)"></dialog-info>
    <dialog-perform ref="performDialog" @success="handleQuery(true)"></dialog-perform>
  </div>
</template>

<script>
import {listEduTask, addEduTask, updateEduTask} from "@/api/core/drill/drillTask";
import OrgTree from "@/components/orgTree";
import DialogInfo from "./dialog.info";
import DialogPerform from "./dialog.perform";
import dayjs from "dayjs";

export default {
  name: "EduTask",
  dicts: ['drill_task_status','core_drill_type'],
  components: {
    DialogInfo,
    DialogPerform,
    OrgTree
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教育任务表格数据
      eduTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        checkSub: true,
        title: null,
        orgId: this.$store.getters.orgId,
        type: null,
        status: null,
        range: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orgId: [
          {required: true, message: "机构不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },

  methods: {
    /** 查询教育任务列表 */
    getList() {
      this.loading = true;
      listEduTask(this.queryParams).then(response => {
        this.eduTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        range: [],
        title: null,
        type: null,
        status: null,
        checkSub:true,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //单选框状态改变
    checkChange(state) {
      this.queryParams.checkSub = state;
      this.handleQuery();
    },
    getDefaultKey(key) {
      this.queryParams.orgId = key;
      this.getList();
    },
    // 节点单击事件
    clickTreeNode(data) {
      this.queryParams.orgId = data.id;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教育任务";
    },
    /** 修改按钮操作 */
    handleDetail(id) {
      this.$refs["infoDialog"].show(id, {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEduTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEduTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 培训登记按钮操作 */
    handleRecorded(id) {
      this.$refs["performDialog"].show(id, {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/eduTask/export', {
        ...this.queryParams
      }, `eduTask_${new Date().getTime()}.xlsx`)
    },
    canEvaluate(row){
      //仅行社安全保卫管理人员进入且演练任务处于待评价状态才显示
      return row.status==2 && this.$store.getters.roleList.some(item=>item.roleId==120)&&this.isNotOverOrUnStart(row);
    },
    canPerform(row) {
      // return true;
      let flag = 0;
      if (row.status > 0) return false;
      if (!row.taskRoleList) return false;
      let isOver = this.isNotOverOrUnStart(row);
      console.log("isNotOverOrUnStart", isOver);
      row.taskRoleList.forEach((taskRole) => {
        this.$store.getters.roleList.forEach((role) => {
          if (taskRole.roleId == role.roleId) {
            flag = 1;
          }
        });
      });
      return (flag == 1) && isOver;
    },
    isNotOverOrUnStart(row) {
      const currentTime = dayjs().startOf('day'); // 获取当前时间，并将时分秒部分设置为00时00分00秒
      const startDate = dayjs(row.startDate).startOf('day'); // 转换开始时间为 Moment.js 对象，并将时分秒部分设置为00时00分00秒
      const endDate = dayjs(row.endDate).startOf('day'); // 转换结束时间为 Moment.js 对象，并将时分秒部分设置为00时00分00秒
      console.log("isOverOrUnStart", currentTime, startDate, endDate);
      return !(currentTime < startDate || currentTime > endDate);
    },
    async onDown(pdfUrl) {
      // const data = await this.$api.eduTraining.predown(id);
      window.open(pdfUrl);
    },
  }
};
</script>
