<template>
    <div class="container">
        <div class="mod-role" style="height:100%;overflow:auto;">
            <el-form :inline="true" @submit.native.prevent @keyup.enter.native="loadProcessDefList(1)" style="margin:20px 0px 0px 10px">
                <el-form-item>
                    <el-input v-model="form.procdefkey" placeholder="流程定义key" clearable></el-input>
                </el-form-item>
                  <el-form-item>
                    <el-input v-model="form.processInstanceId" placeholder="实例ID" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="search" @click="loadProcessDefList(1)">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-position" type="search" @click="doView()">重发待办</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-refresh-left" type="search" @click="doRecall()">召回</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="list" border  v-loading="loading" style="width: 100%">
                <!-- <el-table-column align="center" label="选择" :selectable="chkstu" width="80" type="selection"></el-table-column> -->
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-table @selection-change="checkedChange" @select="select" ref="multipleTable" @select-all="selectAll" :data="props.row.taskList" :header-cell-style="{ background: '#e0f3ff', color: '#5f95b7' }" border stripe highlight-current-row="true" style="width: 100%">
                            <!-- :selectable="chkstu" 禁止选用-->
                            <el-table-column align="center" label="选择"  width="80" type="selection"></el-table-column>
                            <el-table-column align="center" prop="taskId" label="任务id"></el-table-column>
                            <el-table-column align="center" prop="taskName" label="名称"></el-table-column>
                            <el-table-column align="center" prop="userName" label="任务处理人"></el-table-column>
                            <el-table-column align="center" prop="assignee" label="任务处理人id"></el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="processInstanceId" label="实例ID"></el-table-column>
                <el-table-column align="center" prop="processDefinitionKey" label="流程定义key"></el-table-column>
                <el-table-column align="center" prop="processDefinitionId" label="流程定义id"></el-table-column>

                <el-table-column align="center" prop="processDefinitionName" label="流程名称"></el-table-column>
            </el-table>
            <el-pagination style="margin:10px 10px 0px 10px;float:right" @current-change="loadProcessDefList"  :page-size="form.rows" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>

            <so-distribution v-if="soDistributionVisible" ref="soDistribution" @select="onGotoDialogSelect"></so-distribution>
            <el-dialog title="重发代办" v-if="editFormVisible" :visible.sync="editFormVisible" width="40%" @close="closeEliminateData" style="text-align:left">
                <div style="padding:20px">
                    <el-form label-position="left" label-width="80px" :inline="true" @submit.native.prevent @keyup.enter.native="doSearch(1)">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="处理节点:">
                                    {{ taskname }}
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="审核角色:">
                                    <el-select v-model="userRole" @change="changeUser" placeholder="请选择...">
                                        <el-option v-for="item in userArr" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="审核人:">
                                    <el-select v-model="userMan" @change="userIdchange" placeholder="请选择...">
                                        <el-option v-for="item in userArr1" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addSend">确 定</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>
<script>
// import UserOpenDialog from '@/page/components/userOpenDialog'
import WfActivitySelect from './wfActivitySelect'
import SoDistribution from './doDistribution'
import { processDefinitionKey as getService } from '@/components/components/approvalDialog/index-mixins.js'
export default {
  data() {
    return {
      loading:false,
      editFormVisible: false,
      soDistributionVisible: false,
      checkededRows: [],
      list: null,
      viewImg: null,
      processDefinationlist: [{}, {}],
      startDateRange: null,
      total: 0,
      form: {
        page: 1,
        rows: 10,
        procdefkey: '',
        processInstanceId: ''
      },
      tableData3: [],
      userId: '',
      userArr: [],
      userArr1: [],
      userRole: '', //审核角色
      userMan: '',
      taskname: '',

      taskId: '',
      userId: '',
      // 上一个选中的表格组件
      previousTableCom: null
      // activeti.getUsersByRoleIds
    }
  },
  components: {
    SoDistribution,
    WfActivitySelect
  },
  mounted() {
    this.loadProcessDefList(1)
  },
  methods: {
    loadProcessDefList(value) {
      let self = this
      this.form.page = value

      var obj = {
        url: this.$url.workflowdef.getruns,
        data: this.form,
        type: 'post'
      }
      this.common.httpPost(obj, success)
      function success(data) {
        data.data.rows.forEach(el => {
          el.taskList.forEach(element => {
            element.processDefinitionKey = el.processDefinitionKey
          })
        })
        self.list = data.data.rows
        self.list.forEach(el => {
          el.taskList.map(item => {
            item.processInstanceId = el.processInstanceId
            item.processDefinitionKey = el.processDefinitionKey
          })
        })
        self.total = data.data.total
      }
    },
    onStartDateRangeChanged(val) {
      this.form.startDateBegin = val[0]
      this.form.startDateEnd = val[1]
    },
    chkstu(row, index) {
      return row.assignee ? false : true
    },
    // 禁用全选按钮
    selectAll() {
      this.$refs.multipleTable.clearSelection()
    },
    async addSend() {
      // console.log(this.userId)
      // console.log(this.taskId)
      if (!(this.userId && this.taskId)) return this.$message.error('请选择审核角色或审核人！')
      var obj = {
        url: this.$url.processinst.setPermission1,
        data: {
          userId: this.userId + '',
          taskId: this.taskId
        }
      }
      const { data: res } = await this.common.postRequest(obj)
      // console.log(res)
      if (res.code !== 1) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.editFormVisible = false
      this.loadProcessDefList(1)
    },
    // 召回
    doRecall() {
      if (!(this.deleteList && this.deleteList.length > 0)) return this.$message.error('选择要召回的待办！')
      this.$confirm('此操作将把待办召回, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
            console.log( this.deleteList[0]);
          let { businessKey, processInstanceId } = this.deleteList[0]
          let service = getService(this.deleteList[0].processDefinitionKey, true)
          let url = eval('`' + this.$url.activeti.recallProcess + '`')
          console.log(this.deleteList[0])

          let obj = {
            url,
            data: {
              id: businessKey,
              processInstanceId
            }
          }
          const res = await this.common.postRequest(obj)
          if (res.code !== '1') return this.$message.error('召回失败！')
          this.$message.success('召回成功！')
          this.loadProcessDefList(1)
        })
        .catch(err => {
          this.$message({
            type: 'info',
            message: '已取消召回！'
          })
        })
    },
    // 只能选择一个
    select(selection, row) {
      // console.log(this.$refs.multipleTable)
      // console.log('---------------')
      // if (this.previousTableCom) {
      //     this.previousTableCom.clearSelection()
      // }
      // this.previousTableCom = this.$refs.multipleTable
      // console.log('当用户手动勾选数据行的 Checkbox 时触发的事件', selection, row)

      // 选择项大于1时

      if (selection.length > 1) {
        let del_row = selection.shift()

        // console.log('把数组的第一个元素从其中删除后', selection);

        this.$refs.multipleTable.toggleRowSelection(del_row, false) // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
      }
    },
    userIdchange(value) {
      this.userId = value
      // console.log(this.taskId)
      // console.log(this.userId)
    },
    // 关闭事件
    closeEliminateData() {
      // this.taskId = ''
      this.userArr = []
      this.userArr1 = []
      this.userRole = ''
      this.userMan = ''
      this.userId = ''
      this.taskname = ''
    },
    doTask(key, row) {
      if (row.taskAssignee != null && row.taskAssignee.length > 0) {
        //办理
        this.$router.push({
          path: row.taskFormUrl
        })
        return
      } else if (row.taskCandidate != null && row.taskCandidate.length > 0) {
      } else {
      }
    },

    doDistribution(row) {
      this.soDistributionVisible = true
      this.$nextTick(() => {
        this.$refs.soDistribution.init(row.key, row.id)
      })
    },

    async doView() {
      // this.userArr = []
      // this.userArr1 = []

      // this.userId = ''
      if (!(this.deleteList && this.deleteList.length > 0)) return this.$message.error('选择要发起的流程！')
      this.editFormVisible = true
      var obj = {
        url: this.$url.processinst.getUserTask,
        data: {
          procdefkey: this.deleteList[0].processDefinitionKey,
          taskdefkey: this.deleteList[0].taskDefinitionKey
        }
      }
      const { data: res } = await this.common.postRequest(obj)
      if (res.code !== 1) return this.$message.error(res.message)
      this.taskname = res.data[0].taskname
      let arrTemp = res.data[0].usergroup ? res.data[0].usergroup.split(',') : []
      if (arrTemp.length > 0) {
        arrTemp.forEach(id => {
          this.getuser_info(id)
        })
      }
    },
    async getuser_info(id) {
      var obj = {
        url: this.$url.roleManag.getById,
        data: {
          id
        }
      }
      const { data: res } = await this.common.postRequest(obj)
      this.userArr.push(res)
    },

    checkedChange(value) {
      console.log(value)
      if (value.length > 0) {
        this.taskId = value[0].taskId
        this.deleteList = value
      } else {
        this.deleteList = value
      }
    },
    // 选择角色事件
    async changeUser(value) {
      var obj = {
        url: this.$url.activeti.getUsersByRoleIds,
        data: {
          excludeMeWhenSelectNextHandler: this.common.excludeMeWhenSelectNextHandler,
          excludeFormerHanlder: this.common.excludeMeWhenSelectNextHandler,
          roleId: value + ''
        }
      }
      const { data: res } = await this.common.postRequest(obj)
      this.userArr1 = res
    }
  }
}
</script>
