<template>
  <div
    v-if="permission != 'n'"
    :class="[
      'inputs',
      formInputsDisplay == 'block'
        ? 'ht-form-inputs__block'
        : 'ht-form-inputs__inline',
    ]"
  >
    <ht-user-selector
      ref="userSelectorEl"
      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"
      :is-public="isPublic"
      :pagination="pagination"
      :append-to-body="appendToBody"
      select-label="fullname"
      :quick-search-props="quickSearchProps"
      :mode="mode"
      :current-policy-id="currentPolicyId"
      :current-role-id="currentRoleId"
      :filter-type="filterType"
      :disabled="
        disabled ||
        (permission && permission === 'd') ||
        (permission_sub && permission_sub === 'd')
      "
      :range="range"
      :is-validate="isValidate"
      :hyperlink="hyperlink"
      :is-sub-cell-table="isSubCellTable"
      :max-length="maxLength"
      :is-print-mode="isPrintMode"
      @filter-type-change="handleFilterTypeChange"
      @valueChange="valueChange"
      @change="handleChange"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @contact-group-change="loadContactUser"
      @load-org-user="loadOrgUser"
      @load-policy-user="loadPolicyUser"
      @load-role-user="loadRoleUser"
      @load-org="loadOrg"
      @clear="() => $emit('clear')"
      @row-click="(row) => $emit('row-click', row)"
      @select-data="(data) => $emit('select-data', data)"
    >
      <template v-slot:mobile-right-icon>
        <slot name="mobile-right-icon"></slot>
      </template>
    </ht-user-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: 'HtUserSelectorInput',
    mixins: [permission, inputName, form, mobileMode, policy],
    props: {
      value: String,
      single: Boolean,
      config: Object,
      appendToBody: {
        type: Boolean,
        default: true,
      },
      selectCurrent: {
        type: Boolean,
        default: false,
      },
      title: {
        type: String,
        default: '选择用户',
      },
      quickSearchProps: {
        type: String,
        default: 'fullname,account',
      },
      // 自定义参数
      customParams: {
        type: Object,
        default: () => ({}),
      },
      pageSize: {
        type: Number,
        default: 20,
      },
      range: {
        type: Object,
        default: () => {},
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      hyperlink: Object,
      isValidate: {
        type: Boolean,
        default: false,
      },
      isSubCellTable: {
        // 开启了省略加载的子表==2
        type: [String, Number],
      },
      maxLength: {
        // 最大选中长度
        type: Number,
        default: 0,
      },
    },
    data() {
      return {
        mode: null, // 搜索模式
        filterType: 'contact', //过滤类型(contact:联系人，org:组织，policy:策略，role:角色)
        currentGroup: null,
        currentOrg: null,
        currentPolicy: null,
        currentRole: null,
        searchWord: null,
        data: [],
        pagination: {
          page: 1,
          pageSize: this.pageSize,
          total: 0,
          showTotal: true,
        },
        currentPolicyId: '',
        currentRoleId: '',

        currentDemId: null,
        currentParentId: 0,
      }
    },
    mounted() {
      if (this.range && this.range.type) {
        this.queryRangeData()
      } else {
        if (!this.data || this.data.length == 0) {
          this.handleLoad()
        }
      }
      // 没有值而且需要显示当前用户
      if (!this.value && this.selectCurrent) {
        this.$requestConfig.getCurrentUser().then((currentUserDetail) => {
          this.initCurrentValue(currentUserDetail)
        })
      }
    },
    methods: {
      // 获取过滤的数据
      queryRangeData() {
        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.loadPolicyUser(param)
            })
            break
          case 'role':
            this.getRoleIdByCodes()
            break
        }
      },
      handleSearch(word) {
        if (!word || !word.trim()) {
          this.mode = null
          this.handleReset()
          return
        }

        // 存储搜索关键词
        this.searchWord = word
        // 进入搜索模式
        this.mode = 'search'

        if (this.range && this.range.type) {
          this.queryRangeData()
        } else {
          this.handleLoad()
        }
      },
      handleReset() {
        // 置空搜索关键词
        this.searchWord = null
        // 退出搜索模式

        if (this.range && this.range.type) {
          this.queryRangeData()
        } else if (this.mode != 'search' && this.filterType) {
          this.getUserDataByFilterType()
        } else {
          this.handleLoad()

          this.mode = null
        }
      },
      handlePageChange(page) {
        const isFilter = this.range && this.range.type
        // 搜索模式下或者未进行过滤时，查询所有数据
        if (this.mode != 'filter' && !isFilter) {
          this.handleLoad(page)
        } else {
          // 过滤模式下，根据过滤类型查询数据
          this.getUserDataByFilterType(page)
        }
      },
      getUserDataByFilterType(page) {
        if (this.range && this.range.type) {
          this.filterType = this.range.type
        }
        switch (this.filterType) {
          case 'contact':
            this.loadContactUser(this.currentGroup, page)
            break
          case 'org':
            this.loadOrgUser(this.currentOrg, page)
            break
          case 'policy':
            this.loadPolicyUser(this.currentPolicy, page)
            break
          case 'role':
            this.loadRoleUser(this.currentRole, page)
            break
        }
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.handlePageChange(this.pagination.page)
      },
      // 处理过滤类型变化的事件
      handleFilterTypeChange(type) {
        this.filterType = type
      },
      getQueryFilter(page) {
        const queryFilter = {
          querys: [
            {
              property: 'uu.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)
          })
        }

        this.setQueryParams(queryFilter)
        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.getUserDataByFilterType(page)
        } else {
          this.loadAllUser(param)
        }
      },
      initCurrentValue(user) {
        this.$emit('input', user.fullname)
        // 同时更新绑定的字段
        if (this.config) {
          // 配置了id的绑定关系，则回填到指定属性上
          if (this.config.hasOwnProperty('id')) {
            utils.setValueByConfigKey(this, this.config, 'id', user.id)
          }
          // 配置了fullname的绑定关系，则回填到指定的属性上
          if (this.config.hasOwnProperty('fullname')) {
            utils.setValueByConfigKey(
              this,
              this.config,
              'fullname',
              user.fullname
            )
          }
          // 配置了account的绑定关系，则回填到指定的属性上
          if (this.config.hasOwnProperty('account')) {
            utils.setValueByConfigKey(
              this,
              this.config,
              'account',
              user.account
            )
          }
          if (this.config.hasOwnProperty('mobile')) {
            utils.setValueByConfigKey(this, this.config, 'mobile', user.mobile)
          }
          if (this.config.hasOwnProperty('email')) {
            utils.setValueByConfigKey(this, this.config, 'email', user.email)
          }
        }
      },
      // 加载全部用户
      loadAllUser(param) {
        this.$requestConfig.getUserList(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)
        })
      },
      //设置自定义传参
      setQueryParams(params) {
        params.querys = params.querys || []
        if (Object.keys(this.customParams).length > 0) {
          return (params.querys = params.querys.concat(this.customParams))
        }
      },
      // 加载常用联系人
      loadContactUser(group, page) {
        let contactGroupId
        this.setMode()
        this.currentGroup = group
        const queryFilter = {
          querys: [],
        }
        this.setQueryParams(queryFilter)
        if (group == 'recently') {
          // 查找最近联系人
          this.$requestConfig
            .queryUserWithSelectorLog(this.isMobile, queryFilter)
            .then((data) => {
              this.data = data.rows
              const total = data.rows ? data.rows.length : 0
              const page = null
              const pageSize = data.pageSize
              if (pageSize > 0) {
                this.$set(this, 'pagination', { page, pageSize, total })
              }
            })
          return
        }
        if (group != 'all') {
          contactGroupId = group
        }
        if (this.$requestConfig.getContactUser) {
          console.log('123456')
          const param = {
            pageBean: this.getPageBean(page),
          }
          this.setQueryParams(param)
          this.$requestConfig
            .getContactUser(param, contactGroupId)
            .then((data) => {
              if (data.state && data.value) {
                const { rows, page, pageSize, total } = data.value
                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)
      },
      setMode() {
        this.mode = this.range && this.range.type ? 'search' : 'filter'
      },
      // 通过组织查询用户
      loadOrgUser(org, page) {
        this.setMode()

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

      //查询组织
      async loadOrg(option, page, fn) {
        this.currentDemId = option.demId
        this.currentParentId = option.parentId

        const pageBean = this.getPageBean(page)

        const params = {
          ...{
            // demId: '1258608622670319616',
            // parentId: '0',
            dataType: 'all',
            isCountUser: true,
            showStatus: '1',
          },
          ...option,
        }

        const queryFilter = {
          pageBean,
          params,
        }
        this.setQueryParams(queryFilter)
        const res = await this.$requestConfig.getByParentAndUserPage(
          queryFilter
        )

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

      // 按照角色查询用户
      loadRoleUser(role, page) {
        this.setMode()
        this.currentRole = role
        let queryFilter = {
          pageBean: this.getPageBean(page),
          querys: [
            {
              property: 'uu.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 (role) {
          if (this.range && this.range.type) {
            queryFilter.params = {
              roleIds: role.split(','),
            }
          } else {
            queryFilter.params = {
              role_id_: role,
            }
          }
        }
        this.setQueryParams(queryFilter)
        this.loadAllUser(queryFilter)
      },
      // 通过策略查询用户
      loadPolicyUser(params, page) {
        this.setMode()
        if (!params) return
        this.currentPolicy = params
        let queryFilter = {
          pageBean: this.getPageBean(page),
          querys: [
            {
              property: 'uu.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]
          }
        }

        this.setQueryParams(queryFilter)
        let query = null
        const { type, ids, paths } = params
        switch (type) {
          // 所在主部门
          case '1':
            query = {
              property: 'uo.id_',
              value: params.id,
              group: group,
              operation: 'EQUAL',
              relation: 'AND',
            }
            queryFilter.querys.push(query)
            this.loadAllUser(queryFilter)
            break
          // 所在主部门及下级部门
          case '2':
            query = {
              property: 'uo.path_',
              value: params.path,
              group: group,
              operation: 'RIGHT_LIKE',
              relation: 'AND',
            }
            queryFilter.querys.push(query)
            this.loadAllUser(queryFilter)
            break
          // 所在部门
          case '3':
            ids.forEach((id) => {
              query = {
                property: 'uo.id_',
                value: id,
                group: group,
                operation: 'EQUAL',
                relation: 'OR',
              }
              queryFilter.querys.push(query)
            })
            this.loadAllUser(queryFilter)
            break
          // 所在部门及下级部门
          case '4':
            paths.forEach((path) => {
              query = {
                property: 'uo.path_',
                value: path,
                group: group,
                operation: 'RIGHT_LIKE',
                relation: 'OR',
              }
              queryFilter.querys.push(query)
            })
            this.loadAllUser(queryFilter)
            break
        }
        if (params && params.data == 'noCurrentPolicy') {
          this.data = []
        }
      },
      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.loadOrgUser({ path: orgPath, id: orgIds }, this.pagination.page)
        })
      },
      //根据角色code获取角色id
      getRoleIdByCodes() {
        const codeList = this.range.roles.split(',')
        this.currentRoleId = ''
        this.$requestConfig.getRoleIds(codeList).then((res) => {
          if (res && res.length) {
            this.currentRoleId = res.join(',')
            this.loadRoleUser(this.currentRoleId, this.pagination.page)
          }
        })
      },
    },
  }
</script>
