<template>
  <div class="addExaminationUserSelect-com">
    <el-select
      v-model="userValue"
      multiple
      filterable
      :remote="remote"
      :remote-method="remoteLoadUsers"
      :allow-create="false"
      @change="change"
    >
      <el-option
        v-for="n in userListOptions"
        :key="n.value"
        :label="n.label"
        :value="n.value"
      />
    </el-select>
  </div>
</template>

<script>
import { getSignAddUserScope } from '@/api/workflow/process.js'
import { getAllUsers, getContextUsers, getUsersInOrgs, getUsersByAccount, getUserOrganizations, findInUserSameIndependentOrg } from '@/api/workflow/userSystem'
import { getInstancePbo } from '@/api/workflow/userSettings.js'

export default {
  name: 'AddExaminationUserSelect',
  components: { },
  props: {
    scope: {
      type: Object,
      default: null
    },
    instData: {
      type: Object,
      default: null
    },
    itemObj: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      userValue: [],
      remote: false,
      userListOptions: [],
      businessObject: null,
      partData: {}
    }
  },
  computed: {
    typeEnum() {
      return this.$utils._get(this.itemObj, 'component.props.typeEnum') || ''
    }
  },
  watch: {
    'scope.row': {
      immediate: true,
      handler: function(val) {
        val && this.initData(val)
      },
      deep: true
    },
    instData: {
      immediate: true,
      handler: function(val) {
        val && this.initData(val)
      },
      deep: true
    }
  },
  methods: {
    resetForm() {
      for (const key in this.form) {
        if (this.form[key]) {
          this.$set(this.form, key, '')
        }
      }
    },
    getUser(item, query) {
      if (item.scope === 'ALL') {
        this.remoteMethod(query)
      } else if (item.scope === 'PBO_CONTEXT_TEAM') {
        this.getContextUser(query, item)
      } else if (item.scope === 'PBO_VARIABLE') {
        this.getAllUser(item.scopeValues)
      } else if (item.scope === 'GROUP') {
        this.getGroupUser(item.scopeValues)
      } else if (item.scope === 'SAME_INDEPENDENT_ORG') {
        this.remoteSameIndependentOrgMethod()
      } else {
        const value = item.scope === 'SAME_ORGANIZATION' ? this.getCurrentUserOrgIds() : item.scopeValues
        value && this.getOrgUser(value, query)
      }
    },
    // 获取所有用户
    getAllUser(userArr) {
      const params = {
        'indices': [
          'USERS'
        ],
        'pageFrom': 1,
        'pageSize': 100,
        'openProps': [
          {
            'name': 'userAccounts',
            'pageFrom': 1,
            'pageSize': 9999
          }
        ],
        'sortItem': [
          {
            'fieldName': 'modifyTime',
            'sortOrder': 'desc'
          }
        ],
        'keyWord': null,
        'searchItems': {
          'operator': 'AND',
          'items': []
        }
      }
      if (userArr && userArr.length) {
        params.searchItems.children = [
          {
            'items': [
              {
                'fieldName': 'id',
                'operator': 'IN',
                'value': userArr
              }
            ]
          }
        ]
      }
      getAllUsers(params).then(res => {
        const items = res.items.content
        const userListOptions = items.map(item => {
          return {
            label: item.userName + '(' + item.userAccount + ')',
            value: item.id,
            style: { display: 'block' }
          }
        })
        this.filterData(userListOptions)
      })
    },
    remoteLoadUsers(query) {
      clearTimeout(this.remoteLoadUsers.timer)
      this.remoteLoadUsers.timer = null
      this.remoteLoadUsers.timer = setTimeout(() => {
        if (query.length >= 2) {
          if (this.partData.scope === 'ALL') {
            this.remoteMethod(query)
          } else if (this.partData.scope === 'SAME_INDEPENDENT_ORG') {
            this.remoteSameIndependentOrgMethod(query, this.partData.includeChildOrg)
          }
        }
      }, 250)
    },
    remoteMethod(query) {
      const params = {
        userAccount: query.trim()
      }
      this.userListOptions = []
      getUsersByAccount(params).then(res => {
        if (res.items) {
          const userListOptions = res.items.map(item => {
            return {
              label: item.userName + '(' + item.userAccount + ')',
              value: item.id,
              style: { display: 'block' }
            }
          }).filter(r => r)
          this.filterData(userListOptions)
        }
      })
    },
    filterData(userNameList) {
      const arr = this.userListOptions || []
      arr.length && arr.forEach(user => {
        const isInclud = userNameList.find((item, index) => {
          const bool = item.value === user.value
          if (bool) {
            userNameList.splice(index, 1)
          }
          return bool
        })
        if (!isInclud) {
          user.style = { display: 'none' }
        } else {
          user.style = { display: 'block' }
        }
      })
      arr.push(...userNameList)
      this.userListOptions = arr
    },
    remoteSameIndependentOrgMethod(query, includeChildOrg) {
      findInUserSameIndependentOrg(!!includeChildOrg, (query || '').trim())
        .then(res => {
          if (Array.isArray(res.items)) {
            let userListOptions = []
            res.items.forEach(item => {
              const user = item
              if (user) {
                userListOptions.push({
                  label: user.userName + '(' + user.userAccount + ')',
                  value: user.id,
                  style: { display: 'block' }
                })
              }
            })
            const includeCurrentUser = this.partData.includeCurrentUser || false
            if (!includeCurrentUser) {
              const userId = localStorage.getItem('userId')
              userListOptions = userListOptions.filter(u => (u.value).toString() !== userId)
            }
            this.userListOptions = userListOptions
          }
        })
    },
    // 获取上下文角色下的用户
    getContextUser(query, item) {
      if (this.businessObject && this.businessObject.dxContextId) {
        const params = {
          contextId: this.businessObject.dxContextId,
          teamCode: item.scopeValues.join(',')
        }
        getContextUsers(params).then(res => {
          if (res.items && res.items.length) {
            this.getAllUser(res.items)
          }
        })
      }
    },
    // 获取群组下的用户
    getGroupUser(group) {
      this.userListOptions = []
      const params = {
        'pageFrom': 1,
        'pageSize': 100,
        'searchItems': {
          'children': [

          ],
          'items': [
            {
              'fieldName': 'sourceId',
              'operator': 'IN',
              'value': group
            }
          ],
          'operator': 'AND'
        },
        'openProps': [
          {
            'name': 'target',
            'pageFrom': 1,
            'pageSize': 9999
          }
        ],
        'sortItem': [
          {
            'fieldName': 'modifyTime',
            'sortOrder': 'desc'
          }
        ]
      }
      this.$api.searchApi('DxGroupMemberLink', params).then(res => {
        const arr = res.items && res.items.content ? res.items.content.map((n) => {
          return {
            label: `${n.target.userName}(${n.target.userAccount})`,
            value: n.target.id
          }
        }) : []

        this.userListOptions = arr
      })
    },
    // 获取组织下的用户
    getOrgUser(org, query) {
      this.userListOptions = []
      const includeCurrentUser = this.partData.includeCurrentUser
      getUsersInOrgs(this.partData.includeChildOrg, org).then(res => {
        let arr = []
        if (res.items && res.items) {
          res.items.forEach((n) => {
            const findItem = arr.find(r => r.value === n.id)
            if (!findItem) {
              arr.push({
                label: `${n.userName}(${n.userAccount})`,
                value: n.id
              })
            }
          })
        }
        if (!includeCurrentUser && this.isCheckIncludeCurrUser) {
          const userId = localStorage.getItem('userId')
          arr = arr.filter(u => (u.value).toString() !== userId)
        }
        this.userListOptions = arr
      })
    },
    // 用户所在的独立组织下的所有用户,以及该独立组织下自组织下的所有用户
    getUserOptions() {
      getUserOrganizations({ userId: localStorage.getItem('userId') })
        .then(res => {
          if (res.items && res.items.length) {
            const org = res.items.map(r => r.id)
            this.getOrgUser(org)
          }
        })
    },
    validate() {
      return this.$refs.form.validate()
    },
    initData(data) {
      if (!this.businessObject) {
        // 获取PBO
        getInstancePbo(data.instId || data.procInstId).then(res => {
          this.businessObject = res.items
          getSignAddUserScope(data.processDefinitionId || data.procDefId, data.instId || data.procInstId, data.taskKey, this.typeEnum).then(res => {
            const partData = res.items
            this.partData = partData
            this.partData.includeCurrentUser = partData.includeCurrentUser !== false
            this.partData.includeChildOrg = partData.includeChildOrg !== false
            this.remote = ['ALL', 'SAME_INDEPENDENT_ORG'].includes(partData.scope)
            if (!this.remote) {
              this.getUser(partData)
            }
          })
        })
      } else {
        getSignAddUserScope(data.processDefinitionId || data.procDefId, data.instId || data.procInstId, data.taskKey, this.typeEnum).then(res => {
          const partData = res.items
          this.partData = partData
          this.remote = ['ALL', 'SAME_INDEPENDENT_ORG'].includes(partData.scope)
          if (!this.remote) {
            this.getUser(partData)
          }
        })
      }
    },
    change(val) {
      if (this.instData) {
        this.$emit('getUser', val)
      } else {
        this.$emit('changeForm', { val: val, row: this.scope.row, index: this.scope.$index })
      }
    },
    // 获取当前用户所在组织
    getCurrentUserOrgIds() {
      let currUserOrgIds = null
      try {
        currUserOrgIds = [localStorage.getItem('org')]
      } catch (e) {
        currUserOrgIds = []
      }
      return currUserOrgIds
    }
  },
  validate() {
    return this.$refs.form.validate()
  }
}
</script>

<style lang="scss">
.addExaminationUserSelect-com{
    .el-select{
        width: 100%;
    }
}
</style>