<template>
  <div class="maincss" v-loading="loading">
    <div class="title-box">
      <div class="draw-title">
        {{ title }}
      </div>
      <div class="draw-title">
      </div>
      <el-form
        :model="formSubmit"
        ref="formSubmit"
        class="mt10"
        :rules="formrules"
        label-position="top"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="h28">办理步骤</div>
            <el-tree
              ref="myTree"
              :data="processList"
              :props="processProps"
              node-key="actDefName"
              @node-click="processNodeClick"
              style="border: 1px solid rgb(230, 235, 245); height: 314px;overflow: auto"
              highlight-current
            >
            </el-tree>
          </el-col>
          <el-col :span="8" v-show="processList && processList.length>0 &&nextData&&nextData.actDefType != 'endEvent'">
            <div class="h28">待选用户
<!--              <el-button type="primary" style="float: right" size="mini" @click="handleSelect">通讯录</el-button>-->
            </div>
            <div>
              <el-input
                v-model.trim="userTreeName"
                placeholder="请输入"
                clearable
                size="small"
                prefix-icon="el-icon-search"
              />
            </div>
            <el-tree
              ref="userTree"
              :data="userList"
              :props="userProps"
              :filter-node-method="filterNode"
              :highlight-current="true"
              :default-expand-all="true"
              @node-click="userNodeClick"
              style="border: 1px solid rgb(230, 235, 245); height: 282px;overflow: auto"
            >
            </el-tree>
          </el-col>
          <el-col :span="8" v-show="processList&&processList.length>0&&nextData&&nextData.actDefType != 'endEvent'">
            <div class="h28">已选用户</div>
            <div
              class="wordbox"
              style="border: 1px solid rgb(230, 235, 245); height: 314px;overflow: auto"
            >
              <ul>
                <li v-for="(item, index) in receiveUserList" :key="index">
                  <div class="inli">
                    <i class="el-icon-s-custom"></i>
                    <span>{{ item.name }}</span>
                    <i v-if="editStatus" class="el-icon-close" @click="removeData(item)"></i>
                  </div>
                </li>
              </ul>
            </div>
          </el-col>
          <el-col :span="24" class="mt10" v-if="istongguo">
            <el-form-item label="是否通过" prop="pass">
              <el-radio-group v-model.trim="pass">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item
              label="是否加入档案："
              prop="joinDoc"
              v-if="formSubmit.actDefId == 'EndEvent_0qwgu4i'"
            >
              <el-radio-group v-model.trim="formSubmit.joinDoc">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="isSummary" class="mt10">
            <el-form-item label="审核意见：">
              <el-input
                v-model.trim="formSubmit.summary"
                type="textarea"
                placeholder="请输入审核意见"
                maxlength="200"
                :autosize="{ minRows: 4, maxRows: 4 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  workflowNextactsNew2,
  getNextactuserByPending,
  getNextActUsersByNew,
  getExtAttributeModel,
  selectUserStyle
} from "@/api/my_business/workflow";

export default {
  props: {
    searchQuery:{
      type: Object,
      default: {},
    },
    hideNodeCode: {
      type: Array,
      default: ()=>[],
    },
    isSummary: {
      type: Boolean,
      default: true,
    },
    defaultStaff: {
      type: Object,
      default: undefined,
    },
    pListData: {},
    data: {},
    title: {},
    detatailsData: {},
    promptContent: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      summary: "",
      editStatus: true,
      formSubmit: { summary: "" },
      processList: [],
      processProps: {
        children: "children",
        label: "actDefName",
      },
      userProps: {
        children: "children",
        label: function (data, node) {
          if (data.type == "USER") {
            return data.id+' '+data.name
          } else {
             return data.name
          }
        }
      },
      formrules: {
        summary: [{ required: true, message: " ", trigger: "change" }],
        pass: [{ required: true, message: " ", trigger: "change" }],
      },
      userTreeName:undefined,
      receiveUserList: [],
      userList: [],
      loading: true,
      nextData: {},
      procDefKey: "",
      actionType: "",
      wf_actionType: "",
      actDefType: "", //actDefType: "endEvent" 判断流程到哪一步了
      pass: "", //是否通过
      kuozhanshuju: "",
      istongguo: false,
      morendta: undefined,
    };
  },
  created() {
    this.getOptionsList();
    if (this.pListData.procDefKey != "") {
      this.procDefKey = this.pListData.procDefKey;
    }
    //this.$emit("yingchanbohui", false);
  },
  watch: {
    actionType: function (val) {
      this.wf_actionType = val;
    },
    "formSubmit.summary": function (val) {
      this.summary = val;
      //console.log(val);
    },
    pass(val) {
      console.log(val);
    },
    // 根据名称筛选树
    userTreeName(val) {
      this.$refs.userTree.filter(val);
    }
  },
  mounted() {
  },
  methods: {
    getOptionsList() {
      let _this = this
      let searchQuery = this.searchQuery
      searchQuery.procDefId = _this.pListData.procDefId
      if (!!_this.pListData.curActInstId) {
        searchQuery.curActInstId= _this.pListData.curActInstId
        // 增加参数：当前环节定义ID【用于步骤已执行标记】
        searchQuery.curActDefId = _this.pListData.curActDefId
      }else{
        searchQuery.curActDefId= _this.pListData.actDefId
      }
       // 增加参数：流程实例ID【用于步骤已执行标记】
       searchQuery.procInstId = _this.pListData.procInstId
       _this.loading = true
      workflowNextactsNew2(searchQuery)
        .then((res) => {
          _this.processList = res.data.filter(item=>!_this.hideNodeCode.includes(item.actDefId));
          // 关闭遮罩
          _this.loading = false
          // 自动识别是否默认选中第一个步骤
          if(_this.processList.length > 0) {
              // 默认选中第一个步骤
              // 此方法内有打开遮罩和关闭遮罩
              _this.processNodeClick(_this.processList[0]);
              _this.actDefType = res.data[0].actDefType;
              _this.$nextTick(() => {
                // 步骤清单默认选中第一个步骤
                _this.$refs.myTree.setCurrentKey(_this.processList[0].actDefName);
              });
          }
        })
        .catch((e) => {
          _this.loading = false;
        });
    },
    processNodeClick(val){
      let _this = this
      if (!!_this.pListData.curActInstId) {
        _this.processNodeClick1(val);
      }else {
        _this.processNodeClick2(val);
      }
    },
    //流程节点点击触发 带出可选成员
    processNodeClick1(val) {
      let _this = this
      if (this.nextData != "") {
        if (val.actDefName == this.nextData.actDefName) {
          return;
        }
      }
      this.nextData = val;
      this.userList = []; //代选
      this.receiveUserList = []; //已选
      let params = {
        userOrgId: _this.userInfo.deptId,
        curActInstId: this.pListData.curActInstId,
        destActDefId: val.actDefId,
        // 当前环节ID、流程定义ID、流程实例ID
        curActDefId: this.pListData.curActDefId,
        procDefKey: this.pListData.procDefKey,
        procInstId: this.pListData.procInstId,
      };
      _this.loading = true
      getNextactuserByPending(params)
        .then((res) => {
          // 获取流程待选人员展示方式
          _this.loading = true
          selectUserStyle(params).then((selectRes) => {
            if(selectRes.data == 'tree') {
              // 树形结构展示
              _this.userList = this.handleTree(res.data, "id");
            } else {
              // 平铺结构展示
              _this.userList = res.data.filter(item => item.type==='USER')
              if (_this.defaultStaff&&_this.defaultStaff.length>0) {
                let item=_this.defaultStaff.find(item=>item.nodeCode===val.actDefId)
                if (item&&item.users) {
                  JSON.parse(item.users).forEach(item=>{
                    let user = _this.userList.find(user=>user.id===item.userName)
                    if (!user) {
                      _this.userList.push({
                        type: 'USER',
                        id:item.userName,
                        realId: item.userName,
                        parentId: item.deptId,
                        name: item.nickName,
                      })
                    }
                  })
                }
              }
            }
            let defaultStaffIds = []
            if (_this.defaultStaff&&_this.defaultStaff.length>0) {
              //设定了流程默认执行人
              let item=_this.defaultStaff.find(item=>item.nodeCode===val.actDefId)
              if (item&&item.users) {
                defaultStaffIds = JSON.parse(item.users).map(user=>user.userName)
              }
            }
            if (defaultStaffIds.length>0) {
              let userList = []
              _this.defaultUserList(userList,defaultStaffIds,_this.userList)
              userList.forEach(user=>{
                _this.userNodeClick(user);
              })
              _this.editStatus = true
            } else {
              _this.editStatus = true
              //如果待选人员里就一个人，自动加入到已选人员名单里z
              this.rtuserList(res.data);
              if (this.morendta) {
                this.userNodeClick(this.morendta);
              }
            }
            // 关闭遮挡
            _this.loading = false;
          });
        })
        .catch((e) => {
          console.log(e)
          _this.loading = false;
        });
    },
    processNodeClick2(val) {
      let _this = this
      if (this.nextData != "") {
        if (val.actDefName == this.nextData.actDefName) {
          return;
        }
      }
      this.nextData = val;
      this.userList = []; //代选
      this.receiveUserList = []; //已选
      let params = {
        procDefId:this.pListData.procDefId,
        userOrgId: this.userInfo.deptId,
        curActDefId: this.pListData.actDefId,
        destActDefId: val.actDefId,
      };
      _this.loading = true
      getNextActUsersByNew(params).then((res) => {
        // 获取流程待选人员展示方式
        selectUserStyle(params).then((selectRes) => {
          if(selectRes.data == 'tree') {
            // 树形结构展示
            _this.userList = this.handleTree(res.data, "id");
          } else {
            // 平铺结构展示
            _this.userList = res.data.filter(item => item.type==='USER')
            if (_this.defaultStaff&&_this.defaultStaff.length>0) {
              let item=_this.defaultStaff.find(item=>item.nodeCode===val.actDefId)
              if (item&&item.users) {
                JSON.parse(item.users).forEach(item=>{
                  let user = _this.userList.find(user=>user.id===item.userName)
                  if (!user) {
                    _this.userList.push({
                      type: 'USER',
                      id:item.userName,
                      realId: item.userName,
                      parentId: item.deptId,
                      name: item.nickName,
                    })
                  }
                })
              }
            }
          }

          let defaultStaffIds = []
          if (_this.defaultStaff) {
            //设定了流程默认执行人
            let item=_this.defaultStaff.find(item=>item.nodeCode===val.actDefId)
            if (item&&item.users) {
              defaultStaffIds = JSON.parse(item.users).map(user=>user.userName)
            }
          }
          if (defaultStaffIds.length>0) {
            let userList = []
            _this.defaultUserList(userList,defaultStaffIds,_this.userList)
            userList.forEach(user=>{
              this.userNodeClick(user);
            })
            _this.editStatus = false
          } else {
            _this.editStatus = true
            //如果待选人员里就一个人，就自己加入到已选人员名单里z
            this.rtuserList(res.data);
            if (this.morendta) {
              this.userNodeClick(this.morendta);
            }
          }
          _this.loading = false
        });

      })
        .catch((e) => {
          this.loading = false;
        });
    },
    //点击成员 导入可选成员
    userNodeClick(val) {
      // console.log("val", val);
      if (val.type == "USER"&&this.editStatus) {
        if (this.nextData.multi){
          // 多人处理环节
          let arr = this.receiveUserList.filter((x) => x.id === val.id);
          if (arr.length <= 0) {
            this.receiveUserList.push(val);
          }
        }else {
          // 单人处理环节
          this.receiveUserList = [val]
        }
      }
    },
    //移除成员
    removeData(item) {
      var arr = [];
      this.receiveUserList.forEach((element) => {
        if (element.id != item.id) {
          arr.push(element);
        }
      });
      this.receiveUserList = arr;
    },
    defaultUserList(userList,ids,data) {
      data.forEach(item=>{
        if (ids.includes(item.id)) {
          userList.push(item)
        }
      })
    },
    rtuserList(originalData) {
      let userList = originalData.filter(item => item.type==='USER')
      if (userList.length == 1) {
          // 若是用户节点直接设置成为已选用户
          this.morendta = userList[0];
      } else {
        this.morendta = undefined
      }
    },
    // 从组织用户结构树中寻找叶子节点，不需要的
    filterUserNode(data) {
      if(data.type == "USER") {
        // 若是用户节点就返回
        return data
      } else if(data.hasOwnProperty("children")) {
        let list = data.children;
        for(var i=0;i<list.length;i++) {
          let item = list[i];
          if(item.type != "USER") {
           let res = this.filterUserNode(item)
           if(res != null) {
             // 返回出方法
             return res;
           }
          } else {
            // 若是用户节点就返回
            return item;
          }
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.id.toLowerCase().indexOf(value.toLowerCase()) !== -1||data.name.toLowerCase().indexOf(value.toLowerCase()) !== -1
    },
    handleSelect() {
      let _this = this
      _this.$nextTick(()=>{
        _this.$refs.userList.init(null,null,null)
      })
    },
    handleSubmitUser(source,index,user) {
      let val = {
        type: 'USER',
        id: user.userName,
        name: user.nickName,
        parentId: user.dept.deptId,
        realId: user.userName,
      }
      this.userNodeClick(val);
    },
  },
};
</script>
<style scoped>
 .h28{
   height: 28px;line-height: 28px
 }
</style>
