<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="filter-container">
        <el-checkbox v-model="listQuery.unfinished">任务未办结</el-checkbox>
        <el-checkbox v-model="listQuery.finished">任务已办结</el-checkbox>
        <el-checkbox v-model="listQuery.processUnfinished"
          >流程未办结</el-checkbox
        >
        <el-checkbox v-model="listQuery.processFinished"
          >流程已办结</el-checkbox
        >
      </div>
      <div class="filter-container">
        <el-input
          v-model="listQuery.processInstanceId"
          placeholder="流程实例ID"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-input
          v-model="listQuery.taskId"
          placeholder="任务ID"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-input
          v-model="listQuery.taskName"
          placeholder="任务名称"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-input
          v-model="listQuery.processInstanceBusinessKey"
          placeholder="业务主键"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-input
          v-model="listQuery.taskAssignee"
          placeholder="执行人"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-input
          v-model="listQuery.taskOwner"
          placeholder="所有人"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-input
          v-model="listQuery.taskInvolvedUser"
          placeholder="干系人"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-input
          v-model="listQuery.parentTaskId"
          placeholder="父任务ID"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="btnQuery"
        />
        <el-date-picker
          v-model="listQuery.taskDueAfter"
          value-format="yyyy-MM-dd"
          placeholder="到期日开始"
          type="date"
          style="width: 200px"
          class="filter-item"
        ></el-date-picker>
        <el-date-picker
          v-model="listQuery.taskDueBefore"
          value-format="yyyy-MM-dd"
          placeholder="到期日结束"
          type="date"
          style="width: 200px"
          class="filter-item"
        ></el-date-picker>
        <el-date-picker
          v-model="listQuery.taskCreatedAfter"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="创建时间开始"
          type="datetime"
          style="width: 200px"
          class="filter-item"
        ></el-date-picker>
        <el-date-picker
          v-model="listQuery.taskCreatedBefore"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="创建时间结束"
          type="datetime"
          style="width: 200px"
          class="filter-item"
        ></el-date-picker>
        <el-date-picker
          v-model="listQuery.taskCompletedAfter"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="完成时间开始"
          type="datetime"
          style="width: 200px"
          class="filter-item"
        ></el-date-picker>
        <el-date-picker
          v-model="listQuery.taskCompletedBefore"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="完成时间结束"
          type="datetime"
          style="width: 200px"
          class="filter-item"
        />
        <el-dropdown
          split-button
          type="primary"
          class="filter-item"
          @click="btnQuery"
        >
          <i class="el-icon-search el-icon--left" />查询
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item icon="el-icon-zoom-out" @click.native="btnReset"
              >重置</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="systemRoleTable10"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <!-- <el-button
            icon="el-icon-plus"
            type="primary"
            @click="btnImport"
            class="ele-btn-icon"
            >导入
          </el-button> -->
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-dropdown>
            <span class="el-dropdown-link"
              >操作<i class="el-icon-arrow-down el-icon--right"></i
            ></span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                icon="el-icon-view"
                @click.native="btnViewTask(row)"
                >查看</el-dropdown-item
              >
              <el-dropdown-item
                icon="el-icon-view"
                divided
                @click.native="btnView(row.processInstanceId)"
                >查看详情
              </el-dropdown-item>
              <el-dropdown-item
                icon="el-icon-edit"
                v-if="
                  (row.endTime == null || row.endTime == '') &&
                  (row.assignee == null || row.assignee == '')
                "
                divided
                @click.native="btnClaim(row)"
                >认领并执行
              </el-dropdown-item>
              <el-dropdown-item
                icon="el-icon-edit"
                v-if="
                  (row.endTime == null || row.endTime == '') &&
                  row.assignee == userId
                "
                divided
                @click.native="btnUnclaim(row)"
                >取消认领
              </el-dropdown-item>
              <el-dropdown-item
                v-if="
                  (row.endTime == null || row.endTime == '') &&
                  (row.assignee != null || row.assignee != '') &&
                  row.assignee == userId
                "
                icon="el-icon-edit"
                divided
                @click.native="btnExcuteTask(row)"
                >执行
              </el-dropdown-item>
              <!-- TODO 回收任务 -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 弹窗任务信息 -->
    <task-detail
      v-if="dialogTaskDetailVisible"
      :visible.sync="dialogTaskDetailVisible"
      :dicts="dicts"
      :taskDetailData="taskDetailData"
    ></task-detail>
    <!-- 执行任务 -->
    <execute-task
      v-if="dialogExcuteTaskVisible"
      :visible.sync="dialogExcuteTaskVisible"
      :executeTaskId="executeTaskId"
      @executeTaskFinished="list"
    ></execute-task>
    <process-detail
      v-if="dialogViewVisible"
      :visible.sync="dialogViewVisible"
      :processInstanceId="processInstanceId"
    ></process-detail>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination';
  import {
    deleteAction,
    getAction,
    postAction,
    putAction
  } from '@/api/flowable/manage';
  import { Message } from 'element-ui';
  import TaskDetail from '../components/TaskDetail';
  import ExecuteTask from '../components/ExecuteTask';
  import ProcessDetail from '../components/ProcessDetail';

  export default {
    name: 'FlowableTask',
    components: { Pagination, TaskDetail, ExecuteTask, ProcessDetail },
    data () {
      return {
        columns: [
          {
            type: 'index',
            label: '序号',
            width: 50,
            align: 'center',
            fixed: 'left'
          },

          {
            prop: 'processInstanceName',
            label: '流程实例名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '任务名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'claimTime',
            label: '开始时间',
            align: 'center',

            showOverflowTooltip: true
          },
          {
            prop: 'endTime',
            label: '结束时间',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'owner',
            label: '所有人',
            align: 'center',

            showOverflowTooltip: true
          },

          {
            prop: 'assignee',
            label: '执行人',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 230,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],

        dicts: [],
        records: null,
        selectedRecords: [],
        total: 0,
        userId: localStorage.getItem('userId'),
        listQuery: {
          processInstanceId: undefined,
          taskId: undefined,
          taskName: undefined,
          processInstanceBusinessKey: undefined,
          taskDescription: undefined,
          taskAssignee: undefined,
          taskOwner: undefined,
          taskInvolvedUser: undefined,
          finished: false,
          unfinished: false,
          processFinished: false,
          processUnfinished: false,
          suspended: false,
          active: false,
          taskParentTaskId: undefined,
          taskDueBefore: undefined,
          taskDueAfter: undefined,
          taskCreatedBefore: undefined,
          taskCreatedAfter: undefined,
          taskCompletedBefore: undefined,
          taskCompletedAfter: undefined,
          taskCandidateUser: undefined,
          taskCandidateGroupIn: undefined
        },
        dialogTaskDetailVisible: false,
        dialogExcuteTaskVisible: false,
        dialogTaskBackNodesVisible: false,
        formJson: undefined,
        taskDetailData: {
          id: '',
          name: '',
          description: '',
          category: '',
          owner: '',
          assignee: '',
          claimTime: '',
          dueDate: '',
          endTime: '',
          durationInMillis: '',
          workTimeInMillis: '',
          priority: '',
          taskDefinitionKey: '',
          processInstanceId: '',
          processInstanceName: '',
          processDefinitionId: '',
          processDefinitionName: '',
          processDefinitionDescription: '',
          processDefinitionKey: '',
          processDefinitionCategory: '',
          processDefinitionVersion: '',
          processDefinitionDeploymentId: '',
          formKey: '',
          renderedTaskForm: '',
          processInstanceStartUserId: '',
          initiatorCanCompleteTask: '',
          memberOfCandidateGroup: '',
          memberOfCandidateUsers: '',
          delegationState: '',
          suspended: '',
          involvedPeople: '',
          ownerName: '',
          assigneeName: '',
          tenantId: ''
        },
        executeTaskId: '',
        processInstanceId: '',
        dialogViewVisible: false
      };
    },

    watch: {
      $route: {
        handler (route) {
          if (route.query && route.query.processInstanceId) {
            this.listQuery.processInstanceId = route.query.processInstanceId;
          } else {
            this.listQuery.processInstanceId = undefined;
          }
          this.$refs.table?.reload({ page: 1 });
        },
        immediate: true
      }
    },
    methods: {
      async datasource ({ page, limit }) {
        const res = await getAction('/flowable/task/list', {
          ...this.listQuery,
          current: page,
          size: limit
        });
        const { data } = res.data;
        return {
          list: data.records,
          count: data.total
        };
      },
      list () {
        this.$refs.table.reload({ page: 1 });

        // getAction('/flowable/task/list', this.listQuery).then((res) => {
        //   const { data } = res;
        //   this.records = data.data.records;
        //   this.total = data.data.total;
        // });
      },
      btnQuery () {
        this.listQuery.current = 1;
        this.list();
      },
      btnReset () {
        this.listQuery = {
          processInstanceId: undefined,
          taskId: undefined,
          taskName: undefined,
          processInstanceBusinessKey: undefined,
          taskDescription: undefined,
          taskAssignee: undefined,
          taskOwner: undefined,
          taskInvolvedUser: undefined,
          finished: false,
          unfinished: false,
          processFinished: false,
          processUnfinished: false,
          taskParentTaskId: undefined,
          taskDueBefore: undefined,
          taskDueAfter: undefined,
          taskCreatedBefore: undefined,
          taskCreatedAfter: undefined,
          taskCompletedBefore: undefined,
          taskCompletedAfter: undefined,
          taskCandidateUser: undefined,
          taskCandidateGroupIn: undefined
        };
        this.list();
      },

      btnViewTask (row) {
        getAction('/flowable/task/queryById', { taskId: row.id }).then(
          (res) => {
            const { data } = res.data;
            this.taskDetailData = Object.assign({}, data);
            this.dialogTaskDetailVisible = true;
          }
        );
      },
      btnClaim (row) {
        putAction('/flowable/task/claim', { taskId: row.id })
          .then(({ msg }) => {
            this.list();
            this.btnExcuteTask(row);
          })
          .catch((response) => {
            this.list();
          });
      },
      btnUnclaim (row) {
        putAction('/flowable/task/unclaim', { taskId: row.id }).then(
          ({ data }) => {
            Message.success(data.message);
            this.list();
          }
        );
      },
      btnExcuteTask (row) {
        this.executeTaskId = row.id;
        this.dialogExcuteTaskVisible = true;
      },
      doExcuteTask () {
        this.$refs.generateForm
          .getData()
          .then((values) => {
            putAction('/flowable/task/complete', {
              taskId: this.taskDetailData.id,
              values: values
            }).then(({ msg }) => {
              Message.success(msg);
              this.dialogExcuteTaskVisible = false;
              this.list();
            });
          })
          .catch((e) => {
            // data check failed
          });
      },
      btnBackTask (row) {
        this.executeTaskId = row.id;
        this.dialogTaskBackNodesVisible = true;
      },
      btnView (processInstanceId) {
        this.processInstanceId = processInstanceId;
        this.dialogViewVisible = true;
      },
      selectionChange (selectedRecords) {
        this.selectedRecords = selectedRecords;
      }
    }
  };
</script>
