<template>
  <Poptip
    :disabled="disabled"
    :transfer="false"
    class="advanced-search"
    @on-popper-hide="close"
    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>
        <br v-if="showMore" />
        <Poptip placement="right-start" title="司龄" v-if="showMore" v-model="visibleCA">
          <Button style="width: 150px; margin-bottom: 4px;">
            {{compAge}}
            <Icon type="ios-arrow-forward" />
          </Button>
          <div slot="content">
            <Tree :data="dataCA" @on-select-change="selectCA"></Tree>
          </div>
        </Poptip>
        <br v-if="showMore" />
        <Poptip placement="right-start" title="业务线" v-if="showMore" v-model="visibleBL">
          <Button style="width: 150px; margin-bottom: 4px;">
            {{buzLine}}
            <Icon type="ios-arrow-forward" />
          </Button>
          <div slot="content">
            <Tree :data="dataBL" @on-select-change="selectBL"></Tree>
          </div>
        </Poptip>
      </div>
      <Row justify="end" style="margin-top: 8px;" type="flex">
        <Button @click="clear" size="small" v-if="clearable">清空</Button>
        <Button @click="close" 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'
import configValue from '@conf/index'
export default {
  name: 'advanced-search',
  data () {
    return {
      advancedSearch: false,
      subCenter: '中心',
      specialLine: '专线',
      adminGroup: '业务小组',
      compAge: '司龄',
      buzLine: '业务线',
      resObj: {
        ag: {},
        sc: {},
        ca: {},
        bl: {},
        sl: {}
      },
      visibleSC: false,
      visibleSL: false,
      visibleAG: false,
      visibleCA: false,
      visibleBL: false,
      dataSC: [],
      dataSL: [],
      dataAG: [],
      dataCA: [
        {
          title: '新员工'
        },
        {
          title: '正式员工'
        }
      ],
      dataBL: []
    }
  },
  props: {
    // 是否显示司龄、业务线
    showMore: {
      type: Boolean,
      default: false
    },
    // 自动加载
    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: 2
    },
    // 是否禁用点击选择
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    getUserType () {
      return this.$store.state.user.userType
    }
  },
  watch: {
    getUserType (newVal) {
      this.getOrgAuto('SC', '') // 初始化加载中心
    }
  },
  created () {
    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.length === 0) {
                  this.specialLine = '专线'
                  this.resObj.sl = {}
                  this.adminGroup = '业务小组'
                  this.resObj.ag = {}
                }
                break
              case 'AG':
                if (data.data.length === 0) {
                  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]) {
                  if (!this.isNoAgent()) {
                    const obj = data.data[0]
                    this.subCenter = obj.name
                    this.resObj.sc = obj
                    this.getOrgAuto('SL', obj.id)
                  }
                }
                break
              case 'SL':
                if (data.data && data.data[0]) {
                  if (!this.isNoAgent()) {
                    const obj = data.data[0]
                    this.resObj.sl = obj
                    this.specialLine = obj.name
                    this.getOrgAuto('AG', data.data[0].id)
                  }
                }
                break
              case 'AG':
                if (data.data && data.data[0]) {
                  if (!this.isNoAgent()) {
                    const obj = data.data[0]
                    this.resObj.ag = obj
                    this.adminGroup = obj.name
                    this.visibleAG = false
                    this.$emit('on-confirm', this.resObj)
                    this.$emit('invokeDoSearch')
                  }
                }
            }
          }
        })
        .catch(err => {
          console.error('err:', err)
        })
    },
    renderSC (h, { root, node, data }) {
      return h(
        'span',
        {
          class: 'advanced-search-item',
          style: {
            cursor: 'pointer'
          },
          on: {
            click: () => {
              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, this.resObj)
            }
          }
        },
        data.name
      )
    },
    selectCA (arr, obj) {
      this.compAge = obj.title
      this.resObj.ca = obj
      this.visibleCA = false
      this.$emit('on-select-comp-age', obj, arr)
    },
    selectBL (arr, obj) {
      this.buzLine = obj.title
      this.resObj.bl = obj
      this.visibleBL = false
      this.$emit('on-select-buz-line', obj, arr)
    },
    clear () {
      this.resObj = {
        sc: {},
        sl: {},
        ag: {},
        ca: {},
        bl: {}
      }
      this.subCenter = '中心'
      this.specialLine = '专线'
      this.adminGroup = '业务小组'
      this.compAge = '司龄'
      this.buzLine = '业务线'
      this.dataSL = []
      this.dataAG = []
      this.dataCA = []
      this.dataBL = []
      this.$emit('on-confirm', this.resObj)
      this.$emit('on-clear')

      // this.resObj.ag = {}
      // this.adminGroup = '业务小组'
      // this.dataAG = []
      // this.$emit('on-confirm', this.resObj)
      // this.$emit('on-clear')
    },
    close () {
      this.$emit('on-confirm', this.resObj)
      this.advancedSearch = false
    },
    isNoAgent () {
      let type = this.$store.state.user.userType
      if (
        type === configValue.LEADER_TYPE.ITEAM_AGENT ||
        type === configValue.LEADER_TYPE.ITEAM_LEADER
      ) {
        return false
      } else {
        return true
      }
    }
  }
}
</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>
