<template>
  <div>
    <template v-if="unitData.type==='org'">
      <div class="unit org" @click="unitClick('org')">
        <span class="trangle" :class="{'rotate':unitData.isShow}"><i class="iconfont iconsanjiaoxing"></i></span>
        <el-checkbox v-if="selectType!==2" @change="checkStateChange" v-model="checked"></el-checkbox>
        <span class="unitIcon"><i class="iconfont iconzuzhiwenjian"></i></span>
        {{unitData.name}}
      </div>
      <transition name="el-zoom-in-top">
        <ul v-if="unitData.children.length && unitData.isShow" class="sonList">
          <li v-for="item in unitData.children">
            <template v-if="item.type==='org'">
              <unit-item :unit="item" :selectType="selectType" :selectWay="selectWay"></unit-item>
            </template>
            <template v-if="item.type==='person'">
              <person-item :personData="item" :selectType="selectType" :selectWay="selectWay"></person-item>
            </template>
          </li>
          <li v-if="unitData.pageNumber<unitData.pageCount" @click="loadMorePerson" class="loadMoreBtn">加载更多人员</li>
        </ul>
      </transition>
    </template>
    <template v-if="unitData.type==='person'">
      <person-item :personData="unitData" :selectType="selectType" :selectWay="selectWay"></person-item>
    </template>
    <template v-if="unitData.type==='role'">
      <div @click="unitClick('role')" class="unit role">
        <span class="trangle" :class="{'rotate':unitData.isShow}"><i class="iconfont iconsanjiaoxing"></i></span>
        <span class="unitIcon"><i class="iconfont iconguanliyuan"></i></span>
        {{unitData.name}}
      </div>
      <transition name="el-zoom-in-top">
        <ul v-if="unitData.children.length && unitData.isShow" class="sonList">
          <li v-for="item in unitData.children">
            <person-item :personData="item" :selectType="selectType" :selectWay="selectWay"></person-item>
          </li>
          <li v-if="unitData.pageNumber<unitData.pageCount" @click="loadMorePerson" class="loadMoreBtn">加载更多人员</li>
        </ul>
      </transition>
    </template>
    <template v-if="unitData.type==='post'">
      <div @click="unitClick('post')" class="unit role">
        <span class="trangle" :class="{'rotate':unitData.isShow}"><i class="iconfont iconsanjiaoxing"></i></span>
        <span class="unitIcon"><i class="iconfont iconzhiwei"></i></span>
        {{unitData.name}}
      </div>
      <transition name="el-zoom-in-top">
        <ul v-if="unitData.children.length && unitData.isShow" class="sonList">
          <li v-for="item in unitData.children">
            <person-item :personData="item" :selectType="selectType" :selectWay="selectWay"></person-item>
          </li>
          <li v-if="unitData.pageNumber<unitData.pageCount" @click="loadMorePerson" class="loadMoreBtn">加载更多人员</li>
        </ul>
      </transition>
      <li v-if="unitData.pageNumber<unitData.pageCount" @click="loadMorePerson" class="loadMoreBtn">加载更多人员</li>
    </template>
  </div>
</template>

<script>
  //vuex
  import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
  //通信总线
  import Bus from 'common/js/bus.js'
  //公共混入
  import commonMixin from 'common/js/commonMixin'
  import unitItem from './unitItem'
  import personItem from './personItem'
  import {deepClone} from "common/js/deepClone";

  const PAGE_SIZE = 20

  export default {
    name: "unitItem",
    mixins: [commonMixin],
    data() {
      return {
        checked: false,
        unitData: {}
      }
    },
    props: ['unit', 'selectType', 'selectWay'],
    computed: {},
    watch: {},
    methods: {
      ...mapActions(['fetchPersonList']),
      initFlow() {
        this.unitData = deepClone(this.unit)
        this.$set(this.unitData, 'isShow', false)
        this.$set(this.unitData, 'children', [])
        this.unitData.pageNumber = 1
        this.unitData.pageCount = 0
      },

      unitClick(type) {
        this.unitData.isShow = !this.unitData.isShow
        console.log(1231231)
        //Bus.$emit('toggleDeptShowState', {id: this.unitData._id, type: this.unitData.type})
        if (this.unitData.children && this.unitData.children.length) {
          return
        }
        switch (type) {
          case 'org':
            this.fetchSonDept()
            break;
          case 'role':
            this.loadMorePerson()
            break;
          case 'post':
            this.loadMorePerson()
        }
      },

      //加载更多人
      async loadMorePerson() {
        let personList = await this.loadPerson()
        let targetList = personList.rows
        if (this.unitData.filterDept) {
          targetList = personList.rows.filter(pserson => pserson.dept.deptId === this.unitData.filterDept)
        }
        this.unitData.children = this.unitData.children.concat(this.normalizePersonList(targetList))
      },
      loadPerson() {
        let promise = new Promise(async (resolve, reject) => {
          let payload = {
            orderBy: null,
            orderByColumn: null,
            pageNum: 0,
            pageSize: 0,
            status: 0,
            userId: null,
            userName: null
          }
          if (this.unitData.type === 'org') {
            payload.pageNum = this.unitData.pageNumber + 1
            payload.pageSize = PAGE_SIZE
          }
          // if (this.unitData.filterDept || this.unitData.filterDept === 0) {
          //   payload.deptId = this.unitData.filterDept
          // }
          switch (this.unitData.type) {
            case 'org':
              payload.deptId = this.unitData._id
              break;
            case 'role':
              payload.roleId = this.unitData._id
              break;
            case 'post':
              payload.postId = this.unitData._id
          }
          let result = await this.fetchPersonList(payload)
          this.unitData.pageNumber = result.pageNum
          this.unitData.pageCount = result.totalPageNum
          resolve(result)
        })
        return promise
      },

      //格式化部门列表
      normalizeDeptList(list) {
        if (!list) {
          return []
        }
        list.forEach((subDeptItem) => {
          subDeptItem.type = 'org'
          subDeptItem.name = subDeptItem.deptName
          subDeptItem._id = subDeptItem.deptId.toString()
        })
        return list
      },

      //格式化人员列表
      normalizePersonList(list) {
        if (!list) {
          return []
        }
        list.forEach((personItem) => {
          personItem.type = 'person'
          personItem.name = personItem.userName
          personItem._id = personItem.userId
        })
        return list
      },

      async fetchSonDept() {
        let resp = await this.$axios.get(this.$apiConfig.REQUEST_URL + '/system/dept/getSubOrgAndUsers', {
          params: {
            deptIds: this.unitData._id,
            type: 1
          }
        })

        let personList = await this.loadPerson()
        let personListRows = personList.rows

        this.$apiConfig.resultHandle(resp, (result) => {
          let payload = result.data[0]
          payload.subDeptList = this.normalizeDeptList(payload.subDeptList)
          payload.userList = this.normalizePersonList(personListRows)
          let mixArr = payload.subDeptList.concat(payload.userList)
          this.unitData.children = mixArr
        })
      },
      checkStateChange() {
        Bus.$emit('personListModify', {item: this.unitData, type: this.checked})
      },
    },
    filters: {},
    components: {unitItem, personItem},
    activated() {
    },
    mounted() {
      this.initFlow()
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../mixPicker/mixPicker.styl"

</style>