<template>
  <div class="ibps-fixed-bottom contact">
    <van-sticky>
      <van-nav-bar
        :title="generateTitle()"
      />
      <!-- saerch -->
      <form action="/">
        <van-search
          v-model="search"
          :placeholder="searchPlaceholder"
          @search="onSearchAction"
        />
      </form>
    </van-sticky>
    <!-- data list -->
    <van-cell-group>
      <van-cell class="ibps-root-title contact-nav contact_size">
        <div slot="title">
          <template v-for="(data,index) in pathData">
            <span
              v-if="index == pathData.length-1"
              :key="'pathData'+index"
              class="ibps-color-gary-5"
            >{{ data[labelKey] }}</span>
            <span
              v-else
              :key="'pathData'+index"
              @click="changePath(index)"
            >{{ data[labelKey] }}</span>
            <span v-if="pathData.length-1!==index" :key="index" class="ibps-wingblank ibps-color-gary-5">/</span>
          </template>
        </div>
      </van-cell>

      <van-cell
        v-for="(data,index) in orgList"
        :key="'orgList'+index"
        clickable
        class="ibps-root-content"
        :size="size"
        @click="toggleChild(data,index)"
      >
        <div slot="title">
          {{ data[labelKey] }}
        </div>
        <span
          v-if="data.hasChild"
          slot="right-icon"
        >
          <span class="van-cell__right-icon contact_move">下级</span>
          <van-icon name="arrow " class="van-cell__right-icon" />
        </span>
      </van-cell>
    </van-cell-group>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" @load="loadData">
        <van-cell
          v-for="(item,index) in listData"
          :key="item.id+index"
          :title="item[labelKey]"
          :label="item.orgName"
          class="ibps-flex-c"
          @click="onClick(item)"
        >
          <template slot="icon">
            <ibps-avatar
              :thumb="getPhoto(item['photo'])"
              :thumb-error="errorImage"
              :text="item[labelKey]"
              bg-color="#38f"
              width="33"
              height="33"
              radius="4"
              class="ibps-mr-10"
            />
          </template>
        </van-cell>
        <ibps-list-result-page
          :result-type="resultType"
          :error-type="errorType"
          :result-message="resultMessage"
        />
      </van-list>
    </van-pull-refresh>

    <!--点击明细 -->
    <van-popup v-model="showPopup" class="ibps-fullscreen-popup" position="right">
      <van-nav-bar
        :title="employee.name"
        @click-left="showPopup=false"
      >
        <template #left>
          <van-icon name="cross" class="ibps-nav-bar__close-icon" />
        </template>
      </van-nav-bar>

      <van-cell-group>
        <div class="divider" />
        <van-cell>
          <div slot="title" class="ibps-swipe-button ibps-flex-c contact_size">
            头像
          </div>
          <ibps-avatar
            slot="right-icon"
            :thumb="getPhoto(employee['photo'])"
            :thumb-error="errorImage"
            :text="employee[labelKey]"
            bg-color="#38f"
            round
          />
        </van-cell>
        <van-cell :value="employee.name" title="姓名" clickable :size="size" :value-class="className" :title-class="tClassName" />
        <van-cell :value="employee.gender|sexFilter" title="性别" clickable :size="size" :value-class="className" :title-class="tClassName" />
        <van-cell :value="employee.mobile" title="电话" clickable :size="size" :value-class="className" :title-class="tClassName" />
        <van-cell :value="employee.email" title="邮箱" clickable :size="size" :value-class="className" :title-class="tClassName" />
        <van-cell :value="employee.wcAccount" title="微信" clickable :size="size" :value-class="className" :title-class="tClassName" />
        <van-cell :value="employee.orgName" title="部门" clickable :size="size" :value-class="className" :title-class="tClassName" />
        <van-cell :value="employee.position" title="岗位" clickable :size="size" :value-class="className" :title-class="tClassName" />
      </van-cell-group>
    </van-popup>
  </div>
</template>
<script>
import { queryByOrgIdOrName } from '@/api/platform/org/employee'
import { queryByParentIdOrName } from '@/api/platform/org/org'
import { getPositionByUserId } from '@/api/platform/org/position'
import ActionUtils from '@/utils/action'
import { getFile } from '@/utils/image'
import navbar from '@/mixins/navbar'
import IbpsAvatar from '@/components/ibps-avatar'
import IbpsListResultPage from '@/components/ibps-list-result-page'

export default {
  components: {
    IbpsAvatar,
    IbpsListResultPage
  },
  mixins: [navbar],
  props: {
    valueKey: {
      type: String,
      default: 'id'
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    idKey: {
      type: String,
      default: 'id'
    },
    childrenKey: {
      type: String,
      default: 'children'
    }
  },
  data() {
    return {
      searchPlaceholder: this.$t('common.input'),

      search: '',
      pathData: [],
      orgList: [],

      parentId: '',

      listData: [],
      pagination: {},
      sorts: {},

      loading: false,
      finished: false,
      refreshing: false,
      resultType: 'init',
      errorType: null,
      resultMessage: null,

      employee: {},
      showPopup: false,
      errorImage: this.$baseUrl + 'images/user/default.png',

      size: 'large',
      className: 'contact_size',
      tClassName: 'ibps-flex-c'
    }
  },
  computed: {
    photo() {
      return this.getPhoto(this.employee.photo)
    }
  },
  mounted() {
    this.parentId = '0'
    this.pathData = []
    this.loadOrgdData({
      id: '',
      name: '组织架构'
    })
  },
  methods: {
    loadOrgdData(data, isInit) {
      // 加载
      queryByParentIdOrName(ActionUtils.formatParams({ parentId: this.parentId })).then(res => {
        this.orgList = res.data.dataResult
        data[this.childrenKey] = this.orgList
        this.pathData.push(data)
      }).catch((e) => {
        console.error(e)
      })
    },
    /**
     * 下拉刷新
     */
    onRefresh() {
      this.refreshing = true
      this.finished = false
      this.onSearch()
    },
    /**
     * 查询
     */
    onSearch() {
      ActionUtils.initListData(this)
      this.loadData()
    },
    onSearchAction() {
      this.finished = false
      this.orgList = []
      this.onSearch()
    },
    // 加载用户数据
    loadData() {
      this.loading = true
      queryByOrgIdOrName(this.getSearcFormData()).then(response => {
        // 处理数据
        ActionUtils.handleListData(this, response.data)
      }).catch((e) => {
        // 处理异常
        ActionUtils.handleErrorData(this, e)
      })
    },
    /**
     * 获取格式化参数
     */
    getSearcFormData() {
      const params = {}
      if (this.search) {
        params['name'] = this.search
      }
      if (this.parentId !== '0') {
        params['orgId'] = this.parentId
      }

      return ActionUtils.formatParams(
        params,
        this.pagination,
        this.sorts)
    },
    toggleChild(data) {
      this.parentId = data[this.idKey]
      this.loadOrgdData(data)
      this.onSearch()
    },
    changePath(index) {
      const parentOrg = this.pathData[index]
      this.parentId = parentOrg[this.idKey]
      this.orgList = parentOrg[this.childrenKey]
      this.pathData.splice(index + 1, this.pathData.length - 1)
      this.onSearch()
    },
    getPhoto(photo) {
      if (this.$utils.isNotEmpty(photo)) {
        return getFile(photo)
      } else {
        return
      }
    },
    getOrg(item) {
      if (item.orgName) {
        const nameArr = item.orgName.split('.')
        return nameArr.join(' ')
      }
      return ''
    },
    onClick(item) {
      this.employee = item
      getPositionByUserId({ userId: item.id }).then(response => {
        if (response.data) {
          const positions = response.data
          let position = ''
          for (let index = 0; index < positions.length; index++) {
            const element = positions[index]
            if (position.length > 0) {
              position += ','
            }
            position += element.name
          }
          this.employee.position = position
          this.showPopup = true
        } else {
          this.employee.position = ''
          this.showPopup = true
        }
      }).catch((e) => {
        this.showPopup = true
      })
    }

  }
}
</script>
<style lang="scss" scoped>
  .contact{
    .contact-nav{
      background: #fcfcfc;
      border: 0;
    }
    .contact_size{
      font-size: 16px;
    }
    .divider{
      height:8px;
      background: #f8f8f8;
    }
    .contact_move{
      position: relative;
      top: -3px;
    }
  }

</style>
