/**
 * 单位部门树
 */
<template>
  <div style="user-select: none;">
    <TreeViewNode
      v-for="clientOrganization in datas"
      :key="clientOrganization.id"
      :node="clientOrganization"
      :is-root="true"
      :is-show-check="true"
      @node-select="organizationSelect"
    />
  </div>
</template>

<script>

import Common from '../common/Common.js';
import OrganizationResource from '../api/base/OrganizationResource.js';
// import TreeViewNode from '../widget/TreeViewNode.vue';
import { Notify, Uuid } from 'pc-component-v3';

export default {

  components: {
    // TreeViewNode,
  },
  
  props: {
    autoGetAllClientId: {
      type: Boolean,
      default: false,
    }, 
    ids: {
      type: Array,
      default: function(){
        return null;
      },
    },
  },


  emits: ['selectChanged', 'getClientOrganizations'],

  data: function () {
    return {
      datas: [],   //所有根部门
      selectedClientIds: [], // 已选择的单位集合
      autoGetAll: false,//默认获取所有部门id
    };
  },

  watch: {
    'selectedClientIds': function (newVal) {
      var _self = this;
      _self.$emit('getClientOrganizations', newVal);
    },
    'ids': function (currentValue, oldValue) {
      if (currentValue) {
        this.setSelectedIds(currentValue);
      }
    },
  },

  mounted: function () {
    var _self = this;
    _self.autoGetAll = this.autoGetAllId;
    this.getOrganizations();

    if (this.ids != null) {
      this.setSelectedIds(this.ids);
    }
  },

  methods: {

    /**
         * 获取可访问的单位部门
         */
    getOrganizations: function () {
      var _self = this;
      OrganizationResource.getClientOrganizations().then(successData => {
        if(successData.errorCode != 0){
          Notify.error('部门查询失败', successData.errorCode, false);
          return;
        }
        _self.initClientOrganization(successData.datas);
        _self.setSelectedIds(this.ids);
        _self.$nextTick(function(){
          _self.$emit('loadFinished');
        });
      }, errorData => {
        Common.processException(errorData);
      });
    },

    /**
         * 初始化部门数据
         */
    initClientOrganization: function (data) {
      var _self = this;
      function setOpen(node) {
        node.open = false;
        if (_self.autoGetAll == undefined) {
          node.selected = false;
        } else {
          node.selected = _self.autoGetAll;
        }
        node.isShowCheck = true;
        node.text = node.name;
        if (node.childrenDatas != undefined && node.childrenDatas.length > 0) {
          node.childrenDatas.forEach(function (item) {
            setOpen(item);
          });
        }
      }
      data.forEach(function (item) {
        setOpen(item);
      });
      _self.datas = data;
      if (_self.autoGetAll != undefined && _self.autoGetAll) {
        this.getSelectedIds();
      }
    },

    /**
        * 父组件调用，用来初始化数据
        */
    initClientOrganization1: function () {
      var _self = this;
      _self.initClientOrganization(_self.datas);
    },

    /**
         * 部门选择
         */
    organizationSelect: function (node) {
      var _self = this;
      node.selected = !node.selected;
      var current = node.selected;

      function changeSelect(item) {
        item.selected = current;
        if (item.childrenDatas != undefined && item.childrenDatas.length > 0) {
          item.childrenDatas.forEach(function (item1) {
            changeSelect(item1);
          });
        }
      }
      changeSelect(node);

      function changeParentSelect(item) {
        if (item.childrenDatas != undefined && item.childrenDatas.length > 0) {
          var selectedCount = 0;
          item.childrenDatas.forEach(function (item1) {
            changeParentSelect(item1);
            if (item1.selected) {
              selectedCount++;
            }
          });
          if (item.isClient) {
            if (selectedCount < item.childrenDatas.length) {
              item.selected = false;
            } else {
              item.selected = true;
            }
          }
        }
      }
      _self.datas.forEach(function (item) {
        changeParentSelect(item);
      });
      // 触发selectChanged事件
      _self.$emit('selectChanged');

      let selectedIds = this.getSelectedIds();

      _self.$emit('valueChanged', selectedIds);
    },

    /**
         * 设置选中项
         */
    setSelectedIds: function (ids) {
      var _self = this;
      function setSelected(item) {
        if (ids != null && ids.indexOf(item.id) >= 0) {
          item.selected = true;
        } else {
          item.selected = false;
        }

        if (item.childrenDatas != undefined && item.childrenDatas.length > 0) {
          item.childrenDatas.forEach(function (item1) {
            setSelected(item1);
          });
        }
      }

      _self.datas.forEach(function (item) {
        setSelected(item);
      });

      function setParentSelect(item) {
        if (item.childrenDatas != undefined && item.childrenDatas.length > 0) {
          var selectedCount = 0;
          item.childrenDatas.forEach(function (item1) {
            setParentSelect(item1);
            if (ids != null && ids.indexOf(item1.id) >= 0) {
              selectedCount++;
            }
          });
          if (item.isClient) {
            if (selectedCount > 0) {
              if (selectedCount < item.childrenDatas.length) {
                item.open = true;
                item.selected = false;
              } else {
                item.selected = true;
              }
            }
          }
        }
      }
      _self.datas.forEach(function (item) {
        setParentSelect(item);
      });
    },


    /**
         * 获取选择的部门ID集合
         */
    getSelectedIds: function () {
      var _self = this;
      _self.selectedClientIds.splice(0, _self.selectedClientIds.length);
      function getSelected(item) {
        if (!item.isClient && item.selected) {
          _self.selectedClientIds.push(item.id);
        }
        if (item.childrenDatas != undefined && item.childrenDatas.length > 0) {
          item.childrenDatas.forEach(function (item1) {
            getSelected(item1);
          });
        }
      }
      _self.datas.forEach(function (item) {
        getSelected(item);
      });
      return _self.selectedClientIds;
    },
  },
};
</script>

<style>
</style> 