<template>
  <div>
    <Row :gutter="20">
      <Col span="15">
      <div
        class="tree-box"
      >
        <div class="split-y-line"></div>
        <Input
          v-if="isShowSearchInput"
          v-model="formSearch.searchVal"
          :placeholder="$t(searchInputPlaceholder)"
          @on-search="orgSearch()"
          search
        >
        <!-- <Button
          slot="append"
          icon="md-search"
          @click="orgSearch()"
        ></Button> -->
        </Input>
        <!--这里Tree有不同业务场景 所以加了判断 之前出了很多问题 要修改最好问一下再改 -黄俊辉-->
        <Tree
          v-if="isShowCheckbox"
          ref="orgTree"
          :data="orgTree"
          :load-data="loadData"
          :show-checkbox="true"
          :render="renderContent"
          @on-check-change="getNodes"
          @on-select-change="getNodes"
          @on-toggle-expand="expandHandle"
        >
        </Tree>
        <Tree
          v-if="!isShowCheckbox"
          ref="orgTree"
          :data="orgTree"
          :load-data="loadData"
          :multiple="isMultiple"
          @on-check-change="getNodes"
          @on-select-change="getNodes"
          @on-toggle-expand="expandHandle"
        >
        </Tree>
        <Spin
          v-show="isShowLoading"
          fix
        >
          <Icon
            type="load-c"
            size="18"
            class="demo-spin-icon-load"
          ></Icon>
          <div>正在加载...</div>
        </Spin>
      </div>
      </Col>

      <Col span="9">
      <p style="padding-bottom: 15px;color: #9d9fa7;">
        {{ this.$t("已选择") }}({{ selectedItem.length }})
      </p>
      <div style="top: 4px;display: flex; justify-content: space-between;">
        <Checkbox
          :value="checkAll"
          :indeterminate="indeterminate"
          @click.prevent.native="handleCheckAll"
        >
          {{ this.$t("全选") }}
        </Checkbox>
        <a
          href="javascript:;"
          style="color: #F99C34;font-size: 12px;"
          @click.prevent="handleDelSelItem"
        >
          <Icon type="close"></Icon>
          {{ this.$t("删除") }}
        </a>
      </div>

      <div class="fill-available-h">
        <CheckboxGroup
          v-model="checkAllGroup"
          @on-change="checkAllGroupChange"
        >
          <ul>
            <li
              v-for="item in selectedItem"
              :key="item.id || item.code"
            >
              <Checkbox
                :label="item.id || item.code"
                style="margin-top: 8px;"
              >
                {{ item.title }}
              </Checkbox>
            </li>
          </ul>
        </CheckboxGroup>
      </div>
      </Col>
    </Row>
  </div>
</template>
<script>
/**
 * 查询组织部门、查询雇员信息
 * 已经应用的功能：员工借款、员工还款流程申请
 */
import getOrgs from './getOrgs.js';
import * as server from '../server.js'; // querySubOrgsByOrgCode
// const server = new Server();
export default {
  name: 'RoleTree',
  props: {
    // 类型有3中   选所有all   选人employee   选部门department
    isShowCheckbox: {
      // 是否显示复选框
      type: Boolean,
      default: true
    },
    isMultiple: {
      // 是否多选
      type: Boolean,
      default: true
    },
    treeType: {
      type: String,
      default: 'all'
    },
    len: {
      type: [String, Number],
      default: 99999
    },
    title: {
      type: String,
      default: '标题'
    },
    searchInputPlaceholder: {
      type: String,
      default: '请输入'
    },
    // 部门ID  如果有传入，则只能选择该部门下的员工
    departmentId: {
      type: String,
      default: ''
    },
    // 是否显示搜索框
    isShowSearchInput: {
      type: Boolean,
      default: true
    },
    // 增加了一个接口用来查人，baseUrl / claimURL
    queryFrom: {
      type: String,
      default: 'base'
    },
    // 选中的选项
    selectedItems: {
      type: [Array, String, Boolean],
      default() {
        return [];
      }
    },
    // 用于选择部门的返回数据的类型：leaf-只返回叶子节点, parent-只返回父级, all-全部
    selectType: {
      type: String,
      default: 'all'
      // validator(val){
      //   return ["leaf", "parent", "all"].indexOf(val) !== -1
      // }
    },
    departmentId_wdz: {
      type: String,
      default: ''
    },
    hideNoChildArrow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // server,
      getOrgs,
      isShowLoading: true,
      treeModal: false,
      selectedItem: [],
      formSearch: {
        enabled: '',
        searchVal: '',
        orgId: ''
      },
      isemployee: false,
      // 组织树
      orgTree: [],
      // backupsTree: [],
      backUpcheckNodes: [],
      indeterminate: false,
      checkAll: false,
      checkAllGroup: []
    };
  },
  created: function() {
    const selectedItem = this.formatSelectedItems(this.selectedItems);
    this.selectedItem = selectedItem ? [].concat(selectedItem) : []; // 数组深拷贝，解决每次改变树，selectedItems跟着改变（原组件bug）
    this.queryInitializationOrgs();
    this.$emit('SetTitle', this.title || '请选择');
    this.$emit('SetPageSize', 800);
    this.$emit('SetPageActions', [
      {
        text: this.$t('保存'),
        theme: 'warning',
        handle: this.saveSelect
      },
      {
        text: this.$t('取消'),
        type: 'default',
        handle: this.cancel
      }
    ]);
  },
  destroyed() {
    this.orgTree = null;
    this.backUpcheckNodes = null;
  },
  methods: {
    renderContent(h, { root, node, data }) {
      return h('span', data.title);
    },
    queryInitializationOrgs() {
      this.isShowLoading = true;
      if(this.departmentId_wdz){
        server.queryInitializationOrgs_wdz(this.departmentId_wdz).then(response => {
          if (response && response.statusCode == '-1') {
            $app.$Message.error('查询失败！');
            return;
          }
          this.treeHandle(response);
          this.orgTree = response;
          // this.backupsTree = orgtree;
          this.isShowLoading = false;
        });
      }else{
        this.getOrgs(orgtree => {
          this.treeHandle(orgtree);
          this.orgTree = orgtree;
          // this.backupsTree = orgtree;
          this.isShowLoading = false;
        });
      }
    },
    expandHandle(node) {
      // 查人：每次展开都查一下人以修复组织下可能有组织也有人的情况
      if (this.treeType === 'employee' && node.expand) {
        this.loadEmployeesData(node, (res) => {
          if (res.length > 0) {
            res.map(ritem => {
              const flag = node.children.every(nitem => {
                if (ritem.id !== nitem.id) {
                  return true;
                }
              });
              if (flag) {
                node.children.unshift(ritem);
              }
            });
          }
        });
      }
    },
    extend(obj, obj2) {
      for (const k in obj2) {
        obj[k] = obj2[k];
      }
    },
    getNodes(checkNodes) {
      // 类型有3中   选所有all   选人employee   选部门department
      let data = [];
      if (this.treeType == 'employee') {
        data = checkNodes.filter(function(obj) {
          if (obj.employee) {
            return true;
          }
          return false;
        });
      }
      if (this.treeType == 'department') {
        data = checkNodes.filter(function(obj) {
          if (obj.employee) {
            return false;
          }
          return true;
        });

        if (this.selectType === 'parent') {
          data = this.selectParent(data);
        }

        if (this.selectType === 'leaf') {
          data = this.selectLeaf(data);
        }
      }

      if (this.len == 1 || (!this.isMultiple && !this.isShowCheckbox)) { // 单选
        this.backUpcheckNodes = checkNodes;
        this.selectedItem = data;
      } else { // 多选
        checkNodes.map(item => {
          this.backUpcheckNodes.push(item);
        });

        data.map(item => {
          if (this.selectedItem.every(bitem => {
            if (bitem.id === item.id) {
              return false;
            } else {
              return true;
            }
          })) {
            this.selectedItem.push(item);
          }
        });
      }

      this.$emit('selectedItem', this.selectedItem);
    },
    handleCheckAll() {
      if (this.indeterminate) {
        this.checkAll = false;
      } else {
        this.checkAll = !this.checkAll;
      }
      this.indeterminate = false;

      if (this.checkAll) {
        this.selectedItem.map(item => {
          this.checkAllGroup.push(item.id || item.code);
        });
      } else {
        this.checkAllGroup = [];
      }
    },
    checkAllGroupChange(data) {
      if (data.length === this.selectedItem.length) {
        this.indeterminate = false;
        this.checkAll = true;
      } else if (data.length > 0) {
        this.indeterminate = true;
        this.checkAll = false;
      } else {
        this.indeterminate = false;
        this.checkAll = false;
      }
    },
    handleDelSelItem() {
      if (this.checkAll) {
        this.selectedItem = [];
        this.checkAllGroup = [];
        this.backUpcheckNodes.map(item => {
          item.selected = false;
          item.checked = false;
          item.indeterminate = false;
        });
        this.backUpcheckNodes = [];
      } else {
        this.checkAllGroup = this.checkAllGroup.filter((sid, sindex) => {
          let cflag = true;
          this.selectedItem = this.selectedItem.filter((item, index) => {
            let sflag = true;
            if (sid === item.id || sid === item.code) {
              cflag = false;
              sflag = false;
              this.backUpcheckNodes.map(nitem => { // 去掉树对应勾选项
                if (sid === nitem.id || sid === nitem.code) {
                  nitem.checked = false;
                  nitem.selected = false;
                  this.backUpcheckNodes.map(nnitem => { // 去掉其上级勾选项
                    if (nitem.departmentId === nnitem.id) {
                      nnitem.orgPath.split('/').map(orgid => { // 找到上级并通过orgPath把所有上级都处理 否则无法响应删除
                        this.backUpcheckNodes.map(bbitem => {
                          if (orgid === bbitem.id) {
                            bbitem.checked = false;
                            bbitem.indeterminate = true;
                          }
                        });
                      });
                    }
                  });
                }
              });
            }
            return sflag;
          });
          return cflag;
        });
      }
      this.checkAll = false;
    },
    treeHandle(treeData, setobj) {
      // debugger
      const self = this;
      const o = setobj || {};
      if (treeData.length <= 0) return;
      for (var i = 0; i < treeData.length; i++) {
        var data = treeData[i];
        if (!data) data = {};
        // data["show-checkbox"] = false;
        if (data.children && data.children.length > 0) {
          // 如果传入了departmentId，那只能选该departmentId下的人  -针对搜索
          if (
            self.treeType == 'employee' &&
            self.departmentId &&
            self.departmentId !== data.id
          ) {
            o.disableCheckbox = true; // 禁止checkbox
          } else {
            o.departmentId = data.id;
            o.disableCheckbox = false;
          }

          if (data.orgPath.split('/').length < 2) {
            data.expand = true;
          } else {
            data.expand = false;
          }

          this.treeHandle(data.children, o);
          this.extend(data, o);
        } else {
          data.children = [];
          data.expand = false;
          // 若没有子集不展示箭头
          if (!data.employee) {
            data.loading = false;
          }
          if (data.hasChild !== 'Y' && this.hideNoChildArrow) {
            delete data.children;
            delete data.loading;
          }
          this.extend(data, o);
        }
      }
    },
    openModal() {
      this.treeModal = true;
    },

    cancel() {
      this.$emit('Close');
    },
    loadData(currentOrg, callback) {
      // 判断该节点下面是否有子数据
      // 这里要通过2个接口来判断   一个是查人   一个是查组织
      const self = this;
      let department = null;
      let employee = null;
      if (this.treeType == 'department') {
        employee = [];
      }

      // 查部门
      server.querySubOrgsByOrgCode({ orgId: currentOrg.id })
        .then(response => {
          if (response && response.statusCode == '-1') {
            self.$Message.error({
              content: '查询失败！',
              duration: 3
            });
            return;
          }
          var orgtree = response;
          self.treeHandle(orgtree);
          department = orgtree;
          if (employee) {
            orgtree = department.concat(employee);
            if (orgtree.length == 0) {
              self.$delete(currentOrg, 'loading', true);
              // 如果只查员工   灰掉部门
              if (self.treeType == 'employee') {
                self.$set(currentOrg, 'disableCheckbox', true);
              }
            } else {
              // 如果只查部门  灰掉员工
              if (self.treeType == 'department') {
                for (const k in orgtree) {
                  if (k) {
                    const d = orgtree[k];
                    if (d.employee == true) {
                      d.disableCheckbox = true;
                    }
                  }
                }
              }
              callback(orgtree);
            }
          }
        });

      // 查人
      const actUrl = this.queryFrom === 'base' ? 'queryEmployeeByOrgCode' : 'queryEmployeeByOrgCodeClaim';
      this.treeType != 'department' && server[actUrl]({
        orgId: currentOrg.id
      }).then(response => {
        if (response && response.statusCode == '-1') {
          self.$Message.error({
            content: '查询失败！',
            duration: 3
          });
          return;
        }
        var orgtree = response;
        self.treeHandle(orgtree);
        employee = orgtree;

        employee.map(item => {
          self.$set(item, 'departmentId', currentOrg.id);
        });

        // 如果传入了departmentId，那只能选该departmentId下的人
        if (this.departmentId && this.departmentId !== currentOrg.id) {
          self.$set(currentOrg, 'disableCheckbox', true);
          employee.map(item => {
            self.$set(item, 'disableCheckbox', true);
            self.$set(item, 'disabled', true);
          });
        }

        if (department) {
          orgtree = department.concat(employee);
          if (orgtree.length == 0) {
            self.$delete(currentOrg, 'loading', true);
            // 如果只查员工   灰掉部门
            if (self.treeType == 'employee') {
              self.$set(currentOrg, 'disableCheckbox', true);
            }
          } else {
            callback(orgtree);
            // 如果只查部门  灰掉员工
            if (self.treeType == 'department') {
              for (const k in orgtree) {
                if (k) {
                  const d = orgtree[k];
                  if (d.employee == true) {
                    d.disableCheckbox = true;
                  }
                }
              }
            }
          }
        }
      });
    },
    loadEmployeesData(currentOrg, callback) {
      const self = this;
      let employee = null;

      // 查人
      const actUrl = this.queryFrom === 'base' ? 'queryEmployeeByOrgCode' : 'queryEmployeeByOrgCodeClaim';
      server[actUrl]({ orgId: currentOrg.id }).then(response => {
        if (response && response.statusCode == '-1') {
          self.$Message.error({
            content: '查询失败！',
            duration: 3
          });
          return;
        }
        var orgtree = response;
        self.treeHandle(orgtree);
        employee = orgtree;

        employee.map(item => {
          self.$set(item, 'departmentId', currentOrg.id);
        });

        // 如果传入了departmentId，那只能选该departmentId下的人
        if (this.departmentId && this.departmentId !== currentOrg.id) {
          self.$set(currentOrg, 'disableCheckbox', true);
          employee.map(item => {
            self.$set(item, 'disableCheckbox', true);
            self.$set(item, 'disabled', true);
          });
        }

        callback(employee);
      });
    },
    orgSearch() {
      this.$nextTick(()=>{        
        this.formSearch.searchVal = this.formSearch.searchVal.trim()
      });
      if (this.formSearch.searchVal == '') {
        this.queryInitializationOrgs();
        return;
      }
      this.isShowLoading = true;
      const self = this;
      if (this.treeType == 'employee') {
        const actUrl = 'queryEmployeeByName';
        // if(this.$App.name === "BIZ"){
        //   actUrl = "queryEmployeeByName"
        // }else if(this.$App.name === "ADMIN"){
        //   actUrl = "queryEmployeeByNameForAdmin"
        // }
        server[actUrl]({
          name: this.formSearch.searchVal.trim()
        })
          .then(response => {
            if (response && response.statusCode == '-1') {
              self.$Message.error({
                content: '查询失败！',
                duration: 3
              });
              this.isShowLoading = false;
              return;
            }

            self.treeHandle(response, { expand: true });
            self.orgTree = response;
            this.isShowLoading = false;
          });
      }

      if (this.treeType == 'department') {
        server.queryOrgByOrgName({
          name: this.formSearch.searchVal.trim()
        })
          .then(response => {
            if (response && response.statusCode == '-1') {
              this.$Message.error({
                content: '查询失败！',
                duration: 3
              });
              this.isShowLoading = false;
              return;
            }

            this.treeHandle(response, { expand: true });
            this.orgTree = response;
            this.isShowLoading = false;
          });
      }
    },
    selectParent(checkNodes) {
      const _org = Object.assign([], checkNodes);
      let checks = [];
      for (let i = 0; i < _org.length; i++) {
        const b = _org[i];
        checks = checkNodes.filter(item => {
          if (b.id === item.id) {
            return true;
          }
          if (item.orgPath.indexOf(b.orgPath) < 0) {
            return true;
          }
          return false;
        });
      }
      return checks;
    },
    selectLeaf(checkNodes) {
      return checkNodes.filter(item => {
        if (!item.children || item.children.length <= 0) {
          return true;
        }
      });
    },
    formatSelectedItems(selectedItems) {
      // ids|names
      // codes?names
      if (selectedItems && Object.prototype.toString.call(selectedItems) === '[object String]') {
        const newSi = [];

        if (selectedItems.indexOf('|') > -1) {
          const siArr = selectedItems.split('|');
          const ids = siArr[0].split(',');
          const titles = siArr[1].split(',');
          ids.map((item, index) => {
            if (item) {
              newSi.push({
                id: item,
                title: titles[index]
              });
            }
          });
        } else if (selectedItems.indexOf('?') > -1) {
          const siArr = selectedItems.split('?');
          const codes = siArr[0].split(',');
          const titles = siArr[1].split(',');
          codes.map((item, index) => {
            if (item) {
              newSi.push({
                code: item,
                title: titles[index]
              });
            }
          });
        }

        return newSi;
      } else {
        return selectedItems;
      }
    },
    saveSelect() {
      // 类型有3中   选所有all   选人employee   选部门department
      const data = this.selectedItem || [];
      if (this.len < data.length) {
        this.$Message.error(`最多选择${this.len}项`);
        return;
      }

      this.$emit('Close', data);
    }
  }
};
</script>
<style scoped>
.tree-box {
  min-height: 300px;
  max-height: 600px;
  overflow-y: scroll;
}
.split-y-line {
  width: 1px;
  opacity: 0.08;
  background: #424656;
  position: absolute;
  right: 4px;
  top: 0;
  height: 100%;
}
/deep/ .ivu-checkbox-wrapper {
  font-size: 12px;
}
</style>
