<template>
  <rt-view class="buTreeView">
    <rt-header>
      <!-- <rt-navbar :onBack="goBackClick">{{viewTitle}}</rt-navbar> -->
      <rt-navbar :onBack="goBackClick">
        <span class="rt-header-title2">{{ viewTitle }}</span>
      </rt-navbar>
      <rt-search
        v-if="customBu"
        :placeholder="placeholder"
        :show-search-button="true"
        v-model="quickSearch"
        @on-search="search"
      ></rt-search>
    </rt-header>
    <rt-content style="background: #ffffff;">
      <rt-list-item class="itemSpace itemMember" v-for="(bu,index) in listData" :key="index">
        <i
          v-if="!bu.selectedStatus || bu.selectedStatus===0"
          class="leftIcon rt-icon-oval-unselected"
          v-on:click="checkBoxClick(bu)"
        ></i>
        <i
          v-if="bu.selectedStatus === 1"
          style="color: #4a90e2;opacity: 0.5;"
          class="leftIcon rt-icon-right"
          v-on:click="uncheckBoxClick(bu)"
        ></i>
        <i
          v-if="bu.selectedStatus === 2"
          style="color: #4a90e2;"
          class="leftIcon rt-icon-right"
          v-on:click="uncheckBoxClick(bu)"
        ></i>
        <div class="infoSpace" v-on:click="itemClick(bu)">
          <span class="nameSpace" v-if="!customBu">{{bu.Name}}</span>
          <span class="nameSpace" v-if="customBu">{{bu.Name}}{{bu.buidname1}}{{bu.buidname2}}{{bu.buidname3}}{{bu.buidname4}}</span>
          <rt-icon
            v-if="bu.Children &&bu.Children.length > 0"
            name="rt-xrm-angle-right"
            class="rightIcon"
          ></rt-icon>
        </div>
      </rt-list-item>
    </rt-content>
    <rt-footer class="footer">
      <div class="btn-reset" v-on:click="reSet()">重置</div>
      <div class="btn-sure" v-on:click="okClick()">确定</div>
    </rt-footer>
  </rt-view>
</template>

<script>
export default {
  components: {},
  props: {},
  name: 'butreelookupfilter-list',
  data() {
    return {
      fatherId: '',
      listenId: '',
      fatherlisten: '',
      childrenlisten: '',
      paramJson: {},
      listData: [],
      selectedList: [],
      childSelectedList: [],
      viewTitle: '部门筛选',
      routeName: 'butreelookupfilter-list',
      customBu: false,
      placeholder: '输入部门名称快速搜索',
      quickSearch: ''
    };
  },
  created() {
    this.paramJson = this.$route.params.paramJson ? this.$route.params.paramJson : {};
    this.fatherId = this.$route.params.fatherId;
    this.listenId = this.$route.params.fatherId ? parseInt(this.$route.params.fatherId) + 1 : 1;
    this.fatherlisten = 'butreelookupfilter-list' + (this.$route.params.fatherId ? this.fatherId : '');
    this.childrenlisten = 'butreelookupfilter-list' + this.listenId;
    this.customBu = this.$route.params.customBu;

    this.listData = [
      {
        Id: 'allSelected',
        Name: '全选',
        ParentId: ''
      }
    ];

    this.viewTitle = rt.isNullOrWhiteSpace(this.paramJson.Name) ? '部门筛选' : this.paramJson.Name;

    //父数据
    if (this.paramJson && this.paramJson.Children && this.paramJson.Children.length > 0) {
      this.listData = this.listData.concat(this.paramJson.Children);
      this.handleSelected();
    } else {
      this.getListData();
    }
  },
  methods: {
    //获取数据
    async getListData() {
      let apiUrl = '';
      if(this.customBu) {
        apiUrl = this.$route.params.customApi.replace('$quickSearch', encodeURIComponent(this.quickSearch));
      } else {
        apiUrl = 'api/TblBusinessUnit/GetMobileBusinessTree';
      }
      
      let resp = await rt.get(apiUrl);
      if (!rt.isNull(resp)) {
        this.listData = this.listData.concat(resp);
        this.setStoragedData({
          Id: 'toptree',
          Children: resp
        });
        this.handleSelected();
      }
    },
    search() {
      this.listData = [
        {
          Id: 'allSelected',
          Name: '全选',
          ParentId: ''
        }
      ];
      this.getListData();
    },
    //处理已选中数据
    handleSelected() {
      if (this.paramJson) {
        if (this.paramJson && this.paramJson.selectedStatus === 2) {
          this.checkBoxClick({
            Id: 'allSelected',
            Name: '全选',
            ParentId: ''
          });
        } else {
          let that = this;
          _.forEach(that.listData, function(element) {
            let selectItem = _.find(that.paramJson.Children, function(item) {
              return item.Id === element.Id;
            });

            if (selectItem) that.$set(element, 'selectedStatus', selectItem.selectedStatus);
          });

          this.checkSelectedAllState();
        }
      }
    },
    //反选
    uncheckBoxClick(selected) {
      let that = this;
      if (selected.Id === 'allSelected') {
        //全选
        _.forEach(that.listData, function(element) {
          that.setSelectedStatus(element, 0); //未选择
        });
      } else {
        that.setSelectedStatus(selected, 0);

        that.checkSelectedAllState();
      }
    },
    //点击选择框
    checkBoxClick(selected) {
      let that = this;
      if (selected.Id === 'allSelected') {
        //全选
        _.forEach(that.listData, function(element) {
          element = that.setSelectedStatus(element, 2);
        });
      } else {
        selected = that.setSelectedStatus(selected, 2);
      }

      that.checkSelectedAllState();
    },
    //item点击
    itemClick(bu) {
      let that = this;
      if (bu.Children && bu.Children.length > 0) {
        //有子部门
        that.setSelectedData();

        this.$router.push({
          name: this.routeName,
          params: {
            fatherId: that.listenId,
            paramJson: bu
          }
        });
        let deregistration = that.$bus.$once(that.childrenlisten, value => {
          if (value) {
            var index = _.findIndex(that.listData, function(element) {
              return element.Id === value.Id;
            });

            if (index > -1) that.listData[index] = value;

            that.checkSelectedAllState();
          }
        });
      } else return;
    },
    //检查是否全选
    checkSelectedAllState() {
      if (this.listData) {
        let status = 0;
        let allStatus = 2 * (this.listData.length - 1);
        _.forEach(this.listData, function(element) {
          if (element.Id !== 'allSelected') status += parseInt(element.selectedStatus ? element.selectedStatus : 0);
        });

        if (status === allStatus) this.$set(this.listData[0], 'selectedStatus', 2);
        else if (0 < status && status < allStatus) this.$set(this.listData[0], 'selectedStatus', 1);
        else this.$set(this.listData[0], 'selectedStatus', 0);
      }
    },

    //获取父选中状态
    getSelectedState(data) {
      if (data) {
        if (data.Children && data.Children.length > 0) {
          let status = 0;
          let listData = _.filter(data.Children, function(element) {
            return element.Id !== 'allSelected';
          });

          let allStatus = 2 * (listData ? listData.length : 0);

          _.forEach(listData, function(element) {
            status += parseInt(element.selectedStatus ? element.selectedStatus : 0);
          });

          if (status === allStatus) return 2;
          else if (0 < status && status < allStatus) return 1;
          else return 0;
        } else return data.selectedStatus ? data.selectedStatus : 0;
      }
    },
    //设置树的选中状态
    setSelectedData() {
      let treeData = this.replaceTreeData(this.getParentData(), this.getStoragedData());

      this.$set(treeData, 'selectedStatus', this.getSelectedState(treeData));
      treeData = this.resetTreeSelectedStatus(treeData);
      this.setStoragedData(treeData);
    },
    //设置当前分支往下树的状态
    setSelectedStatus(data, status) {
      let that = this;
      if (data) {
        this.$set(data, 'selectedStatus', status);
        if (data.Children) {
          _.forEach(data.Children, function(element) {
            element = that.setSelectedStatus(element, status);
          });
        }
      }

      return data;
    },
    //获取父数据
    getParentData() {
      let ParentSelectedData = this.paramJson;

      this.$set(ParentSelectedData, 'selectedStatus', this.listData[0].selectedStatus);

      //过滤全选
      ParentSelectedData.Children = _.filter(this.listData, function(element) {
        return element.Id !== 'allSelected';
      });

      return ParentSelectedData;
    },
    //遍历替换某一分支
    replaceTreeData(data, treeData) {
      if (treeData) {
        if (treeData.Id === data.Id) return data;
        else return this.replaceTreeArrayData(data, treeData);
      } else {
        return treeData;
      }
    },
    //替换对应分支上的数据
    replaceTreeArrayData(data, treeData) {
      let temp = [];
      let that = this;

      if (!treeData || !treeData.Children) {
        return;
      }

      let index = _.findIndex(treeData.Children, function(element) {
        return element.Id === data.Id;
      });

      if (index > -1) treeData.Children[index] = data;
      else {
        _.forEach(treeData.Children, function(element) {
          that.replaceTreeArrayData(data, element);
        });
      }

      return treeData;
    },
    //重置整棵树的状态
    resetTreeSelectedStatus(data) {
      let that = this;
      if (!data) return;

      if (data.Children) {
        _.forEach(data.Children, function(element) {
          if (element.Children && element.Children.length > 0) that.resetTreeSelectedStatus(element);

          that.$set(element, 'selectedStatus', that.getSelectedState(element));
        });
      }
      this.$set(data, 'selectedStatus', this.getSelectedState(data));

      return data;
    },
    //存
    setStoragedData(data) {
      if (data) localStorage.setItem('butreelookupfilter-list', JSON.stringify(data));
    },
    //读
    getStoragedData() {
      let data = localStorage.getItem('butreelookupfilter-list');
      if (data) return JSON.parse(data);
      else return data;
    },
    //重置
    reSet() {
      let that = this;
      _.forEach(this.listData, function(element) {
        that.setSelectedStatus(element, 0);
      });
    },
    goBackClick() {
      let resp = this.getParentData();

      this.setSelectedData();

      //返回并向前一页传递数据
      this.$bus.$emit(this.fatherlisten, resp);

      this.backView(-1);
    },
    okClick() {
      this.setSelectedData();

      for (let i = this.fatherId; i > 0; i--) {
        //终止所有的页面监听
        this.$bus.$emit('butreelookupfilter-list' + i, null);
      }

      //返回并向前一页传递数据
      this.$bus.$emit('butreelookupfilter-list', this.getParentData());

      this.backView(-this.listenId);
    },
    backView(num) {
      this.$router ? this.$router.history.go(num) : window.history.go(num);
    }
  }
};
</script>
<style lang="less" scoped>
.buTreeView {
  .itemSpace {
    display: flex;
    height: 44px;
    border-bottom: 1px solid #ddd;
    line-height: 44px;
    .leftIcon {
      flex: 1;
      font-size: 17px;
      color: #cccccc;
    }
    .infoSpace {
      flex: 9;
      display: flex;
      .nameSpace {
        font-size: 14px;
        color: #555555;
        flex: 9;
      }
      .rightIcon {
        font-size: 12px;
        color: #cccccc;
        padding-top: 15px;
        flex: 1;
      }
    }
  }
  .itemMember {
    margin-left: 15px;
  }
  .itemBottom {
    padding-left: 15px;
  }

  .footer {
    display: flex;
    .btn-sure {
      height: 45px;
      background: #4a90e2;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 44px;
      border-top: 1px solid #f3f3f3;
      flex: 1;
    }

    .btn-reset {
      height: 45px;
      font-size: 14px;
      color: #555555;
      line-height: 44px;
      text-align: center;
      border-top: 1px solid #f3f3f3;
      flex: 1;
    }
  }
}
</style>

