/*
 * @Author: husanfeng
 * @qq:1136014061
 * @Date: 2018-12-25 11:08:52
 * @Last Modified by: Anmin
 * @Last Modified time: 2019-06-11 11:48:37
 * @description:  业务类别树
 */
<template>
  <div
    :class="pageClass"
    @keydown.enter="orgSearch"
  >
    <Input
      v-model="formSearch.searchVal"
      :placeholder="$t(searchInputPlaceholder)"
      @on-search="orgSearch()"
      @input="orgSearch()"
      search
    >
    </Input>
    <Tree
      ref="treeData"
      v-bind="$attrs"
      :data="treeData"
      :show-checkbox="ShowCheckbox"
      :multiple="ShowMultiple"
      style="overflow: auto;"
      v-on="$listeners"
      @on-check-change="checkChange"
      @on-select-change="checkChange"
    ></Tree>
    <Spin
      v-show="isShowLoading"
      fix
    >
      <Icon
        type="load-c"
        size="18"
        class="demo-spin-icon-load"
      ></Icon>
      <div>正在加载...</div>
    </Spin>
  </div>
</template>
<script>
/**
 * 业务大类(费用类别)树组件
 */
import { buildCategoryTree, BuildCategoryTreeByCondition } from '../server.js';
export default {
  name: 'SelectBusinessType',
  props: {
    title: {
      type: String,
      default: '选择业务类别'
    },
    searchInputPlaceholder: {
      type: String,
      default: '请输入检索内容'
    },
    len: {
      type: [String, Number],
      default: ''
    },
    isShowCheckbox: {
      // 是否显示复选框
      type: Boolean,
      default: false
    },
    isMultiple: {
      // 是否多选
      type: Boolean,
      default: false
    },
    hasFullPathName: {
      // 全路径
      type: Boolean,
      default: false
    },
    // true :包含选中的所有数据，false：只返回父级节点数据
    isSelectChild: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isShowLoading: true,
      selectedItem: null,
      formSearch: {
        searchVal: ''
      },
      treeData: [] // tree的展示数据
    };
  },
  computed: {
    ShowCheckbox() {
      if (this.isShowCheckbox || this.isShowCheckbox === '') {
        return true;
      } else {
        return false;
      }
    },
    pageClass() {
      return this.ShowCheckbox ? 'crc-component-ui-select-businesstype-page-checked' : '';
    },
    ShowMultiple() {
      if (this.isMultiple === '' || this.isMultiple === true) {
        return true;
      } else {
        return false;
      }
    }
  },
  created: function() {
    this.$emit('SetTitle', this.title);
    this.$emit('SetPageActions', [
      {
        text: this.$t('确定'),
        type: 'warning',
        action: 'save',
        handle: this.saveSelect
      },
      {
        text: this.$t('关闭'),
        type: 'default',
        handle: () => {
          this.$emit('Close');
        }
      }
    ]);
    this.queryAllBusinessType();
  },
  methods: {
    /**
     * 查询初始化的三层组织信息
     */
    fetchAllBusinessType() {
      return new Promise(resolve => {
        buildCategoryTree({})
          .then(data => {
            resolve(data);
          })
          .catch(error => {
            const responseData = {
              dataResult: [],
              extra: '',
              msg: error.response.data.message || '服务异常，请联系管理员',
              statusCode: '-1'
            };
            resolve(responseData);
          });
      });
    },
    async queryAllBusinessType() {
      this.isShowLoading = true;
      const response = await this.fetchAllBusinessType();
      if (response.statusCode == '-1') {
        this.$Message.error({
          content: response.msg,
          duration: 3
        });
      } else {
        // 1.获取业务类别的数据
        // 2.对数据进行整理
        // 3.绑定数据渲染
        this.treeData = this.treeHandle(response);
      }
      this.isShowLoading = false;
    },
    checkChange(checkNodes) {
      this.selectedItem = checkNodes;
      this.$emit('selectedItem', this.selectedItem);
    },
    treeHandle(data, parentNode, isExpand) {
      const self = this;
      if (data.length <= 0) return;
      const arr = data.map(element => {
        if (!element) {
          element = {};
        }
        // 给fullPathName属性赋值
        if (self.hasFullPathName || self.hasFullPathName === '') {
          if (!element.parentCode || !parentNode) {
            element.fullPathName = element.title;
          } else {
            element.fullPathName = parentNode.fullPathName + '/' + element.title;
          }
        }
        // end
        if (element.children && element.children.length > 0) {
          element.expand = isExpand || false;
          element.children = self.treeHandle(element.children, element, isExpand);
        } else if (element.children && element.children.length == 0) {
          element.title = `${element.title}-${element.code}`;
        } else {
          element.children = null;
        }
        element.defaultTitle = element.title; // 处理title本身就有-的情况
        return element;
      });
      return arr;
    },
    // 模糊查询
    orgSearch() {
      if(this.formSearch.searchVal==' '){
        this.$nextTick(()=>{        
        this.formSearch.searchVal = ''
      })
        return
      }
      this.$nextTick(()=>{        
        this.formSearch.searchVal = this.formSearch.searchVal.trim()
      })
      const searchVal = this.formSearch.searchVal.trim();
      if (searchVal === '') {
        this.queryAllBusinessType();
      } else if (searchVal != '') {
        this.queryBusinessTypeForName({
          categoryNameOrCode: searchVal
        });
      }
    },
    /**
     * 根据名称查询
     */
    fetchQueryBusinessTypeForName(param) {
      return new Promise(resolve => {
        BuildCategoryTreeByCondition(param)
          .then(response => {
            resolve(response);
          })
          .catch(error => {
            const responseData = {
              dataResult: [],
              extra: '',
              msg: error.response.data.message || '服务异常，请联系管理员',
              statusCode: '-1'
            };
            resolve(responseData);
          });
      });
    },
    async queryBusinessTypeForName(searchVal) {
      this.isShowLoading = true;
      const response = await this.fetchQueryBusinessTypeForName(searchVal);
      if (response.statusCode == '-1') {
        this.$Message.error({
          content: response.msg,
          duration: 3
        });
      } else {
        this.treeData = this.treeHandle(response, null, true);
      }
      this.isShowLoading = false;
    },
    /**
     * 选中业务类别
     * 有两种选择数据的方法
     * 1.有复选框 ，可勾选
     * 2.点击title 选中
     * 数据会有重复。
     * 默认只给 选中（1）复选框的内容
     * 如果同时设置了 勾选和选中  默认返回 复选框内容
     */
    saveSelect() {
      this.$emit('SetActionsState', { btn: 'save', state: true });
      let data = null;
      if (this.ShowCheckbox) {
        data = this.$refs.treeData.getCheckedNodes(); // 获取被勾选的节点;
      } else if (this.ShowMultiple) {
        data = this.$refs.treeData.getSelectedNodes(); // 获取被选中的节点
      } else {
        // 单选
        const _arr = this.$refs.treeData.getSelectedNodes(); // 获取被选中的节点
        if (_arr.length === 1) {
          data = _arr[0];
        }
      }
      // 如果多选，并且限制数量
      if (this.len && this.len < data.length) {
        this.$Message.error(`最多选择${this.len}项`);
        this.$emit('SetActionsState', { btn: 'save', state: false });
        return;
      }
      // 多选 是取所有节点还是只要父节点
      if (this.isSelectChild) {
        this.$emit('Close', data);
      } else {
        this.$emit('Close', this.getParentsNode(data));
      }
    },
    // 子节点数据过滤 选中的数据包含
    getParentsNode(data) {
      function getResult(item, arr) {
        const result = [];
        arr.forEach(element => {
          if (element.parentCode !== item.code) {
            result.push(element);
          }
        });
        return result;
      }
      let result = data;
      for (var i = 0; i < result.length; i++) {
        result = getResult(result[i], result);
      }
      return result;
    }
  }
};
</script>
<style lang="less">
.crc-component-ui-select-businesstype-page-checked {
  .ivu-tree {
    ul {
      li {
        position: relative;
        line-height: 24px;
        display: inline-block;
        margin: 0px !important;
        .ivu-checkbox-wrapper {
          width: 100%;
          position: absolute;
        }
        .ivu-tree-title {
          margin-left: 25px;
        }
      }
    }
  }
}
.ivu-tree-title, .ivu-tree ul{
  font-size: 12px;
}
</style>
