<template>
  <div class="organization">
      <el-row :gutter="20">
        <el-col class="rim" :span="12">
          <el-tree
            default-expand-all
            :data="treeData"
            show-checkbox
            node-key="regionId"
            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-row>
      <div style="margin-top: 60px;margin-left: 250px;">
      <el-button type="primary" size="small" @click="save">保存</el-button>
    </div>

  </div>
</template>

<script>
import { openLoading, closeLoading } from "@/utils/utils";
import { doUpload, getFilePath } from "@/utils/qiniu-util";
import * as operationData from "@/utils/operation";
import { moRelSearch, morDeleteOrg } from '@/utils/yqrange/memberApi';
import { getOrgProvincesReq } from '@/utils/yqrange/rangeApi';
import { getCircleTree,postCircleTree } from '@/utils/yqrange/yqrangeApi';
let vm = null;
export default {
  props: {
    circleId: {
      type: Number | String,
      default: 1
    },
    roleType: {
      type: Number | String,
      default: 1
    },
  },
  data() {
    return {
      allSelectedKeys: [],
      updatedTree: false,
      organizationRegion: [],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: "isLeaf"
      },
      treeData: []
    }
  },
  created() {
    vm = this;
    this.getAdministrative();
  },
  mounted() {
  },
  methods: {
      //通过key设置tree
    //   setCheckedKeys(tagsRegion) {
    //   let treeKeyList = [];
    //   for (let index = 0; index < tagsRegion.length; index++) {
    //     treeKeyList[index] = tagsRegion].key;
    //   }
    //   this.$refs.tree.setCheckedKeys(treeKeyList);
    // }, 
    //初始化范围树
    setTreeData(administrative) {
      let treeIdList = [];
      for (let i = 0; i < administrative.length; i++) {
        treeIdList.push(administrative[i]);
 
      }
      console.log(treeIdList);
      this.$refs.tree.setCheckedKeys(treeIdList);
    },
    //查询行政范围（树）
    getAdministrative() {
      let req = {
        circleId: this.circleId//826,874,832
      };
      openLoading(vm);
    
      getCircleTree(req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          let administrativeAll = res.data.regionTreeDto;
          //获取已选的区域
          let administrative = [];
          res.data.provinceIds.forEach(element => {
            administrative.push(element);
          });
          res.data.cityIds.forEach(element => {
            administrative.push(element);
          });
          res.data.countryIds.forEach(element => {
            administrative.push(element);
          });
          res.data.townIds.forEach(element => {
            administrative.push(element);
          });

          // let administrative = res.data.administrative;
          this.treeData = [];
          
          this.treeData[0] = administrativeAll;
         console.log("administrative",administrative);
          this.setTreeData(administrative);
        }
      });
    },
    onChecked(node, data) {
      console.log("11node",node);
      console.log("11data",data);
  
      vm.checkUpdate(node, data);
      
      //重构归并树
      let checkedTree = operationData.getSimpleCheckedNodes(
        this.$refs.tree.store
      );
      console.log("checkedtree",checkedTree);
      let halfCheckedTree = this.$refs.tree.getHalfCheckedKeys();
      console.log("halfcheckedtree",halfCheckedTree);
      let allSelectedKeys = operationData.setSelectedKeys(
        checkedTree,
        halfCheckedTree
      );
      //重构内容

      this.allSelectedKeys = allSelectedKeys;
      //处理原始数据
      //1. 设置选中数据
      let selectedData = data.checkedKeys;
      let halfSelectedData = data.halfCheckedKeys;
      let selectedAll = {};
      selectedData.forEach(element => {
        selectedAll[element] = 1;
     });
      //2.设置半选数据
      halfSelectedData.forEach(element => {
        selectedAll[element] = 2;
     });
     console.log("seledAll",selectedAll);
    //  selectedAll.forEach(element => {
  //特殊处理全国选择状态
  let allSelectRegionId = this.treeData[0].regionId;
  let isExit = selectedAll[allSelectRegionId];
  if(isExit){
    this.treeData[0].checkStatus = isExit
  }else{
    this.treeData[0].checkStatus = 0;
  }
      this.dealOrgData(this.treeData[0].children,selectedAll);
     
    },
    // type 1:选中 2:半选
    dealOrgData(orgData,selectedAll){
      orgData.forEach(element => {
        
        let type = selectedAll[element.regionId];
        if(type){
          //如果是在选中列表(包含半选)里面
           console.log("elementregionid",type);
           element.checkStatus = type;
           if(element.children){
            this.dealOrgData(element.children,selectedAll);
          }
        }else{
            element.checkStatus = 0;
            if(element.children){
            this.dealOrgData(element.children,selectedAll);
          }
        }
      });
     
    },
    checkUpdate(node, data) {
      let flag = -1;
      flag = data.checkedKeys.indexOf(node.regionId);
      console.log("flag",flag);
      if(flag >=0){
        //选中
        this.$refs.tree.setChecked(data,false)
      }else{
        //取消
      }
      // this.dealTreeData(flag,node,this.treeData[0].children,false);
      // 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)
      // }
    },
    //处理原始数据 isHaveFlag 是否直接赋值
    dealTreeData(flag,node,orgTreeData,isHaveFlag){
      orgTreeData.forEach(element => {
        if(isHaveFlag){
          element.checkStatus = flag >0 ? 1 : 0 
        }else{
        if(element.regionId == node.regionId){
          element.checkStatus = flag >0 ? 1 : 0
        }
        }
       
        if(element.children){
          //处理原始数据
          this.dealTreeData(flag,node,element.children,true);
        }
         
      });
    },
    //1.如果选中父,子节点存在,全部选中
       //子节点选中
       appendCheck(administrative, checked) {
      let checkList = [];
      checkList = this.$refs.tree.getCheckedKeys();
      if (checked) {
        for (let i = 0; i < administrative.length; i++) {
          checkList.push(administrative[i].regionId);
        }
      }
      this.$nextTick(function() {
        this.$refs.tree.setCheckedKeys(checkList);
      });
    },
    //添加子节点
    append(data, node) {
      console.log("data:", data);
      console.log("node:", node);
    if (node.level-1 == 1) {
            let req = {
              provinceId: node.data.regionId
            };
            vm.GET("basic-data/position/cities", req).then(res => {
             vm.setMoreOption(data,res.data.cityList, "cities",node);
             });
          } else if (node.level-1 == 2) {
            let req = {
              cityId: node.data.regionId
            };
            vm.GET("basic-data/position/counties", req).then(res => {
               vm.setMoreOption(data,res.data.countyList, "counties",node);
             //添加数据
             

            });
          } else if (node.level-1 == 3) {
            let req = {
              countyId: node.data.regionId
            };
            vm.GET("basic-data/position/towns", req).then(res => {
               vm.setMoreOption(data,res.data.townList, "towns",node);
              
            });
          }
        },
        //设置数据
       // data 父节点,newdata新节点
        setMoreOption(data,newdata, type,node) {
          
          if (data.children !=null) return;
       
        let statusValue = 0;
        if (node.checked == true) {
          statusValue = 1;
        }
          let option = [];
      for (let i = 0; i < newdata.length; i++) {
        let obj = {};
        if (type == "cities") {
          obj.name = newdata[i].cityName;
          obj.regionId =newdata[i].cityId;
        } else if (type == "counties") {
          obj.name = newdata[i].countyName;
          obj.regionId = newdata[i].countyId;
          // obj.leaf = true;
        } else if (type == "towns") {
          obj.name = newdata[i].townName;
          obj.regionId = newdata[i].townId;
          // obj.leaf = true;
        }
        
        obj.checkStatus = statusValue;
        // obj.disabled = false;
        obj.children = null;
        obj.id = null
        option.push(obj);
      }
      console.log("childrenlist:",option);
        data.children = option;
        vm.appendCheck(option,node.checked);
             
  
    },
    //保存
    save(){
      console.log("treedata",this.treeData[0]); 
      let res = this.treeData[0];
      openLoading(vm);
      postCircleTree(res).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          this.$message("保存成功");
          this.$emit('setOrgAndPeople');
        } else {
          this.$message(res.message);
        }
      }).catch(err => {
        this.$message.error('请求失败');
      });
    },
  }
}
</script>
<style >
/*.organization .el-dialog {*/
  /*max-height: 90%;*/
  /*overflow: scroll;*/
/*}*/
</style>
<style lang="scss" >
   .rim {
     .el-icon-caret-right:before {
    content: " "!important;
}
   
}
</style>
<style lang="scss" scoped>
.organization {
  .add-organization {
    margin-left: 36px;
    line-height: 20px;
    width: 120px;
    cursor: pointer;
    padding-top: 10px;
    i {
      font-size: 18px;
      margin-right: 2px;
    }
    .rim {
    border: 1px solid #dddddd;
  }

  }
}
</style>
