<template>
  <el-dialog title="权限分配" width="90%" top="1%" v-if="visible" :visible.sync="visible"  append-to-body>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <el-button @click="loadSingleBpmn" type="primary">初始化</el-button>
          <el-table
            class="mb20"
            :data="tableData3"
            :header-cell-style="{background:'#e0f3ff',color:'#5f95b7'}"

            border
            stripe
            :highlight-current-row="true"
            style="width: 100%"
            @cell-click="cellClick"
          >

            <el-table-column align="center" prop="id" label="ID"></el-table-column>
            <el-table-column align="center" prop="procdefkey" label="流程定义key"></el-table-column>
            <el-table-column align="center" prop="procdefname" label="流程定义名称"></el-table-column>
             <el-table-column align="center" prop="taskdefkey" label="任务key"></el-table-column>
            <el-table-column align="center" prop="taskname" label="名称"></el-table-column>
            <el-table-column align="center" prop="usergroup" label="角色"></el-table-column>
            <el-table-column align="center" prop="candidateids" label="受理人"></el-table-column>

          </el-table>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <el-button @click="doSure" type="primary">确认分配</el-button>
          <div style="margin-top: 20px" v-if="comms">
            <el-radio-group v-model="taskType"  size="small">
              <el-radio label="1" border>固定受理人(唯一)</el-radio>
              <el-radio label="2" border>固定候选人(多个)</el-radio>
              <el-radio label="3" border>固定候选组（多个）</el-radio>
              <!-- <el-radio label="4" border>动态指定人</el-radio> -->
            </el-radio-group>
          </div>

          <el-form class="mt20" :model="model" v-if="taskType==1||taskType==2"  ref="form1" label-width="100px" >
        <el-row :gutter="20">
          <el-col :span="16" >
            <el-form-item  label="审核角色"   prop="data1"  >
              <el-select  v-model="model.data1" :multiple="taskType==2" @remove-tag ="removeTag"  placeholder="请选择..." @change="role">
              <el-option
                    v-for="item in tableData2"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item  label="审核人"  prop="nextDealMan">
              <el-select  v-model="model.nextDealMan"  :multiple="taskType==2"  placeholder="请选择...">
              <el-option
                    v-for="item in options2"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>


        </el-row>

      </el-form>
          <el-table
            v-if="taskType==4||taskType==3"
            class="mb20 mt20"
            :data="tableData2"
            height="500px"
            :header-cell-style="{background:'#e0f3ff',color:'#5f95b7'}"
            border
            stripe
            ref="roleTable"

            :highlight-current-row="true"
            style="width: 100%"
          >
            <el-table-column align="center" type="selection" width="55"></el-table-column>

            <el-table-column align="center" prop="code" label="角色ID"></el-table-column>
            <el-table-column align="center" prop="name" label="角色名称"></el-table-column>
            <!-- <el-table-column align="center" prop="org" label="所属部门"></el-table-column> -->
            <el-table-column align="center" prop="description" label="角色描述"></el-table-column>
            <el-table-column align="center" prop="locked" label="角色状态">
              <template slot-scope="scope">
                <el-tag type="success" v-show="!scope.row.locked">启用</el-tag>
                <el-tag type="danger" v-show="scope.row.locked">停用</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <!-- <el-button type="primary" @click="doAprove()">确认</el-button> -->
      <el-button @click="visible = false">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
// import moment from 'moment';
// //import util from '@/util'
export default {
  data() {
    return {
      selectIndex:null,
      comms:false,
      items: [],
      visible: false,
      pageTotal: 0,
      candidateids:"",
      gid:null,
      procdefkey: null,
      taskType:'4',
      processDefinitionId: null,
      usergroup:"",
      model:{
        data1:'',
        nextDealMan:[]
      },
      form: {
        name: "",
        pageNum: "1",
        pageSize: "9999"
      },
      tableData3: [

      ],
      tableData2: [],
      selectedRows: []
    };
  },
  created() {},
  watch:{
    taskType(value){
       var str = ''

      if(value==1){
        str = this.tableData2[0].id;
      }else if(value==2){
        str = [this.tableData2[0].id];
        this.model.nextDealMan = [];
      } else{
        return false;
      }

      this.model.data1 = str
      this.role(str)

    }
  },
  methods: {
    init(key, id) {
      this.visible = true;

      this.procdefkey = key;
      this.processDefinitionId = id;
      this.doSearch();
    },

    changeFun(){
        var arr = [];


        if(this.taskType==1){
          this.candidateids = this.model.nextDealMan;
        }else if(this.taskType==2){
          this.candidateids = this.model.nextDealMan.join(",");
        }else if(this.taskType==3){
          let val = this.$refs.roleTable.selection;
          val.forEach((element)=>{
              arr.push(element.id)
          })
          this.candidateids = this.usergroup = arr.join(",");
        }else if(this.taskType==4){
          let val = this.$refs.roleTable.selection;
          val.forEach((element)=>{
              arr.push(element.id)
          })
          this.candidateids = this.usergroup = arr.join(",");
        }
    },
    doSearch() {
      let self = this;
      var obj = {
        url: this.$url.processinst.getUserTaskList,
        data: {
          procdefkey: this.procdefkey
        }
      };
      this.common.httpPost(obj, success);
      function success(data) {
        console.log(data)
        if(data.data.length==0){
           self.loadSingleBpmn();
        }else{
          if(data.data[0].taskdefkey.indexOf("multiNext")!=-1){
            self.comms = true;
            self.taskType='3';
          }else{
            self.comms = false;
            self.taskType='4';
            self.tableData3 = data.data;
            self.gid = data.data[0].id;
            self.usergroup = data.data[0].usergroup
            self.doSearchRole(1);
          }
        }
      }
    },
    doSearchRole(value) {
      this.form.pageNum = value;

      let self = this;
      // var obj = {
      //   url: this.$url.roleManag.getList,
      //   data: this.form
      // };
      // this.common.httpPost(obj, success);
      // function success(data) {
      //   self.tableData2 = data.rows;
      //   if(self.taskType==2){
      //     self.model.data1 = [data.rows[0].id];
      //   }else{
      //     self.model.data1 = data.rows[0].id;
      //   }

      //   self.cheacked();
      // }
       this.$http({
          url: this.$url.roleManag.getList,
          method: "post",
          headers: {
              "Content-Type": "application/json",
          },
          data: this.form,
      }).then((res) => {
        console.log(res.data.data);
        self.tableData2 = res.data.data.rows;
        if(self.taskType==2){
          self.model.data1 = [res.data.data.rows[0].id];
        }else{
          self.model.data1 = res.data.data.rows[0].id;
        }

        self.cheacked();
      });
    },
    loadSingleBpmn() {
      let self = this;
      var obj = {
        url: this.$url.processinst.loadSingleBpmn,
        data: {
          processDefinitionId: this.processDefinitionId
        }
      };
      this.common.httpPost(obj, success);
      function success(data) {
        self.doSearch();
      }
    },
    doSure(){


      this.changeFun();

      let self = this;
      var oob = {
          id: this.gid,
          tasktype:this.taskType,

      }
      if(this.taskType==4){
        oob.usergroup=this.usergroup
      }else if(this.taskType==3){
        oob.candidateids=this.usergroup
      }else{
        oob.candidateids = this.candidateids
      }
      var obj = {
        url: this.$url.processinst.setPermission,

        data: oob
      };
      this.common.httpPost(obj, success);
      function success(data) {
         self.$message({
             message:"已分配",
             type:"success"
         })
         self.doSearch();
      }
    },
    cheacked(){

        let self = this;
        try {
          self.$refs.roleTable.clearSelection();

        } catch (error) {

        }
        if(!this.usergroup){
          return false;
        }
        let arr = this.usergroup.split(",");
        let arr1 = []
        this.tableData2.forEach((elment,index)=>{
          arr.forEach((i,o)=>{

            if(elment.id==i){
              arr1.push(index)
            }
          })

        })
        this.$nextTick(function () {

          // if(arr1.length==0){
          // }else{

            arr1.forEach((ob)=>{
              self.$refs.roleTable.toggleRowSelection(self.tableData2[ob],true);
            })
          // }
        })
    },
    cellClick(row){

      if(row.taskdefkey.indexOf("multiNext")!=-1){
        this.comms = true;
        if(row.taskType){

          this.taskType=row.tasktype;
        }else{
          this.taskType = '1';
        }
      }else{
         this.comms = false;
          this.taskType = '4';


      }

      this.usergroup = row.usergroup;
      this.gid = row.id;
      this.cheacked();
    },
    role(row){
      var str = ''

        if(typeof row =="object"){
          if(row.length==0){
            return false;
          }
          str = row.join(",");
        }else{
          if(!row){
            return false;
          }
          str = String(row)
        }

        let self = this;
        let obj = {
          roleId:str,
          excludeMeWhenSelectNextHandler:self.common.excludeMeWhenSelectNextHandler,
          excludeFormerHanlder:self.common.excludeMeWhenSelectNextHandler,
          procinstid:self.procinstid
        };
       this.common.selectInit(this.$url.activeti.getUsersByRoleIds,success,obj,'options2');
       function success(data,str){
         self.$nextTick(()=>{

            if( self.taskType==2){
              self.nextDeal(data[0].id);
            }else{

              self.model.nextDealMan = data[0].id;
            }
            self[str] = data;
         })

      }
    },
    nextDeal(id){

     if( typeof this.model.nextDealMan!="object"){
       this.model.nextDealMan = [];
     }
     if(this.model.nextDealMan.length>0){

       var tag = this.model.nextDealMan.find(i=>{
           return i == id;
         })
         if(!tag){
           this.model.nextDealMan.push(id);
         }
     }else{
       this.model.nextDealMan.push(id);
     }
    },
  }
};
</script>
<style >
 .mt20{
   margin-top: 20px;
 }
</style>
