<template>
  <Poptip
    :disabled="disabled"
    :transfer="false"
    class="advanced-search"
    placement="bottom"
    style="margin-left: 8px;"
    v-model="advancedSearch"
  >
    <a>
      高级查询
      <Icon :type="advancedSearch ? 'ios-arrow-up' : 'ios-arrow-down'" />
    </a>
    <div class="align-left" slot="title">组织架构</div>
    <div slot="content">
      <div style="white-space: normal;">
        <Button disabled style="width: 150px; margin-bottom: 4px;" v-if="disableSC">
          {{subCenter}}
          <Icon type="ios-arrow-forward" />
        </Button>
        <Poptip :transfer="false" placement="right-start" title="中心" v-else v-model="visibleSC">
          <Button style="width: 150px; margin-bottom: 4px;">
            {{subCenter}}
            <Icon type="ios-arrow-forward" />
          </Button>
          <div slot="content">
            <Tree :data="dataSC" :render="renderSC"></Tree>
          </div>
        </Poptip>
        <br />
        <Button disabled style="width: 150px; margin-bottom: 4px;" v-if="disableSL">
          {{specialLine}}
          <Icon type="ios-arrow-forward" />
        </Button>
        <Poptip :transfer="false" placement="right-start" title="专线" v-else v-model="visibleSL">
          <Button style="width: 150px; margin-bottom: 4px;">
            {{specialLine}}
            <Icon type="ios-arrow-forward" />
          </Button>
          <div slot="content">
            <Tree :data="dataSL" :render="renderSL"></Tree>
          </div>
        </Poptip>
        <br />
        <Button disabled style="width: 150px; margin-bottom: 4px;" v-if="disableAG">
          {{adminGroup}}
          <Icon type="ios-arrow-forward" />
        </Button>
        <Poptip :transfer="false" placement="right-start" title="业务小组" v-else v-model="visibleAG">
          <Button style="width: 150px; margin-bottom: 4px;">
            {{adminGroup}}
            <Icon type="ios-arrow-forward" />
          </Button>
          <div slot="content">
            <Tree :data="dataAG" :render="renderAG"></Tree>
          </div>
        </Poptip>
      </div>
      <Row justify="end" style="margin-top: 8px;" type="flex">
        <Button @click="clear" size="small" v-if="clearable">清空</Button>
        <Button @click="confirm" size="small" style="margin-left: 4px;" type="primary">确定</Button>
      </Row>
    </div>
  </Poptip>
</template>

<script>
// import { SUB_CENTER } from '@conf/dict'
import WfmOrgAPI from '@api/common/wfmOrg'
export default {
  name: 'advanced-search',
  data () {
    return {
      advancedSearch: false,
      subCenter: '中心',
      specialLine: '专线',
      adminGroup: '业务小组',
      resObj: {
        sc: {},
        sl: {},
        ag: {}
      },
      visibleSC: false,
      visibleSL: false,
      visibleAG: false,
      dataSC: [],
      dataSL: [],
      dataAG: []
    }
  },
  props: {
    // 自动加载
    autoLoad: {
      type: Boolean,
      default: false
    },
    // 是否自动查询
    autoSearch: {
      type: Boolean,
      default: false
    },
    // 是否禁用中心选择
    disableSC: {
      type: Boolean,
      default: false
    },
    // 是否禁用专线选择
    disableSL: {
      type: Boolean,
      default: false
    },
    // 是否禁用业务小组选择
    disableAG: {
      type: Boolean,
      default: false
    },
    // 可否清空
    clearable: {
      type: Boolean,
      default: false
    },
    // 机构树权限类型（排班1绩效2）
    orgType: {
      type: Number,
      default: 1
    },
    // 是否禁用点击选择
    disabled: {
      type: Boolean,
      default: false
    }
  },
  created () {
    this.getOrg('SC', '') // 初始化加载中心
    // if (this.autoLoad) {
    //   this.getOrgAuto('SC', '') // 初始化加载中心
    // } else {
    //   this.getOrg('SC', '')
    // }
  },
  methods: {
    /**
     * @param category 'SC':中心, 'SL':专线，'AG': 业务小组
     */
    getOrg (category, parentId) {
      const type = this.orgType
      WfmOrgAPI.orgTreeAuth({ parentId, type })
        .then(({ data }) => {
          if (data.status === 'success') {
            this['data' + category] = data.data
            switch (category) {
              case 'SL':
                if (data.data && data.data[0]) {
                  const obj = data.data[0]
                  //this.specialLine = obj.name
                  //this.resObj.sl = obj
                  //this.getOrg('AG', data.data[0].id)
                  this.$emit('on-select-sub-center', obj.id, obj)
                } else {
                  this.specialLine = '专线'
                  this.resObj.sl = {}
                  this.adminGroup = '业务小组'
                  this.resObj.ag = {}
                }
                break
              case 'AG':
                if (data.data && data.data.length > 0) {
                  let teamId = this.$store.state.user.teamId
                  var obj = null
                  if (teamId) {
                    teamId = 't_' + teamId
                    for (let i = 0; i < data.data.length; i++) {
                      if (data.data[i].id === teamId) {
                        obj = data.data[i]
                        break
                      }
                    }
                  } else {
                    obj = data.data[0]
                  }
        
                  // this.adminGroup = obj.name
                  // this.resObj.ag = obj
                  this.$emit('on-select-admin-group', obj.id, obj)
                } else {
                  this.adminGroup = '业务小组'
                  this.resObj.ag = {}
                }
            }
          }
        })
        .catch(err => {
          console.error('err:', err)
        })
    },
    /**
     * @param category 'SC':中心, 'SL':专线，'AG': 业务小组
     */
    getOrgAuto (category, parentId) {
      const type = this.orgType
      WfmOrgAPI.orgTreeAuth({ parentId, type })
        .then(({ data }) => {
          if (data.status === 'success') {
            this['data' + category] = data.data
            switch (category) {
              case 'SC':
                if (data.data && data.data[0]) {
                  const obj = data.data[0]
                  this.subCenter = obj.name
                  this.resObj.sc = obj
                  this.getOrgAuto('SL', obj.id)
                  this.$emit('on-select-sub-center', obj.id, obj)
                }
                break
              case 'SL':
                if (data.data && data.data[0]) {
                  const obj = data.data[0]
                  this.specialLine = obj.name
                  this.resObj.sl = obj
                  this.getOrgAuto('AG', data.data[0].id)
                  this.$emit('on-select-special-line', obj.id, obj)
                }
                break
              case 'AG':
                if (data.data && data.data.length > 0) {
                  let teamId = this.$store.state.user.teamId
                  var obj = null
                  if (teamId) {
                    teamId = 't_' + teamId
                    for (let i = 0; i < data.data.length; i++) {
                      if (data.data[i].id === teamId) {
                        obj = data.data[i]
                        break
                      }
                    }
                  } else {
                    obj = data.data[0]
                  }

                  this.adminGroup = obj.name
                  this.resObj.ag = obj
                  this.visibleAG = false
                  this.$emit(
                    'on-select-admin-group',
                    obj.id,
                    obj,
                    this.autoSearch
                  )
                }
                this.clear()
                //this.$emit('do-select-search')
            }
          }
        })
        .catch(err => {
          // console.error('WfmOrgAPI.orgTreeAuth:', err)
          this.$emit('on-get-org-err', err)
        })
    },
    renderSC (h, { root, node, data }) {
      return h(
        'span',
        {
          class: 'advanced-search-item',
          style: {
            cursor: 'pointer'
          },
          on: {
            click: () => {
              //console.log(data);
              this.subCenter = data.name
              this.resObj.sc = data
              this.visibleSC = false
              this.getOrg('SL', data.id)
              this.$emit('on-select-sub-center', data.id, data)
            }
          }
        },
        data.name
      )
    },
    renderSL (h, { root, node, data }) {
      return h(
        'span',
        {
          class: 'advanced-search-item',
          style: {
            cursor: 'pointer'
          },
          on: {
            click: () => {
              this.specialLine = data.name
              this.resObj.sl = data
              this.visibleSL = false
              this.getOrg('AG', data.id)
              this.$emit('on-select-special-line', data.id, data)
            }
          }
        },
        data.name
      )
    },
    renderAG (h, { root, node, data }) {
      return h(
        'span',
        {
          class: 'advanced-search-item',
          style: {
            cursor: 'pointer'
          },
          on: {
            click: () => {
              this.adminGroup = data.name
              this.resObj.ag = data
              this.visibleAG = false
              this.$emit('on-select-admin-group', data.id, data)
            }
          }
        },
        data.name
      )
    },
    clear () {
      console.log(this.dataAG)
      this.resObj.ag = {}
      this.resObj.sl = {}
      this.subCenter = '中心'
      this.specialLine = '专线'
      this.adminGroup = '业务小组'
      // this.dataSC = []
      this.dataSL = []
      this.dataAG = []
      this.$emit('on-confirm', this.resObj)
      this.$emit('on-clear')
    },
    confirm () {
      this.$emit('on-confirm', this.resObj)
      this.advancedSearch = false
      this.$emit('do-select-search')
    }
  }
}
</script>

<style lang="less" scoped>
.align-left {
  text-align: left;
}

.advanced-search {
  /deep/.ivu-tree {
    .advanced-search-item {
      padding: 4px;
      border-radius: 4px;
      &:hover {
        background: fade(@primary-color, 20%);
      }
    }
  }
}
</style>
