<template>
  <div
    ref='selectShareOrg'
    class='select-share-org'
  >
    <FormBlock
      direction='column'
      class='select-share-org-search'
      :style='contentHeight'
    >
      <div class='select-share-org-content'>
        <Form
          ref='searchForm'
          :model='searchForm'
          :label-width='10'
          inline
          style='padding: 10px 0;'
        >
          <FormItem
            prop='sharedOrgName'
            style='width:100%;margin-right: 0'
          >
            <Input
              v-model.trim='searchForm.sharedOrgName'
              size='small'
              style='width: calc(100% - 20px)'
              placeholder="请输入"
              :loading='loading.search'
              @input="search"
              clearable
              search
            ></Input>
            <!-- <Button
              ref='search'
              size='small'
              type='warning'
              icon='md-search'
              style='margin-left: 10px; height: 24px;'
              :loading='loading.search'
              @click='search'
            >{{ $t('查询') }}</Button> -->
          </FormItem>
        </Form>
        <!-- <Button
          v-if='!onModal'
          type='warning'
          icon='md-add'
          size='small'
          style='margin-left: 10px;'
          @click='add'
        >{{ $t('新增') }}</Button>
        <Button
          v-if='!onModal'
          type='warning'
          icon='ios-download-outline'
          size='small'
          style='margin-left: 10px;'
          @click='exportData'
        >{{ $t('导出') }}</Button> -->
        <div class='select-share-org-tree'>
          <Tree
            ref='shareOrgTree'
            style='margin-top: -8px;'
            :data='treeData'
            :multiple='isMultiple'
            :render='treeRender'
            @on-select-change='select'
          ></Tree>
        </div>
      </div>
    </FormBlock>
    <div class="btns" v-if='!onModal'>
        <Button
          type='warning'
          icon='md-add'
          class="ems-btn-medium ems-btn-type1 add"
          @click='add'
        >{{ $t('新增') }}</Button>
        <Button
          icon='icon iconfont iconbaisedaochu'
          class="ems-btn-medium ems-btn-type3 export"
          @click='exportData'
        >{{ $t('导出') }}</Button>
    </div>
  </div>
</template>
<script>
import { QueryShareOrgTree } from '../server.js';
const QUERY = {
  enabled: '',
  groupType: '',
  centerOrgCode: '',
  sharedOrgName: ''
}
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    valid: {
      type: String,
      default: null
    },
    onModal: {
      type: Boolean,
      default: true
    },
    isMultiple: {
      type: Boolean,
      default: false
    },
    disabledRoot: {
      type: Boolean,
      default: true
    },
    validateFn: {
      type: Function,
      default: null
    },
    enabled: {
      type: [Number, String],
      default: ''
    },
    groupType: {
      type: [Number, String],
      default: ''
    },
    centerOrgCode: {
      type: [Number, String],
      default: ''
    }
  },
  data() {
    return {
      contentHeight: '',
      treeData: [],
      selectData: null,
      loading: {
        search: false
      },
      searchForm: Object.assign({}, QUERY, {
        enabled: this.enabled,
        groupType: this.groupType,
        centerOrgCode: this.centerOrgCode,
        sharedOrgName: ''
      }),
      firstCreated: true,
      selectId: null
    };
  },
  mounted() {
    this.search();
    try {
      if (this.onModal) {
        this.contentHeight = `height: ${
          window.innerHeight - this.$refs.selectShareOrg.offsetTop - 195
          }px`;
      } else {
        this.contentHeight = `height: ${
          window.innerHeight - this.$refs.selectShareOrg.offsetTop - 20
          }px`;
      }
    } catch (error) { }
    this.$emit('SetTitle', this.title);
    this.$emit('SetPageActions', [
      {
        text: this.$t('确定'),
        type: 'warning',
        className: 'ems-btn-medium ems-btn-type1',
        action: 'save',
        handle: () => {
          this.save();
        }
      },
      {
        text: this.$t('返回'),
        className: 'ems-btn-medium ems-btn-type3',
        action: 'close',
        handle: () => this.$emit('Close')
      }
    ]);
  },
  methods: {
    // 导出数据
    async exportData() {
      // if (this.treeData[0].children && this.treeData[0].children.length < 1) {
      //   this.$Message.warning('没有可导出的数据');
      //   return false;
      // }
      this.$DownloadFile({
        url: '/ems-shared-dispatch-application/shared/excel/export',
        method: 'post',
        data: this.downLoadQuery || QUERY
      });
    },

    treeRender(h, { root, node, data }) {
      return h('span', [
        h('span', data.title),
        data.sharedOrgId === this.selectId
          ? h('span', {
            style: 'display: none',
            class: 'selectFlag'
          })
          : null
      ]);
    },
    reset(val) {
      this.searchForm.sharedOrgName = '';
      this.search(val);
    },
    search(val) {
      this.downLoadQuery = Object.assign({}, this.searchForm);
      this.selectId = val ? val.id : null;
      this.loading.search = true;
      QueryShareOrgTree(this.searchForm)
        .then((data) => {
          data.data.title = this.$t('共享组织');
          const treeData = [data.data];
          treeData.forEach((item) => {
            if (!this.searchForm.sharedOrgName && !this.selectId) {
              item.expand = true;
              item.children = item.children || [];
            } else {
              item.expand = true;
              item.children = item.children || [];
              this.deepTree(item.children, [item]);
            }
          });
          this.treeData = treeData;
          if (this.firstCreated && !this.onModal) {
            this.$nextTick(() => {
              try {
                this.$refs.selectShareOrg
                  .querySelectorAll('.ivu-tree-children li .ivu-tree-title')[1]
                  .click();
              } catch (error) { }
              this.firstCreated = false;
            });
          }
          if (this.selectId) {
            this.$nextTick(() => {
              try {
                this.$refs.selectShareOrg.querySelector('.selectFlag').click();
              } catch (error) { }
            });
          }
        })
        .catch((error) => {
          this.$Message.error(error || this.$t('网络错误'));
        })
        .done(() => {
          this.loading.search = false;
        });
    },
    add() {
      if (this.loading.search) return;
      this.$emit('add');
    },
    select(list, data) {
      if (!list.length) {
        this.selectData = null;
        this.$emit('select', null);
      } else {
        if (this.isMultiple) {
          this.selectData = list;
        } else {
          this.selectData = data;
        }
        this.$emit('select', data);
      }
    },
    deepTree(children, parent) {
      children.forEach((item) => {
        if (this.searchForm.sharedOrgName) {
          item.expand = true;
          item.children = item.children || [];
          item.children.length && this.deepTree(item.children);
        }
        if (this.selectId) {
          if (this.selectId === item.sharedOrgId) {
            parent.forEach((it) => {
              it.expand = true;
            });
          } else {
            item.children = item.children || [];
            item.children.length &&
              this.deepTree(item.children, [...parent, item]);
          }
        }
      });
    },
    save() {
      if (!this.selectData) {
        this.$Message.error(this.valid || this.$t('请选择一项数据'));
      } else {
        if (this.selectData.sharedOrgCode === 'ROOT' && this.disabledRoot) {
          this.$Message.error(this.$t('根节点不可选'));
          return;
        } else if (this.validateFn) {
          if (!this.validateFn(this.selectData)) {
            return;
          }
        }
        this.$emit('Close', this.selectData);
      }
    }
  }
};
</script>
<style lang='less'>
.select-share-org {
  position: relative;
  .select-share-org-search {
    background: #fff;
    margin-right: 0px;
    border: none;
  }

  .form-block-title {
    display: none;
  }

  .select-share-org-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;

    .ivu-form-item {
      margin-bottom: 0 !important;
    }

    .select-share-org-tree {
      position: absolute;
      top: 60px;
      bottom: 60px;
      right: 0;
      left: 0;
      overflow: auto;
      .ivu-tree-title{
        font-size: 12px;
      }
      .ivu-tree-empty {
        padding-top: 15px;
        text-align: center;
      }
    }
  }
  .btns{
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px;
    line-height: 60px;
    background: #fff;
    border-top: 1px solid rgba(66,70,86,0.05);
    text-align: right;
    button{
      margin-right: 16px;
      padding: 0 10px !important;
    }
  }
}
.ivu-tree-title-selected {
  background: none !important;
  color: #F99C34 !important;
}
</style>
<style scoped>
.ivu-input-wrapper-small .ivu-input-icon {
  line-height: 32px !important;
}
</style>
