<template>
  <div
    v-if="permission != 'n'"
    :class="[
      'inputs',
      formInputsDisplay == 'block'
        ? 'ht-form-inputs__block'
        : 'ht-form-inputs__inline',
    ]"
  >
    <ht-org-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"
      :pagination="pagination"
      :append-to-body="appendToBody"
      :select-label="selectLabel"
      :quick-search-props="quickSearchProps"
      :mode="mode"
      :show-path="showPath"
      :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"
      @change="handleChange"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @load-org="loadOrg"
      @load-policy-org="loadPolicyOrg"
      @clear="() => $emit('clear')"
      @row-click="(row) => $emit('row-click', row)"
      @select-data="(data) => $emit('select-data', data)"
      @load-org-withdemension="loadOrgWithDemension"
    >
      <template v-slot:mobile-right-icon>
        <slot name="mobile-right-icon"></slot>
      </template>
    </ht-org-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'
  import tableFieldReadOnly from '@/mixins/tableFieldReadOnly.js'
  export default {
    name: 'HtOrgSelectorInput',
    mixins: [
      permission,
      inputName,
      form,
      mobileMode,
      policy,
      tableFieldReadOnly,
    ],
    props: {
      value: String,
      single: Boolean,
      config: Object,
      appendToBody: {
        type: Boolean,
        default: false,
      },
      selectCurrent: {
        type: Boolean,
        default: false,
      },
      title: {
        type: String,
        default: '选择组织',
      },
      quickSearchProps: {
        type: String,
        default: 'name,code,pathName',
      },
      pageSize: {
        type: Number,
        default: 20,
      },
      showPath: {
        type: Boolean,
        default: false,
      },
      range: {
        type: Object,
        default: () => {},
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      hyperlink: Object,
      isValidate: {
        type: Boolean,
        default: false,
      },
      isSubCellTable: {
        // 开启了省略加载的子表==2
        type: [String, Number],
      },
    },
    data() {
      return {
        mode: null, // 搜索模式
        filterType: 'org', //过滤类型(org:组织，policy:策略)
        filterVal: null, //策略值
        currentGroup: null,
        currentOrg: null,
        currentPolicy: null,
        searchWord: null,
        data: [],
        pagination: {
          page: 1,
          pageSize: this.pageSize,
          total: 0,
          showTotal: true,
        },

        currentPolicyId: '',

        currentDemId: null,
        currentParentId: 0,
      }
    },
    computed: {
      selectLabel() {
        return this.showPath ? 'pathName' : 'name'
      },
    },
    mounted() {
      // 没有值而且需要显示当前组织
      if (!this.value && this.selectCurrent) {
        this.$requestConfig.getCurrentUser('org').then((currentUserOrg) => {
          this.initCurrentOrg(currentUserOrg)
        })
      }
      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.loadPolicyOrg(param, this.pagination.page)
            })
            break
        }
      } else {
        if (!this.data || this.data.length == 0) {
          this.handleLoad()
        }
      }
    },
    methods: {
      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.filterVal) {
          this.mode = 'search'
          this.getOrgDataByFilterType()
        } 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.getOrgDataByFilterType(page)
        }
      },
      getOrgDataByFilterType(page) {
        switch (this.filterType) {
          case 'org':
            this.loadOrg(this.currentOrg, page)
            break
          case 'policy':
            this.loadPolicyOrg(this.currentPolicy, page)
            break
        }
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.handlePageChange(this.pagination.page)
      },
      // 处理过滤类型变化的事件
      handleFilterTypeChange(type, val) {
        this.filterType = type
        this.filterVal = val
      },
      getQueryFilter(page) {
        const queryFilter = {
          querys: [
            {
              property: 'showStatus',
              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.getOrgDataByFilterType(page)
        } else {
          this.loadAllOrg(param)
        }
      },
      initCurrentOrg(org) {
        if (org && this.config) {
          // 配置了id的绑定关系，则回填到指定属性上
          if (this.config.hasOwnProperty('id')) {
            utils.setValueByConfigKey(this, this.config, 'id', org.orgId)
          }
          // 配置了code的绑定关系，则回填到指定的属性上
          if (this.config.hasOwnProperty('code')) {
            utils.setValueByConfigKey(this, this.config, 'code', org.orgCode)
          }
          // 配置了name的绑定关系，则回填到指定的属性上
          if (this.config.hasOwnProperty('name')) {
            utils.setValueByConfigKey(this, this.config, 'name', org.orgName)
          }
          // 配置了pathName的绑定关系，则回填到指定的属性上
          if (this.config.hasOwnProperty('pathName')) {
            let orgPath = org.pathName
            if (orgPath && orgPath.split('/').filter(Boolean).length > 1) {
              const result = orgPath
                .split('/')
                .filter((item) => item !== org.demName)
              orgPath = result.length && `/${result.join('/')}`
            }
            utils.setValueByConfigKey(this, this.config, 'pathName', orgPath)
          }
        }
        org &&
          setTimeout(() => {
            this.$emit('input', this.showPath ? org.pathName : org.orgName)
          })
      },
      setMode() {
        this.mode = this.range && this.range.type ? 'search' : 'filter'
      },
      // 通过组织查询组织
      loadOrg(org, page, queryData) {
        this.setMode()
        this.currentOrg = org

        let queryFilter = {
          pageBean: this.getPageBean(page),
          querys: [
            {
              property: 'showStatus',
              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: '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: 'id_',
              value: item,
              group: 'orgGroup',
              operation: 'EQUAL',
              relation: 'OR',
            }
          })
          queryFilter.querys = queryFilter.querys.concat(idQuerys)
        }

        if (queryData) {
          queryFilter.querys = queryData
        }

        this.loadAllOrg(queryFilter)
      },

      //移动端 按照维度查询组织
      async loadOrgWithDemension(option, fn) {
        this.currentDemId = option.demId
        this.currentParentId = option.parentId

        const pageBean = this.getPageBean(option.page)

        const querys = [
          {
            property: 'parent_id_',
            value:
              option.parentId == undefined || option.parentId == null
                ? option.parentId
                : option.parentId + '',
            group: 'main',
            operation: 'EQUAL',
            relation: 'AND',
          },
          {
            property: 'dem_id_',
            value: option.demId,
            group: 'main',
            operation: 'EQUAL',
            relation: 'AND',
          },
          {
            property: 'showStatus',
            value: '1',
            group: 'main2',
            operation: 'EQUAL',
            relation: 'AND',
          },
        ]
        const res = await this.$requestConfig.getOrgList({
          pageBean,
          querys,
        })

        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()
      },

      // 通过策略查询组织
      loadPolicyOrg(params, page) {
        this.setMode()
        if (!params) return
        this.currentPolicy = params
        let queryFilter = {
          pageBean: this.getPageBean(page),
          querys: [
            {
              property: 'showStatus',
              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: 'id_',
              value: params.id,
              group,
              operation: 'EQUAL',
              relation: 'AND',
            }
            queryFilter.querys.push(query)
            this.loadAllOrg(queryFilter)
            break
          // 所在主部门及下级部门
          case '2':
            query = {
              property: 'path_',
              value: params.path,
              group,
              operation: 'RIGHT_LIKE',
              relation: 'AND',
            }
            queryFilter.querys.push(query)
            this.loadAllOrg(queryFilter)
            break
          // 所在部门
          case '3':
            ids.forEach((id) => {
              query = {
                property: 'id_',
                value: id,
                group,
                operation: 'EQUAL',
                relation: 'OR',
              }
              queryFilter.querys.push(query)
            })
            this.loadAllOrg(queryFilter)
            break
          // 所在部门及下级部门
          case '4':
            paths.forEach((path) => {
              query = {
                property: 'path_',
                value: path,
                group,
                operation: 'RIGHT_LIKE',
                relation: 'OR',
              }
              queryFilter.querys.push(query)
            })
            this.loadAllOrg(queryFilter)
            break
        }
        if (params && params.data == 'noCurrentPolicy') {
          this.data = []
        }
      },
      // 加载全部组织
      loadAllOrg(param) {
        if (
          this.isMobile &&
          this.mode != 'search' &&
          this.filterType == 'org'
        ) {
          if (this.currentParentId >= 0) {
            param.querys.push({
              property: 'parent_id_',
              value: this.currentParentId + '',
              group: 'main',
              operation: 'EQUAL',
              relation: 'AND',
            })
          }

          if (this.currentDemId) {
            param.querys.push({
              property: 'dem_id_',
              value: this.currentDemId,
              group: 'main',
              operation: 'EQUAL',
              relation: 'AND',
            })
          }
        }
        this.$requestConfig.getOrgList(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)
        })
      },
      valueChange(value) {
        this.$emit('input', value)
      },
      handleChange(data) {
        this.$emit('change', 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.loadOrg({ path: orgPath, id: orgIds }, this.pagination.page)
        })
      },
    },
  }
</script>
