<template>
  <div
    v-if="permission != 'n'"
    :class="[
      'inputs',
      formInputsDisplay == 'block'
        ? 'ht-form-inputs__block'
        : 'ht-form-inputs__inline',
    ]"
  >
    <ht-post-selector
      v-model="value"
      :title="title"
      :form-inputs-display="formInputsDisplay"
      :validate="validate"
      :name="name"
      :data-vv-as="name"
      :placeholder="placeholder"
      :permission="permission_sub"
      :single="single"
      :config="config"
      :data="data"
      :table-columns="tableColumns"
      :pagination="pagination"
      :demensions="demensions"
      :default-demension="defaultDemension"
      :orgs="orgs"
      :append-to-body="appendToBody"
      :show-switch-dimension="showSwitchDimension"
      select-label="name"
      :quick-search-props="quickSearchProps"
      :mode="mode"
      :current-policy-id="currentPolicyId"
      :disabled="
        disabled ||
        (permission && permission === 'd') ||
        (permission_sub && permission_sub === 'd')
      "
      :filter-type="filterType"
      :range="range"
      :is-validate="isValidate"
      :hyperlink="hyperlink"
      :is-sub-cell-table="isSubCellTable"
      :is-print-mode="isPrintMode"
      @filter-type-change="handleFilterTypeChange"
      @valueChange="valueChange"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @load-org-post="loadOrgPost"
      @load-policy-post="loadPolicyPost"
      @change="handleChange"
      @row-click="(row) => $emit('row-click', row)"
      @clear="() => $emit('clear')"
      @select-data="(data) => $emit('select-data', data)"
      @load-post-byorganddemension="loadPostByOrgAndDemension"
    >
      <template v-slot:mobile-right-icon>
        <slot name="mobile-right-icon"></slot>
      </template>
    </ht-post-selector>
  </div>
</template>
<script>
  import utils from '@/utils.js'
  import permission from '@/mixins/permission.js'
  import inputName from '@/mixins/inputName.js'
  import form from '@/mixins/form.js'
  import mobileMode from '@/mixins/mobileMode.js'
  import policy from '@/mixins/policy.js'

  export default {
    name: 'HtPostSelectorInput',
    mixins: [permission, inputName, form, mobileMode, policy],
    props: {
      value: String,
      single: Boolean,
      config: Object,
      appendToBody: {
        type: Boolean,
        default: false,
      },
      selectCurrent: Boolean,
      title: {
        type: String,
        default: '选择岗位',
      },
      showSwitchDimension: {
        type: Boolean,
        default: true,
      },
      pageSize: {
        type: Number,
        default: 20,
      },
      quickSearchProps: {
        type: String,
        default: 'p.pos_name_,p.code_,o.path_name_',
      },
      range: {
        type: Object,
        default: () => {},
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      hyperlink: Object,
      isValidate: {
        type: Boolean,
        default: false,
      },
      isSubCellTable: {
        // 开启了省略加载的子表==2
        type: [String, Number],
      },
    },
    data() {
      return {
        data: [],
        demensions: [],
        defaultDemension: null,
        orgs: [],
        tableColumns: [
          { prop: 'name', label: '名称' },
          { prop: 'code', label: '编码' },
          { prop: 'orgName', label: '所属组织' },
        ],
        orgLength: 0,
        createQuery: {},
        mode: null, // 搜索模式
        filterType: 'org', //过滤类型(org:组织，policy:策略)
        currentGroup: null,
        currentOrg: null,
        currentPolicy: null,
        searchWord: null,
        pagination: {
          page: 1,
          pageSize: this.pageSize,
          total: 0,
          showTotal: true,
        },
        currentPolicyId: '',

        currentDemId: null,
        currentParentId: '0',
      }
    },
    mounted() {
      if (!this.value && this.selectCurrent) {
        this.$requestConfig.getCurrentUser('post').then((currentUserPost) => {
          this.initCurrentPost(currentUserPost)
        })
      }
      if (this.range && this.range.type) {
        this.filterType = this.range.type
        this.mode = 'search'
        switch (this.filterType) {
          case 'org':
            this.getCurrentOrgPath()
            break
          case 'policy':
            this.currentPolicyId = this.range.policy
            this.loadUserWithPolicy(this.currentPolicyId, (param) => {
              this.loadPolicyPost(param, this.pagination.page)
            })
            break
        }
      } else {
        if (!this.data || this.data.length == 0) {
          this.handleLoad()
        }
      }
    },
    methods: {
      initCurrentPost(post) {
        post && post.postName && this.$emit('input', post.postName)
        if (post && this.config) {
          // 配置了id的绑定关系，则回填到指定属性上
          if (this.config.hasOwnProperty('id')) {
            utils.setValueByConfigKey(this, this.config, 'id', post.postId)
          }
          // 配置了code的绑定关系，则回填到指定的属性上
          if (this.config.hasOwnProperty('code')) {
            utils.setValueByConfigKey(this, this.config, 'code', post.postCode)
          }
          // 配置了name的绑定关系，则回填到指定的属性上
          if (this.config.hasOwnProperty('name')) {
            utils.setValueByConfigKey(this, this.config, 'name', post.postName)
          }
        }
      },
      valueChange(value) {
        this.$emit('input', value)
      },
      handleChange(data) {
        this.$emit('change', data)
      },
      handleSearch(word) {
        if (!word || !word.trim()) {
          this.handleReset()
          return
        }
        // 存储搜索关键词
        this.searchWord = word
        // 进入搜索模式
        this.mode = 'search'
        this.handleLoad()
      },
      handleReset() {
        // 置空搜索关键词
        this.searchWord = null
        // 退出搜索模式
        if (this.range && this.range.type) {
          this.mode = 'search'
          this.getPostDataByFilterType()
        } else {
          this.mode = null
          this.handleLoad()
        }
      },
      handlePageChange(page) {
        const isFilter = this.range && this.range.type
        // 搜索模式下或者未进行过滤时，查询所有数据
        if (this.mode != 'filter' && !isFilter) {
          this.handleLoad(page)
        } else {
          // 过滤模式下，根据过滤类型查询数据
          this.getPostDataByFilterType(page)
        }
      },
      getPostDataByFilterType(page) {
        switch (this.filterType) {
          case 'org':
            this.loadOrgPost(this.currentOrg, page)
            break
          case 'policy':
            this.loadPolicyPost(this.currentPolicy, page)
            break
        }
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.handlePageChange(this.pagination.page)
      },
      // 处理过滤类型变化的事件
      handleFilterTypeChange(type) {
        this.filterType = type
      },
      getQueryFilter(page) {
        const queryFilter = {
          querys: [
            {
              property: 'p.show_status_',
              value: '1',
              group: 'main2',
              operation: 'EQUAL',
              relation: 'AND',
            },
          ],
          pageBean: this.getPageBean(page),
        }

        if (
          this.quickSearchProps &&
          this.quickSearchProps.constructor == String &&
          this.searchWord
        ) {
          const props = this.quickSearchProps.split(',')
          props.forEach((item) => {
            let query = {
              property: item,
              value: this.searchWord,
              group: 'main',
              operation: 'LIKE',
              relation: 'OR',
            }
            queryFilter.querys.push(query)
          })
        }
        return queryFilter
      },
      // 获取查询参数中的分页信息(不传page时默认查询第一页)
      getPageBean(page) {
        const pageBean = { ...this.pagination }
        delete pageBean['total']
        pageBean.page = page || 1
        return pageBean
      },
      handleLoad(page) {
        const param = this.getQueryFilter(page)
        this.data = this.data || []
        if (this.range && this.range.type) {
          this.getPostDataByFilterType(page)
        } else {
          this.loadAllPost(param)
        }
      },
      // 加载全部岗位
      loadAllPost(param) {
        if (
          this.isMobile &&
          this.mode != 'search' &&
          this.filterType == 'org'
        ) {
          this.loadAllPostMobile(param)
          return
        }

        this.$requestConfig.getPostList(param).then((data) => {
          const { rows, page, pageSize, total } = data
          if (this.isMobile && page > 1) {
            this.data = this.data.concat(rows)
          } else {
            this.data = rows
          }
          const paginationResult = { page, pageSize, total }
          this.$set(this, 'pagination', paginationResult)
        })
      },

      // [移动端]加载全部岗位
      async loadAllPostMobile(option) {
        const pageBean = this.getPageBean(
          option.pageBean.page ? option.pageBean.page : option.page
        )
        const params = {
          demId: this.currentDemId,

          parentId: this.currentParentId,
          showStatus: '1',
        }

        const res = await this.$requestConfig.getByParentAndPostPage({
          pageBean,
          params,
        })

        const { rows, pageSize, total } = res

        if (this.isMobile && res.page > 1) {
          this.data = this.data.concat(rows)
        } else {
          this.data = rows
        }
        const paginationResult = {
          page: res.page,
          pageSize,
          total,
        }
        this.$set(this, 'pagination', paginationResult)
      },

      setMode() {
        this.mode = this.range && this.range.type ? 'search' : 'filter'
      },
      // 通过组织查询岗位
      loadOrgPost(org, page) {
        this.setMode()
        this.currentOrg = org
        let queryFilter = {
          pageBean: this.getPageBean(page),
          querys: [
            {
              property: 'p.show_status_',
              value: '1',
              group: 'main2',
              operation: 'EQUAL',
              relation: 'AND',
            },
          ],
        }
        if (this.range && this.range.type && this.searchWord) {
          const param = this.getQueryFilter(page)
          if (param) {
            queryFilter.querys = [...param.querys]
          }
        }
        if (org.path) {
          if (typeof org.path === 'string') {
            queryFilter.querys.push({
              property: 'path_',
              value: org.path,
              group: 'main',
              operation: 'RIGHT_LIKE',
              relation: 'AND',
            })
          } else if (Array.isArray(org.path)) {
            const query = org.path.map((item) => {
              return {
                property: 'o.path_',
                value: item,
                group: 'orgGroup',
                operation: 'RIGHT_LIKE',
                relation: 'OR',
              }
            })
            queryFilter.querys = queryFilter.querys.concat(query)
          }
        }
        if (org.id && Array.isArray(org.id)) {
          const idQuerys = org.id.map((item) => {
            return {
              property: 'o.id_',
              value: item,
              group: 'orgGroup',
              operation: 'EQUAL',
              relation: 'OR',
            }
          })
          queryFilter.querys = queryFilter.querys.concat(idQuerys)
        }
        this.loadAllPost(queryFilter)
      },

      //移动端 通过组织和维度查询岗位
      async loadPostByOrgAndDemension(option, fn) {
        this.currentDemId = option.demId
        this.currentParentId = option.parentId

        const pageBean = this.getPageBean(option.page)

        const params = {
          demId: option.demId,
          parentId: option.parentId,
          showStatus: '1',
        }

        const res = await this.$requestConfig.getByParentAndPostPage({
          pageBean,
          params,
        })

        const { rows, pageSize, total } = res

        if (this.isMobile && res.page > 1) {
          this.data = this.data.concat(rows)
        } else {
          this.data = rows
        }
        const paginationResult = {
          page: res.page,
          pageSize,
          total,
        }
        this.$set(this, 'pagination', paginationResult)
        fn && fn()
      },

      // 通过策略查询岗位
      loadPolicyPost(params, page) {
        this.setMode()
        if (!params) return
        this.currentPolicy = params
        let queryFilter = {
          pageBean: this.getPageBean(page),
          querys: [
            {
              property: 'p.show_status_',
              value: '1',
              group: 'main2',
              operation: 'EQUAL',
              relation: 'AND',
            },
          ],
        }
        let group = 'main'
        if (this.range && this.range.type && this.searchWord) {
          group = 'policyGroup'
          const param = this.getQueryFilter(page)
          if (param) {
            queryFilter.querys = [...param.querys]
          }
        }
        let query = null
        const { type, ids, paths } = params
        switch (type) {
          // 所在主部门
          case '1':
            query = {
              property: 'o.id_',
              value: params.id,
              group: group,
              operation: 'EQUAL',
              relation: 'AND',
            }
            queryFilter.querys.push(query)
            this.loadAllPost(queryFilter)
            break
          // 所在主部门及下级部门
          case '2':
            query = {
              property: 'o.path_',
              value: params.path,
              group: group,
              operation: 'RIGHT_LIKE',
              relation: 'AND',
            }
            queryFilter.querys.push(query)
            this.loadAllPost(queryFilter)
            break
          // 所在部门
          case '3':
            ids.forEach((id) => {
              query = {
                property: 'o.id_',
                value: id,
                group: group,
                operation: 'EQUAL',
                relation: 'OR',
              }
              queryFilter.querys.push(query)
            })
            this.loadAllPost(queryFilter)
            break
          // 所在部门及下级部门
          case '4':
            paths.forEach((path) => {
              query = {
                property: 'o.path_',
                value: path,
                group: group,
                operation: 'RIGHT_LIKE',
                relation: 'OR',
              }
              queryFilter.querys.push(query)
            })
            this.loadAllPost(queryFilter)
            break
        }
        if (params && params.data == 'noCurrentPolicy') {
          this.data = []
        }
      },
      //根据组织code获取组织path和id
      getCurrentOrgPath() {
        const codes = this.range.orgs.map((item) => item.code)
        const codeConfig = this.range.orgs.reduce((pre, cur) => {
          pre[cur.code] = cur.isCurrentAndLowerLevel
          return pre
        }, {})
        this.$requestConfig.getOrgPathByCodes(codes).then((res) => {
          const orgPath = []
          const orgIds = []
          if (res && res.length) {
            res.map((item) => {
              if (codeConfig[item.code]) {
                orgPath.push(item.path)
              } else {
                orgIds.push(item.id)
              }
            })
          }
          this.loadOrgPost({ path: orgPath, id: orgIds }, this.pagination.page)
        })
      },
    },
  }
</script>
