<template>
  <div>
    <el-dialog :title="'['+(role && role.roleName)+'] ' + $t('ec.role.memberList')" :visible.sync="visible" class="findMemberDialog " top="4%" width="850px">
      <el-row :gutter="20" type="flex" justify="space-between" align="middle">
        <el-col :span="12">在{{ tenantName }}共{{ page.total }}位成员使用该角色</el-col>
        <el-col :span="8" style=" text-align: right;">
          <el-button type="primary" @click="showUserCard = true">
            +{{ $t('ec.role.addMember') }}
          </el-button>
        </el-col>
      </el-row>

      <vxe-grid
        ref="vxeDio"
        row-key
        show-overflow
        show-header-overflow
        max-height="1000"
        highlight-current-row
        highlight-hover-row
        border="default"
        resizable
        sync-resize
        auto-resize
        class="vxe-table-element"
        :loading="loading"
        :start-index="(page.currentPage - 1) * page.pageSize"
        :pager-config="page"
        :columns="columns"
        :data="roleData"
        @current-change="currentRowChange"
        @radio-change="radioRowChange"
        @page-change="handlePageChange"
      >
        <template v-slot:role_member_operation="{ row }">
          <el-button v-permission="['user:view']" size="mini" type="text" @click="allDetail(row.id)">{{ $t('ec.table.detail') }}</el-button>
          <el-button v-permission="['user:permission']" class="text-green-color" type="text" @click="$refs.userAllRoleDialog.init(row,true)">{{ $t('ec.table.permission') }}</el-button>
          <el-button v-permission="['role:edit']" type="text" @click="edit(row)">{{ $t('ec.table.edit') }}</el-button>
          <el-dropdown
            v-permission="['user:edit', 'user:app', 'user:role', 'user:org', 'user:dept', 'user:reset']"
            trigger="click"
            style="padding-left:5px;padding-right:5px;"
            @command="command => dropDownCmd(command, row)"
          >
            <el-button type="text" icon="el-icon-arrow-down" size="mini" />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-permission="['user:delete']" command="delete">{{ $t('ec.table.delete') }}</el-dropdown-item>
              <el-dropdown-item v-if="superAdmin" v-permission="['user:app']" command="system">{{ $t('ec.user.accessibleApp') }}</el-dropdown-item>
              <el-dropdown-item v-permission="['user:role']" command="role">{{ $t('ec.user.assignRole') }}</el-dropdown-item>
              <el-dropdown-item v-if="superAdmin" v-permission="['user:org']" command="org">{{ $t('ec.role.orgAuth') }}</el-dropdown-item>
              <el-dropdown-item v-permission="['user:dept']" command="dept">{{ $t('ec.role.deptAuth') }}</el-dropdown-item>
              <el-dropdown-item v-permission="['user:reset']" command="resetPwd">{{ $t('ec.user.resetPwd') }}</el-dropdown-item>
              <el-dropdown-item v-permission="['user:impersonate']" command="impersonate">{{ $t('ec.user.switchId') }}</el-dropdown-item>
              <el-dropdown-item command="onlineSystem">{{ $t('ec.user.onlineSystem') }}</el-dropdown-item>
              <el-dropdown-item command="point">{{ $t('ec.user.pointPermissions') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>

        <template v-slot:role-avatar="{ row }">
          <img style="height: 35px;width: 35px; border-radius: 50%;" :src="row.avatar || defaultAvatar" alt="">
        </template>
      </vxe-grid>

      <!--    <div slot="footer" class="dialog-footer">-->
      <!--      <el-button type="primary" plain @click="visible = false">{{ $t('ec.tagsView.close') }}</el-button>-->
      <!--    </div>-->

      <ec-contact
        v-if="showUserCard"
        ref="ecUser"
        v-model="delegateUser"
        value-field="username"
        :str-result="true"
        :multiple="true"
        :is-direct="showUserCard"
        @getContact="getContactData"
        @directClose="()=>{showUserCard = false}"
      />

    </el-dialog>
    <user-all-role ref="userAllRoleDialog" />
    <detail ref="userEditDialog" @refreshData="getData" />

    <user-app ref="userAppDialog" />

    <user-org-permission ref="userOrgPermissionDialog" />

    <user-dept-permission ref="userDeptPermissionDialog" />

    <user-superior ref="userSuperiorDialog" />
    <onlineSystem ref="onlineSystem" />
    <userLocation ref="userLocation" />
    <user-role ref="userRoleDialog" />
  </div>
</template>

<script>
import { userVo, saveRoleAppUsers } from 'ecip-web/api/vue/role/sysrRoleApi'
import { resetPassword, impersonate } from 'ecip-web/api/vue/user/sysrUserApi'
import UserAllRole from '../../../user/sysrUser/components/userAllRole'
import Detail from '../../../user/sysrUser/components/detail'
import UserApp from '../../../user/sysrUser/components/userApp'
import userLocation from '../../../user/sysrUser/components/userLocation'
import UserOrgPermission from '../../../user/sysrUser/components/userOrgPermission'
import UserDeptPermission from '../../../user/sysrUser/components/userDeptPermission'
import onlineSystem from '../../../user/sysrUser/components/onlineSystem'
import UserSuperior from '../../../user/sysrUser/components/userSuperior'
import UserRole from '../../../user/sysrUser/components/userRole'
export default {
  name: 'FindMember',
  components: { UserAllRole, Detail, UserApp, userLocation, UserOrgPermission, UserDeptPermission, onlineSystem, UserSuperior, UserRole },
  data() {
    return {
      defaultAvatar: require('@/assets/img/avatar.png'),
      showUserCard: false,
      delegateUser: '',
      visible: false,
      loading: false,
      saveLoading: false,
      appId: '',
      role: {},
      roleUsers: '',
      roleUserList: [],
      form: {
        name: ''
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        align: 'left',
        pageSizes: [10, 20, 50, 100, 200, 500],
        layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
        perfect: true
      },
      columns: [
        { title: 'ec.table.id', type: 'seq', minWidth: 60, align: 'center' },
        { title: 'ec.user.avatar', minWidth: 80, align: 'center', slots: { default: 'role-avatar' }},
        { title: 'ec.user.realName', field: 'realName', minWidth: 90, align: 'center', showOverflow: true },
        { title: 'ec.user.sex', field: 'sexName', minWidth: 80, align: 'center', showOverflow: true },
        { title: 'ec.user.organization', field: 'orgName', minWidth: 120, align: 'center', showOverflow: true },
        { title: 'ec.sms.phone', field: 'phone', minWidth: 100, align: 'center', showOverflow: true },
        { title: 'ec.table.actions', minWidth: 210, align: 'center', slots: { default: 'role_member_operation' }}
      ],
      roleData: [],
      tenantName: ''
    }
  },
  methods: {
    getContactData(data) {
      if (data && data.name) {
        this.$confirm(`确定为${data.name.join()}这${data.name.length}个成员添加【${this.role.roleName}】的角色吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          this.loading = true
          saveRoleAppUsers(this.role.id, this.role.appId, data.id).then((res) => {
            // 清空所有已选
            this.delegateUser = ''
            this.$refs.ecUser.clearChoose()
            this.handlePageChange({ currentPage: 1, pageSize: 10 })
          }).catch((e) => {
            this.loading = false
          })
          this.showUserCard = false
        })
      }
    },
    // 下拉菜单点击事件
    async dropDownCmd(command, row) {
      switch (command) {
        case 'delete':
          this.remove(row.id)
          break
        case 'system':
          this.$refs.userAppDialog.init(row)
          break
        case 'role':
          this.$refs.userRoleDialog.init(row)
          break
        case 'dept':
          this.$refs.userDeptPermissionDialog.init(row)
          break
        case 'org':
          this.$refs.userOrgPermissionDialog.init(row)
          break
        case 'resetPwd':
          this.resetPwd(row.id)
          break
        case 'impersonate':
          this.impersonate(row)
          break
        case 'onlineSystem':
          this.$refs.onlineSystem.init(row)
          break
        case 'point':
          this.$refs.userLocation.init(row)
          break
      }
    },
    allDetail(id) {
      this.$router.push({ path: '/user/sysrUserDetail', query: { id }})
    },
    resetPwd(id) {
      this.$confirm(this.$t('ec.user.resetPwdConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        await resetPassword(id)
      })
    },
    impersonate(row) {
      this.$confirm(this.$t('ec.user.switchConfirm', { name: row.realName ? row.realName : row.username }), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        await impersonate(row.id)
        // window.location.reload()
        if (window._CONFIG['portalUrl']) {
          window.open(window._CONFIG['portalUrl'], '_blank')
        }
        window.location.replace(process.env.BASE_URL || '/')
      })
    },
    edit(row) {
      this.$refs.userEditDialog.init('edit', row, true)
    },
    async init(appId, role, tenantName) {
      this.appId = appId
      this.role = role
      this.visible = true
      this.tenantName = tenantName
      this.$nextTick(() => {
        if (role && role.id) {
          this.roleUser(role.id)
        } else {
          this.roleUserList = []
          this.roleUsers = ''
        }
      })
      this.getData()
      console.log(this.role.id)
    },
    async roleUser(id) {

    },
    radioRowChange({ row }) {
      // this.$refs.vxeDio.setRadioRow(row)
    },
    currentRowChange({ row }) {
      // this.$refs.vxeDio.setRadioRow(row)
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.getData()
    },
    async getData() {
      try {
        this.loading = true
        const { data } = await userVo(Object.assign({}, { id: this.role.id }), { size: this.page.pageSize, current: this.page.currentPage })
        data.records.length && data.records.forEach((item) => {
          !item.sex ? item.sexName = '男士' : item.sexName = '女士'
        })
        this.roleData = data.records

        this.page.total = data.total
      } finally {
        this.loading = false
      }
    }

  }
}
</script>

<style lang="scss">
.findMemberDialog{
  .el-dialog__body{
    padding-top: 5px;
    .el-row{
      padding-bottom: 10px;
    }
  }
}
</style>
