<!---选择行政范围-->
<template>
  <div class="select-region-wrap">
    <el-row :gutter="20">
      <el-col class="rim" :span="12">
        <el-tree
          default-expand-all
          :data="treeData"
          show-checkbox
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps"
          @check="onChecked"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                v-if="node.level < 5"
                type="text"
                icon="el-icon-caret-bottom"
                size="small"
                @click="() => append(data,node)"
              ></el-button>
            </span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="11">
        <p class="area-p">
          项目范围包含下列区域所有机构和人员({{ tagsRegion.length }})
        </p>
        <el-tag
          v-for="tag in tagsRegion"
          :key="tag.name"
          closable
          :type="tag.type"
          @close="handleCloseTree(tag)"
        >{{tag.name}}</el-tag>
      </el-col>
    </el-row>
  </div>
</template>

<script>
let vm = null;
import BreadCrumb from "../../../components/breadcrumb.vue";
import { doUpload, getFilePath } from "../../../utils/qiniu-util";
import { mapGetters } from "vuex";
import { openLoading, closeLoading } from "../../../utils/utils";
import * as commonUtil from "../../../utils/utils";
import * as operationData from "../../../utils/operation";
import { getExeclUrl } from "@/utils/index";
import {
  uploadOrgExcel,
  uploadPersonExcel
} from "@/utils/education/educationApi";
import Sortable from "sortablejs";
export default {
  data() {
    return {
      scopeReq: {},     // 区域范围
      allSelectedKeys: [],
      updatedTree: false,
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf"
      },
      treeData: [],
      tagsRegion: [],
      projectId: 640
    }
  },
  created() {
    vm = this;
    this.initRange();
  },
  methods: {
     //选择范围 初始化
    initRange() {
      console.log('====================initRange')
      let projectId = this.projectId;
      if (projectId == null) {
        //新建
      } else {
        //编辑
        this.getAdministrative();
      }
    },
      //查询行政范围（树）
    getAdministrative() {
      console.log('=========================getAdministrative')
      let req = {
        projectId: this.projectId
      };
      openLoading(vm);
      vm.GET("portal/scope/v1/administrative", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          //console.log(res.data);
          let administrativeAll = res.data.administrativeAll;
          let administrative = res.data.administrative;
          this.treeData = [];
          this.treeData[0] = administrativeAll;
          this.setTreeData(administrative);
          this.getCheckedTree();
        }
      });
    },
    //获取勾选树
    getCheckedTree() {
      console.log('=========================getCheckedTree')
      if (this.idType != 2) {
        let allTree = JSON.parse(JSON.stringify(this.treeData[0].children));
        let changedTags = JSON.parse(JSON.stringify(this.tagsRegion));
        let organizationArea = operationData.treeHandler(allTree, changedTags);
        console.log("多级树：", organizationArea);
        this.organizationRegion = organizationArea;
      }
    },
    //初始化范围树
    setTreeData(administrative) {
      console.log('=========================setTreeData')
      let treeIdList = [];
      let checkList = [];
      for (let i = 0; i < administrative.length; i++) {
        treeIdList.push(administrative[i].id);
        checkList[i] = {};
        checkList[i].name = administrative[i].label;
        checkList[i].key = administrative[i].id;
      }
      //console.log(treeIdList);
      this.$refs.tree.setCheckedKeys(treeIdList);
      this.tagsRegion = checkList;
    },
    // 选择行政范围
    onChecked(node, data) {
      console.log('=========================onChecked')
      vm.checkUpdate(node, data);
      //重构归并树
      let checkedTree = operationData.getSimpleCheckedNodes(
        this.$refs.tree.store
      );
      let halfCheckedTree = this.$refs.tree.getHalfCheckedKeys();
      let allSelectedKeys = operationData.setSelectedKeys(
        checkedTree,
        halfCheckedTree
      );
      //重构内容

      this.allSelectedKeys = allSelectedKeys;
      this.initCheckList(allSelectedKeys);
      //console.log("allSelectedKeys", allSelectedKeys);
      //改变行政范围后，更新设定机构和设定人员
      this.updateOrganizationAndPerson(allSelectedKeys);
      this.updatedTree = true;
    },
     //v2.2教培更新
    checkUpdate(node, data) {
       console.log('=========================checkUpdate')
      let flag = -1;
      flag = data.checkedKeys.indexOf(node.id);
      if (vm.status4Flag == 1 && flag >= 0) {
        console.log(node, data, flag, vm.status4Flag);
        vm.nowCheck = node;
        vm.warnType = 0;
        vm.dialogWarn = true;
        // this.$refs.tree.setChecked(data,false)
      }
    },
    //列举选中地区
    initCheckList(allSelectedKeys) {
      console.log('=========================initCheckList')
      this.tagsRegion = [];
      // console.log(allSelectedKeys);
      // console.log(this.$refs.tree.getCheckedNodes());
      let nodeData = this.$refs.tree.getCheckedNodes();
      for (let i = 0; i < nodeData.length; i++) {
        for (let j = 0; j < allSelectedKeys.length; j++) {
          if (
            allSelectedKeys[j].type == 1 &&
            nodeData[i].id == allSelectedKeys[j].key
          ) {
            let tagObj = {};
            tagObj.name = nodeData[i].label;
            tagObj.key = nodeData[i].id;
            this.tagsRegion.push(tagObj);
          }
        }
      }
    },
    //行政范围改变更新设定机构
    updateOrganizationAndPerson(allSelectedKeys) {
      console.log('=========================updateOrganizationAndPerson')
      this.tableOrganization = [];
      this.tablePerson = [];
      this.lookedOrganization = [];
      this.changedOrganization = [];
      this.changedOrganization2 = [];
    },
    getCheckedKeys() {
      console.log('=========================getCheckedKeys')
      console.log(this.$refs.tree.getCheckedKeys());
    },
     //添加子节点
    append(data, node) {
      console.log('=========================append')
      console.log("data:", data);
      console.log("node:", node);
      if (data.children.length == 0) {
        //let id = data.id + "add";
        let statusValue = 0;
        if (node.checked == true) {
          statusValue = 1;
        }
        let req = {
          id: data.id,
          status: statusValue,
          disabled: data.disabled
        };
        vm.GET("portal/scope/v1/administrative/children", req).then(res => {
          if (res.code == "000000") {
            let administrative = res.data.administrative;
            //console.log(administrative);
            data.children = administrative;
            this.appendCheck(administrative, node.checked);
          }
        });
      }
    },
     //子节点选中
    appendCheck(administrative, checked) {
       console.log('====================appendCheck')
      //console.log(checked,administrative)
      let checkList = [];
      checkList = this.$refs.tree.getCheckedKeys();
      if (checked) {
        for (let i = 0; i < administrative.length; i++) {
          checkList.push(administrative[i].id);
          // console.log(checkList);
        }
      }
      this.$nextTick(function() {
        this.$refs.tree.setCheckedKeys(checkList);
      });
    },
     //删除label节点 同步树结构
    handleCloseTree(tag) {
      console.log('=========================handleCloseTree')
      if (this.status4Flag != 1) {
        this.tagsRegion.splice(this.tagsRegion.indexOf(tag), 1);
        this.setCheckedKeys(this.tagsRegion);
      }
    },
     //通过key设置tree
    setCheckedKeys(tagsRegion) {
       console.log('=========================setCheckedKeys')
      console.log(tagsRegion);
      let treeKeyList = [];
      for (let index = 0; index < tagsRegion.length; index++) {
        treeKeyList[index] = tagsRegion[index].key;
      }
      console.log(treeKeyList);
      this.$refs.tree.setCheckedKeys(treeKeyList);
    }
  }
}
</script>

<style lang="scss" >
 .select-region-wrap {
    .rim {
      border: 1px solid #ddd;
    }
    
  }
</style>
