<template>
  <div class="box">
     <div class="leftTree" ref="leftTree">
        <!-- <div class="drag-handle"></div> -->
        <el-row>
          <el-input
            placeholder="请输入内容"
            class="search_component remove-margin-b"
            size="mini"
            v-model="keyWords"
            @keyup.13.native="filterTree"
          >
            <i
              class="el-icon-search el-input__icon"
              slot="suffix"
              @click="filterTree">
            </i>
          </el-input>
        </el-row>
        <!-- <el-scrollbar class="left_tree_wrapper margin-t20"> -->
        <div class="left_tree_wrapper margin-t10">
          <el-tree
            ref="tree"
            class="filter-tree"
            :props="props"
            :load="loadNode"
            node-key="id"
            lazy
            v-show="!controlTree"
            :default-expanded-keys="grandParentId"
            :expand-on-click-node="false"
          >
            <div slot-scope="{ node, data }" class="custom-tree-node">
              <!-- <span :class="data.pid ? 'process_02' : 'process_01'" /> -->
              <!-- <p class="grow" :title="node.label">{{ node.label }}</p> -->
              <p
                :class="{
                  green: data.release === 'Y',
                  red: data.spstate === '1'
                }"
                @click="nodeClick(node, data)"
                :title="node.label"
              >
                {{
                  node.label +
                    "(" +
                    data.childrenReleaseCount +
                    "/" +
                    data.childrenCount +
                    ")"
                }}
              </p>
              <p class="font14 opertionBtn">
                <i
                  v-if="data.adder == '1' && node.level < 7"
                  class="el-icon-circle-plus-outline add"
                  @click="handlerTreeOperate('add', data, node)"
                />
                <i
                  v-if="
                    data.id != '79957553BD2F3978E053BF1A13ACD486' &&
                      data.updater == '1'
                  "
                  class="el-icon-edit add"
                  @click="handlerTreeOperate('edit', data, node)"
                />
                <i
                  v-if="
                    data.id != '79957553BD2F3978E053BF1A13ACD486' &&
                      data.deleter == '1'
                  "
                  class="el-icon-delete add"
                  @click="handlerTreeOperate('del', data, node)"
                />
              </p>
            </div>
          </el-tree>
          <el-tree
            class="filter-tree"
            ref="treeFilter"
            node-key="id"
            :props="props"
            :data="treelist"
            v-show="controlTree"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <!--<span :class="data.pid ? 'process_02' : 'process_01'"></span>-->
              <p
                :class="{ green: data.release === 'Y' }"
                @click="nodeClick(node, data)"
                :title="node.label"
                style="font-size: 13px"
              >
                {{
                  node.label +
                  "(" +
                  data.childrenReleaseCount +
                  "/" +
                  data.childrenCount +
                  ")"
                }}
              </p>
              <p class="font14 opertionBtn">
                <i
                  v-if="data.adder == '1' && node.level < 7"
                  class="el-icon-circle-plus-outline add"
                  @click="handlerTreeOperate('add', data, node)"
                />
                <i
                  v-if="
                    data.id != '79957553BD2F3978E053BF1A13ACD486' &&
                      data.updater == '1'
                  "
                  class="el-icon-edit add"
                  @click="handlerTreeOperate('edit', data, node)"
                />
                <i
                  v-if="
                    data.id != '79957553BD2F3978E053BF1A13ACD486' &&
                      data.deleter == '1'
                  "
                  class="el-icon-delete add"
                  @click="handlerTreeOperate('del', data, node)"
                />
              </p>
            </div>
          </el-tree>
        </div>
        <!-- </el-scrollbar> -->
      </div>
    <!-- <el-dialog
      v-if="isDialogsVisible"
      :title="playBoxType === 'add' ? '添加企业流程框架' : '编辑企业流程框架'"
      :visible.sync="isDialogsVisible"
      width="40%"
    >
      <el-form
        ref="editRef"
        label-width="120px"
        label-position="right"
        :model="processForm"
        :rules="rules"
      >
        <el-form-item label="流程框架名称" prop="name">
          <el-input v-model="processForm.name" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogsVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlerConfirm">确 定</el-button>
      </span>
    </el-dialog> -->
    <add-process-dialog v-model="isDialogsVisible"
      :processForm=processForm
      :treeTempId=treeTempId
      :type=playBoxType
      @confirm=confirmUpdate>
    </add-process-dialog>
  </div>
</template>

<script>
import {
  getProcessIframeTree,
  searchProcessIframeTree,
  getProcessTreeNodeCode,
  getProcessTreedelete,
  getProcessIframeTreeVersion,
  getProcessTreeofprincipal
} from '../../api/processTree'
import {
  getProcesslist,
  processSaveAttr,
  queryProcessDesignListInfo
} from '../../api/processDesignCenter'
import {
  isSameData
  } from '../../utils/utils'
import processTabMenu from '../processTabMenu/index.vue'
import addProcessDialog from './components/addProcessDialog.vue'
export default {
  components: {
    processTabMenu,
    addProcessDialog
  },
  data() {
    console.log("this", this);
    return {
      keyWords: '',
      controlTree: false,
      props: {
        label: "name",
        isLeaf: function (data, node) {
          if (data.isparent === true) {
            return false;
          } else {
            return true;
          }
        },
      },
      grandParentId: [],
      treelist: [],
      defaultSelected: true,
      modelid: '',
      nodeData: {},
      treeData: {},
      processObj: {},
      setIntervalSave: null,
      processTabMenu: [],
      proInfo: {},
      datarank: "",
      playBoxType: "",
      // 暂存将要添加的组织树
      treeTempId: "",
      processForm: {
        name: '',
        typeid: '2',
        systematic: 'function',
        displaymode: 'treeShape'
      },
      isDialogsVisible: false
    };
  },
  computed: {
    userid() {
      return JSON.parse(localStorage.getItem("portalCurrentUserInfo") || "{}")
        .empuid;
    },
    username() {
      return JSON.parse(localStorage.getItem("portalCurrentUserInfo") || "{}")
        .cnname;
    },
  },
  mounted() {},

  methods:{
     loadNode(node, resolve) {
      let _this = this;
      let id = node.data ? node.data.id : "0";
      getProcessIframeTree(id).then((res) => {
        if (!res) return false;
        if (id === "0") {
          this.grandParentId.push(res[0].id);
        }
        resolve(res);
      });
    },
    filterTree() {
      if (!this.keyWords) {
        this.controlTree = false;
        return false;
      }
      searchProcessIframeTree({
        name: this.keyWords,
      }).then((res) => {
        if (!res) return false;
        this.controlTree = true;
        this.treelist = res;
      });
    },
    nodeClick(node, data) {

      let chartJson = window.chartJson()
      if (isSameData(chartJson, JSON.parse(sessionStorage.getItem('chartJson')))) {
          this.getTreeData(node, data)
      } else {
        this.$confirm('当前流程还未保存，是否确定打开?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.getTreeData(node, data)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }

    },
    getTreeData (node, data) {
      this.nodeData = node;
      this.treeData = data;
      let self = this;
      // self.modelid = data.id
      this.defaultSelected = false;
      self.getList();
    },
    getList() {
      let self = this;
      self.versionList = [];
      (self.imgsShow = false),
        queryProcessDesignListInfo(self.treeData.id, {
          fullFilters: [
            {
              filters: [
                {
                  key: "code",
                  opt: "LIKE",
                  type: "S",
                  value: self.keyWords,
                  logic: "or",
                },
                {
                  key: "name",
                  opt: "LIKE",
                  type: "S",
                  value: self.keyWords,
                  logic: "or",
                },
              ],
              logic: "and",
            },
          ],
          logic: "and",
          pageNum: 1,
          pageSize: 10,
          sort: "desc"
        // getProcesslist({
        //   filters: [{ key: "modelid", value: self.modelid }],
        //   orderby: "createon",
        //   pageNum: 1,
        //   pageSize: 10,
        //   sort: "desc",
        }).then((res) => {
          this.processObj = {};
          if (!res || res.list.length === 0) return false;
          let item = res.list[0]
          this.treeData = item;
          this.modelid = item.modelid
          if (item.state === "2") {
            processSaveAttr({
              // id: item.bpmid,
              bpo: item.bpo,
              bponame: item.bponame,
              code: item.code,
              listid: item.id,
              modelid: item.id,
              signer: this.userid,
              signername: this.username,
              version: item.version,
              name: item.name,
              modelInstitution: {},
            }).then((rt) => {
              if (!rt) return false;
              this.processObj = res.list[0];
              this.processObj.state = '5';
              this.processObj.item.state = '5';
              this.processObj.bpmid = rt.split(",")[0]
            });
          } else {
            this.processObj = res.list[0];
          }
        });
    },
    handlerTreeOperate(type, datas, node) {
      let data = JSON.parse(JSON.stringify(datas))
      console.log(type, data, node)
      this.datarank = data.rank;
      this.playBoxType = type;
      const me = this;
      if (data.spstate === "1" && data.operation === "insert") {
        this.$message({
          message: "该流程新增审批中，暂不可操作！",
          type: "warning"
        });
        return false;
      }
      if (data.spstate === "1" && data.operation === "update") {
        this.$message({
          message: "该流程修改审批中，暂不可操作！",
          type: "warning"
        });
        return false;
      }
      if (data.spstate === "1") {
        this.$message({
          message: "该流程正在审批中，暂不可操作！",
          type: "warning"
        });
        return false;
      }
      if (type === "add") {
        this.treeTempId = data.id;
        this.processForm.pid = data.id;
        this.processForm.status = data.state;
        this.processForm.parentname = data.name;
        this.processForm.rank = node.level + 1;
        getProcessTreeNodeCode(data.id).then(res => {
          if (!res) return
          this.isDialogsVisible = true;
          this.processForm.name = "";
          this.processForm.ename = "";
          this.processForm.code = res.code;
          this.processForm.rank = node.level + 1;
          if (res.code.substr(2, 1) || res.code.substr(3, 1) == 0) {
            this.processForm.rank = 2;
          }
          if (data.id == "79957553BD2F3978E053BF1A13ACD486") {
            this.processForm.businessLayer = true;
            this.processForm.code = "";
          } else {
            this.processForm.businessLayer = false;
          }
        });
      } else if (type === "edit") {
        this.treeTempId = node.parent.data.id;
        // this.processForm = data
        // this.processForm.rank = node.level;

        // this.processForm.id = data.id;
        // this.processForm.ename = data.ename;
        // this.processForm.processcode = data.processcode;
        // this.processForm.rank = node.level;
        // this.processForm.name = data.name;
        // this.processForm.code = data.code;
        // this.processForm.ename = data.ename;
        // this.processForm.processcode = data.processcode;
        // this.processForm.typeid = data.typeid;
        // this.processForm.processoptions = data.processoptions;
        // this.processForm.ruleperson = "";
        // this.processForm.consultmanager = "";
        // this.processForm.rulecode = data.rulecode;
        // this.processForm.rulename = data.rulename;
        // this.processForm.systematic = data.systematic;
        // this.processForm.displaymode = data.displaymode;

        getProcessTreeofprincipal(data.id).then(res => {
          this.isDialogsVisible = true;
          this.processForm = res
          this.processForm.parentname = res.pname
          // 上一次保存数据
          // let jsondata = {};
          // if (res.operation === "insert" || res.operation === "updata") {
          //   jsondata = JSON.parse(res.jsontext);
          // } else {
          //   jsondata = res;
          // }
          // this.processForm.ename = jsondata.ename;
          // this.processForm.name = jsondata.name;
          // this.processForm.managerList = jsondata.managerList;
          // this.processForm.processcode = jsondata.processcode;
          // this.processForm.systematic = jsondata.systematic;
          // this.processForm.displaymode = jsondata.displaymode;
          // this.processForm.rulecode = jsondata.rulecode;
          // this.processForm.rulename = jsondata.rulename;
          // this.processForm.systematic = jsondata.systematic;
          // this.processForm.displaymode = jsondata.displaymode;
          // this.processForm.spstate = jsondata.spstate;
          // this.processForm.spinstid = jsondata.spinstid;
          // const list = jsondata.managerList;
          // const temp = [];
          // for (let i = 0; i < list.length; i++) {
          //   temp.push(list[i].value);
          //   this.selectedID.push({
          //     ID: parseInt(list[i].empuid),
          //     name: list[i].value,
          //     person: {
          //       cnname: list[i].cnname,
          //       empid: list[i].userid
          //     }
          //   });
          // }
          // this.processForm.person = temp.toString(",");
          // this.processForm.rulemanagerList = jsondata.rulemanagerList || [];
          // this.processForm.consultmanagerList = jsondata.consultmanagerList || [];
          // this.processForm.managerList = jsondata.managerList || [];
          // const list2 = this.editForm.rulemanagerList;
          // const temp2 = [];
          // for (let i = 0; i < list2.length; i++) {
          //   temp2.push(list2[i].value);
          //   this.selectedID2.push({
          //     ID: parseInt(list2[i].empuid),
          //     NAME: list2[i].value
          //   });
          // }
          // this.processForm.ruleperson = temp2.toString(",");
          // const list3 = this.processForm.consultmanagerList;
          // const temp3 = [];
          // for (let i = 0; i < list3.length; i++) {
          //   temp3.push(list3[i].value);
          // }
          // this.ruleperson.consultmanager = temp3.toString(",");
        });
      } else {
        const parentId = node.parent.data.id;
        this.$confirm('您确定要删除吗?', '提示', {
          confirmBtnText: '确 定',
          cancelBtnText: '取 消',
          type: "warning"
        }).then(() => {
          const id = data.id;
          getProcessTreedelete(id).then(res => {
            if (res) {
              this.$message({
                type: "success",
                message: res
              });
              const node = this.$refs.tree.getNode(parentId); // 通过节点id找到对应树节点对象
              node.loaded = false;
              node.expand();
            }
          });
        });
      }
    },
    confirmUpdate(data) {
      console.log('treeTempId')
      const node = this.$refs.tree.getNode(this.treeTempId); // 通过节点id找到对应树节点对象
      node.loaded = false;
      node.expand();
    }
  },
  watch: {
    processObj: {
      handler(val) {
        // let query = this.$router.history.current.query
        // let path = this.$router.history.current.path
        val.rank = this.nodeData.level + 1
        console.log(val, this.nodeData)
        if (!!val.id) {
          // location.href = `./BaseNewPage.html?id=${val.id}&listid=${val.listid}&treeId=${this.modelid}&processName=${val.name
          // }&username=0000419&processNum=${val.code}&state=${val.state}&isRead=no`;
          // location.href = location.origin+location.pathname + `?id=${val.bpmid}&listid=${val.id}&treeId=${this.modelid}&processName=${val.name
          // }&username=0000419&processNum=${val.code}&state=${val.state}&isRead=no`
          this.processTabMenu = JSON.parse(sessionStorage.getItem('processTabMenu')) || []
          let obj = {
              id: val.bpmid,
              listid: val.id,
              treeId: this.modelid,
              processName: val.name,
              username: '',
              processNum: val.code,
              state: val.state,
              isRead: 'no',
              version: val.version,
              item: val,
              treeData: this.treeData
            }
            console.log(this.processTabMenu, 'processTabMenu')
          if (this.processTabMenu) {
            let tabMenus = this.processTabMenu.map(item => item.listid).join(',')
            if (tabMenus.indexOf(val.id) === -1) {
              this.processTabMenu.push(obj)
            } else {
              this.processTabMenu.forEach(item => {
                    if (item.listid === obj.listid) {
                      item = obj
                    }
                })
            }
            sessionStorage.setItem('processTabMenu', JSON.stringify(this.processTabMenu))
            sessionStorage.setItem('processInfo', JSON.stringify(obj))
            this.proInfo = obj
            // setTimeout(function () {
            // window.getTabMenu(processTabMenu, obj)
            window.getProcessJson('Update')
            // }, 1000)
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },

};
</script>
<style lang='scss' scoped>
.box {
  .margin-t10 {
    margin-top: 10px
  }
  /deep/.leftTree {
    .el-row {
      padding: 2px 6px;
    }
    .el-input__icon {
      cursor: pointer;
      line-height: 34px;
    }
    .left_tree_wrapper {
      height: calc(100vh - 190px);
      overflow: auto;
      .el-tree-node__children {
        overflow: visible;
      }
      /deep/
      .el-tree-node.is-current
      > .el-tree-node__content
      .custom-tree-node
      .green {
        color: #2d42af;
      }
      /deep/ .el-tree-node.is-current > .el-tree-node__content .custom-tree-node {
        color: #2d42af;
      }
      /deep/ .custom-tree-node {
        color: #666;
        padding-right: 60px!important;
      }
    }
    .opertionBtn {
      margin-left: 15px;
    }
  }
}
 /*滚动条样式*/
        .left_tree_wrapper::-webkit-scrollbar {
             width: 4px;     /*高宽分别对应横竖滚动条的尺寸*/

        height: 8px;
        }
        .left_tree_wrapper::-webkit-scrollbar-thumb {
            border-radius: 10px;
            -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
            background: rgba(0,0,0,0.2);
        }
        .left_tree_wrapper::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
            border-radius: 0;
            background: rgba(0,0,0,0.1);
        }

  // 自定义树dom节点
  .custom-tree-node {
    color: #2d42af ;
    padding-right: 60px!important;
    .process_01 {
      display: inline-block;
      width: 16px;
      height: 14px;
      margin-right: 5px;
      vertical-align: middle;
      background-image: url('../../../img/process/process_01.png');
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }
    .process_02 {
      display: inline-block;
      width: 16px;
      height: 14px;
      margin-right: 5px;
      vertical-align: middle;
      background-image: url('../../..//img/process/process_02.png');
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }
    .text {
      display: inline-block;
      vertical-align: middle;
    }
    &:after {
      content: '';
      display: inline-block;
      height: 100%;
      vertical-align: middle;
    }
  }
  /deep/.el-tree {
      .el-tree-node {
        .el-tree-node__content {
          line-height: 26px;
          .custom-tree-node{
            height: 100%;
            position: relative;
            display: flex;
            .opertionBtn {
              // position: absolute;
              // right: 10px;
              // top: 0;
              // bottom: 0;
              // min-width: 50px;
              display: flex;
              display: none;
              justify-content: space-between;
              align-items: center;
              i {
                display: inline-block;
                height: 14px;
                // line-height: 26px;
                padding: 0;
                margin: 0;
                &:hover {
                  background: none;
                  font-weight: bold;
                }
              }
            }
          }
          &:hover {
            .opertionBtn{
              display: block;
            }
          }
        }
      }
    }
</style>
