<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"
        >
          <template v-slot="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  v-if="node.level < 5"
                  type="text"
                  :icon="ElIconCaretBottom"
                  size="small"
                  @click="() => append(data, node)"
                ></el-button>
              </span>
            </span>
          </template>
        </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>
import { CaretBottom as ElIconCaretBottom } from '@element-plus/icons'
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: [],
      // 是否预览
      isPreview: 1,
      ElIconCaretBottom,
    }
  },
  props: {
    projectId: {
      type: String | Number,
      default: '',
    },
    status4Flag: {
      type: String | Number,
      default: 0,
    },
  },
  created() {
    vm = this
    vm.initRange()
    vm.isPreview = vm.$route.query.isPreview ? vm.$route.query.isPreview : 0
  },
  methods: {
    //选择范围 初始化
    initRange() {
      console.log('====================initRange')
      let projectId = vm.projectId
      if (projectId == null) {
        //新建
      } else {
        //编辑
        vm.getAdministrative()
      }
    },
    //查询行政范围（树）
    getAdministrative() {
      console.log('=========================getAdministrative')
      let req = {
        projectId: vm.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
          vm.treeData = []
          if (vm.isPreview == 1) {
            vm.setDisable(administrativeAll)
          }
          vm.treeData[0] = administrativeAll
          console.log('================== administrativeAll==================')
          console.log(administrativeAll)
          console.log('====================================')
          vm.setTreeData(administrative)
          // vm.getCheckedTree();
        }
      })
    },
    //获取勾选树
    getCheckedTree() {
      console.log('=========================getCheckedTree')
      if (vm.idType != 2) {
        let allTree = JSON.parse(JSON.stringify(vm.treeData[0].children))
        let changedTags = JSON.parse(JSON.stringify(vm.tagsRegion))
        let organizationArea = operationData.treeHandler(allTree, changedTags)
        console.log('多级树：', organizationArea)
        vm.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);
      vm.$refs.tree.setCheckedKeys(treeIdList)
      vm.tagsRegion = checkList
    },
    // 选择行政范围
    onChecked(node, data) {
      console.log('=========================onChecked')
      vm.checkUpdate(node, data)
      //重构归并树
      let checkedTree = operationData.getSimpleCheckedNodes(vm.$refs.tree.store)
      let halfCheckedTree = vm.$refs.tree.getHalfCheckedKeys()
      let allSelectedKeys = operationData.setSelectedKeys(
        checkedTree,
        halfCheckedTree
      )
      //重构内容
      vm.allSelectedKeys = allSelectedKeys
      vm.initCheckList(allSelectedKeys)
      //console.log("allSelectedKeys", allSelectedKeys);
      //改变行政范围后，更新设定机构和设定人员
      // vm.updateOrganizationAndPerson(allSelectedKeys);
      vm.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
        // vm.$refs.tree.setChecked(data,false)
      }
    },
    //列举选中地区
    initCheckList(allSelectedKeys) {
      console.log('=========================initCheckList')
      vm.tagsRegion = []
      // console.log(allSelectedKeys);
      // console.log(vm.$refs.tree.getCheckedNodes());
      let nodeData = vm.$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
            vm.tagsRegion.push(tagObj)
          }
        }
      }
    },
    //添加子节点
    append(data, node) {
      console.log('=========================append')
      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
            vm.appendCheck(administrative, node.checked)
          }
        })
      }
    },
    //子节点选中
    appendCheck(administrative, checked) {
      console.log('====================appendCheck')
      //console.log(checked,administrative)
      let checkList = []
      checkList = vm.$refs.tree.getCheckedKeys()
      if (checked) {
        for (let i = 0; i < administrative.length; i++) {
          checkList.push(administrative[i].id)
          // console.log(checkList);
        }
      }
      vm.$nextTick(function () {
        vm.$refs.tree.setCheckedKeys(checkList)
      })
    },
    //删除label节点 同步树结构
    handleCloseTree(tag) {
      if (vm.status4Flag != 1 && vm.isPreview != 1) {
        vm.tagsRegion.splice(vm.tagsRegion.indexOf(tag), 1)
        vm.setCheckedKeys(vm.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)
      vm.$refs.tree.setCheckedKeys(treeKeyList)
    },
    //设定的行政范围内容(传给设定机构的范围)
    getScope(type) {
      let scope = ''
      for (let i = 0; i < vm.tagsRegion.length; i++) {
        scope += vm.tagsRegion[i].key
        if (i < vm.tagsRegion.length - 1) {
          scope += '|'
        }
      }
      if (scope == '') {
        return null
      }
      return scope
    },
    //设定的行政范围内容(完成或是暂存时传给后台的数据格式)
    setScope(type) {
      let noChangeTree = vm.getTreeCheck()
      let scope = ''
      if (vm.allSelectedKeys.length > 0) {
        for (let i = 0; i < vm.allSelectedKeys.length; i++) {
          scope += vm.allSelectedKeys[i].key + ':' + vm.allSelectedKeys[i].type
          if (i < vm.allSelectedKeys.length - 1) {
            scope += '|'
          }
        }
      } else {
        // let noChangeTree = vm.getTreeCheck();
        console.log('noChangeTree值', noChangeTree)
        if (noChangeTree.length > 0) {
          for (let i = 0; i < noChangeTree.length; i++) {
            scope += noChangeTree[i].key + ':' + noChangeTree[i].type
            if (i < noChangeTree.length - 1) {
              scope += '|'
            }
          }
        } else {
          //选全国项目
          if (vm.tagsRegion.length > 0 && vm.tagsRegion[0].key == '000') {
            scope = '000:1'
            console.log(vm.tagsRegion, 'scope', scope)
          }
        }
      }
      //console.log(scope);
      if (scope == '') {
        return null
      }
      return scope
    },
    getTreeCheck() {
      //重构归并树
      let checkedTree = operationData.getSimpleCheckedNodes(vm.$refs.tree.store)
      let halfCheckedTree = vm.$refs.tree.getHalfCheckedKeys()
      let allSelectedKeys = operationData.setSelectedKeys(
        checkedTree,
        halfCheckedTree
      )
      vm.allSelectedKeys = allSelectedKeys
      //重构内容
      return allSelectedKeys
    },
    // 预览时设置全部不可以选
    setDisable(r) {
      r.disabled = true
      if (r.children.length) {
        for (let i = 0; i < r.children.length; i++) {
          vm.setDisable(r.children[i])
        }
      }
    },
  },
}
</script>

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