<template>
  <div class="assignPermissions">
    <div class="sub-title" style="padding-left:8px;color:#212121;font-weight:400">
      <img src="/icons/back.png" @click="back">
      <span>{{ userInfo.name }}</span>
    </div>
    <dee-tab id="dee-tab" ref="deetab" class="assignPermissions-tab" :tabs="tabs" @tabClick="tabClick">
      <div slot="1" style="height:100%">
        <dee-tools :tools="userTools" mode="normal" style="padding: 10px 0" />
        <div style="height: calc(100% - 44px);">
          <dee-up-table
            ref="usertable"
            :index-row="{title:'序号',width: '80'}"
            :data="userData"
            :columns="userColumns"
            :options="userOptions"
            selection-row
            @select="handleSelect"
            @selection-change="checkrows"
            @pagination-size-change="changePageSize"
            @pagination-current-change="changePageNum"
          />
        </div>
        <!-- 添加特定用户-弹出框 -->
        <dee-dialog :visible.sync="dialogVisible" width="580px" :destroy-on-close="true" :close-on-click-modal="false" :before-close="handleClose" title="新增用户">
          <el-form
            ref="newForm1"
            :model="form1"
            label-width="100px"
          >
            <el-form-item label="选择组:">
              <OrgLazyLoadSelect
                v-model="groupcheckeds"
                :is-multi="true"
                value-key="id"
                :parent-id="tripleTreeNode.level===2 ?tripleTreeNode.organizationId : ''"
                style="width: 100%;"
              />
            </el-form-item>
            <el-form-item label="选择群组:">
              <dee-group
                v-model="userGroupcheckeds"
                :multiple="true"
                value-key="id"
                :triple-org-id="tripleTreeNode.level===2 ?tripleTreeNode.organizationId : ''"
                style="width: 100%;"
              />
            </el-form-item>
            <el-form-item label="选择用户:">
              <el-select
                v-model="users"
                class="auto-width"
                multiple
                filterable
                clearable
                remote
                value-key="id"
                placeholder="输入联想查询用户,可选多个用户"
                :remote-method="remoteUserMethod"
              >
                <el-option
                  v-for="item in tempUserRemoteOptions"
                  :key="item.id"
                  :label="`${item.userName}`+'('+`${item.userAccount}`+')'"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" style="text-align:center">
            <el-button
              slot="sub_text"
              type="primary"
              class="searchBtn"
              @click="addUserGroup"
            >确定</el-button>
            <el-button slot="sub_cancel" class="searchBtn" @click="handleClose">取消</el-button>
          </div>
        </dee-dialog>
        <!-- 添加团队角色-弹出框 -->
        <dee-dialog :visible.sync="roleDialogVisible" width="580px" :destroy-on-close="true" :close-on-click-modal="false" :before-close="handleCloseRole" title="添加团队角色">
          <el-form
            ref="newForm1"
            :model="form1"
            label-width="100px"
          >
            <el-form-item required label="类型">
              <el-select
                v-model="selectType"
                class="auto-width"
                placeholder="请选择类型"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="selectType === '上下文类型'" required label="上下文类型">
              <el-select
                v-model="contexts"
                class="auto-width"
                multiple
                filterable
                placeholder="请选择上下文类型"
              >
                <el-option
                  v-for="item in contextOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="selectType === '上下文'" required label="上下文">
              <input-tree
                class="auto-width"
                :tree-data="groupRemoteOptionsMap2"
                :columns="groupInputTree2"
              />
            </el-form-item>
            <el-form-item required label="角色">
              <el-select
                v-model="roles"
                class="auto-width"
                multiple
                filterable
                placeholder="请选择角色"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" style="text-align:center">
            <el-button
              slot="sub_text"
              type="primary"
              class="searchBtn"
              @click="addRoleGroup"
            >确定</el-button>
            <el-button slot="sub_cancel" class="searchBtn" @click="handleCloseRole">取消</el-button>
          </div>
        </dee-dialog>
        <!-- 角色详情-弹出框 -->
        <dee-dialog :visible.sync="detailDialogVisible" width="580px" :destroy-on-close="true" :close-on-click-modal="false" :before-close="handleCloseDetailDialog" title="团队角色">
          <div style="margin-bottom: 15px">名称: {{ currentRow.name }}</div>
          <dee-table
            :data="roleDetailData"
            :columns="roleDetailColumns"
          />

        </dee-dialog>
        <!-- 修改授权部门-弹出框 -->
        <dee-dialog :visible.sync="authOrgVisible" width="580px" :destroy-on-close="true" :close-on-click-modal="false" title="修改授权部门">
          <el-form ref="newForm1" :model="authOrgForm" label-width="100px">
            <el-form-item label="授权部门">
              <el-select
                v-model="authOrgForm.authOrgIds"
                class="auto-width"
                multiple
                filterable
                clearable
                default-first-option
                placeholder="请选择授权部门,可选多个授权部门"
              >
                <el-option
                  v-for="item in authOrgOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" style="text-align:center">
            <el-button
              slot="sub_text"
              type="primary"
              class="searchBtn"
              size="small"
              @click="onCloseEditAuthOrgDialog(true)"
            >确定</el-button>
            <el-button slot="sub_cancel" class="searchBtn" size="small" @click="onCloseEditAuthOrgDialog(false)">取消</el-button>
          </div>
        </dee-dialog>
      </div>
      <div slot="2" style="height:100%">
        <div style="height:100%;overflow: hidden;">
          <dee-tools v-if="0" :tools="assignTools" mode="normal" />
          <split-pane
            :min-percent="18"
            :default-percent="22"
            split="vertical"
            class="detail-pane"
          >
            <template slot="paneL">
              <div class="three-member-wrap">
                <!-- <dee-form v-if="!userInfo.appId" :form="appForm" :form-data="appFormData" /> -->
                <dee-form v-if="currAppData.id==='1' && !userInfo.innerFlag " :form="appForm" :form-data="appFormData" />
                <perm-tree ref="permTree" :show-title="false" :appid="currAppId" class="tree-rwap" @change="getResourceData" @changeView="changeView" />
              </div>
            </template>
            <template slot="paneR">
              <div class="resourceTable-wrap">
                <dee-up-table
                  v-if="permViewIdx === 1"
                  :key="modelId"
                  ref="resourceTable"
                  class="resourceTable"
                  :selection-row="{selectable: selectable}"
                  :dis-select-all="disSelectAll"
                  :check-row-default="checkRowDefault"
                  :data="resourceData"
                  :columns="resourceColumns"
                  @select="checkResourceRow"
                  @select-all="checkResourceRowAll"
                />
                <ActionPermTree
                  v-if="permViewIdx === 2"
                  :key="modelId"
                  class="tree-wrap"
                  :role-info="userInfo"
                  :model-id="modelId"
                />
              </div>
            </template>
          </split-pane>
          <permission ref="permission" :key="permissionKey" :row="row" :dialog-visible="permissionDialogVisible" :user-info="userInfo" @go-back="goBack" @handleClose="handleClose" />
          <copy-perm-expression :dialog-visible="copyDia" :resource-data="resourceData" :row="row" :user-info="userInfo" @handleClose="handleClose" @getPermByObjIdAndRoleId="getPermByObjIdAndRoleId" />
        </div>
      </div>
      <div slot="3" style="height:100%">
        <menuPermAssignment :role-info="userInfo" :apps="apps" :curr-app-data="currAppData" :triple-tree-node="tripleTreeNode" type="3" />
      </div>
      <div v-if="!userInfo.innerFlag" slot="4" style="height:100%">
        <menuPermAssignment :role-info="userInfo" :apps="apps" :curr-app-data="currAppData" :triple-tree-node="tripleTreeNode" type="4" />
      </div>
    </dee-tab>
  </div>
</template>
<script>
import Permission from './Permission2'
import InputTree from '../../business-components/tree/InputTree'
import PermTree from './permTree'
import MenuPermAssignment from './menuPermAssignment'
import CopyPermExpression from './components/copyPermExpression'
import ActionPermTree from './actionPermTree'
import {
  addusers2role,
  changeAuthOrg,
  removeUserById,
  getThirdUser, savePerms,
  getGroupPerson, getUserList,
  addRole, deleteRole, deleteRoleBatch, getGlobalTree,
  saveRolePerms
} from '@/api/mgt/role.js'
import { getPermByObjIdAndRoleId } from '@/api/mgt/permission'
import { generateTree } from '@/utils/util'
import { get } from '@/utils/http'
import { getUsersByAccount } from '../../../../architecture-dee/src/api/globalProperties'
export default {
  name: 'AssignPermissions',
  components: { Permission, InputTree, PermTree, MenuPermAssignment, CopyPermExpression, ActionPermTree },
  props: {
    userInfo: {
      type: Object,
      default: () => null
    },
    tripleTreeNode: {
      type: Object,
      default: () => null
    },
    currAppData: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      currAppId: '',
      permissionKey: 0,
      permissionDialogVisible: false,
      copyDia: false,
      row: null,
      grouBlen: false,
      // groups: [],
      groupcheckeds: [],
      currentRow: {},
      groupRemoteOptions: [],
      reGroupRemoteOptions: [],
      reUserGroupRemoteOptions: [],
      userGroupcheckeds: [],
      // 授权部门
      authOrgIds: [],
      authOrgVisible: false,
      authOrgForm: {
        record: null,
        authOrgIds: []
      },
      users: [],
      roles: [],
      contexts: [],
      contextOptions: [],
      roleOptions: [],
      roleOptionsObj: {},
      roleDetailData: [
        {}
      ],
      selectType: '上下文类型',
      typeOptions: [
        {
          name: '上下文类型'
        },
        {
          name: '上下文'
        }
      ],
      userRemoteOptions: {},
      tempUserRemoteOptions: [],
      contextTreeArray: [],
      showSubLoad: {},
      thirdPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50]
      },
      appName: '',
      perName: '',
      userData: [],
      userRoleData: [],
      roleDetailColumns: [
        { title: '操作', minWidth: 40, align: 'center', component: {
          name: 'EditTableRow',
          show: true,
          props: {
            btns: [{
              operation: '删除',
              handleClick: (row, index) => {
                this.removeRole(row, index)
              },
              icon: '/icons/c-creatbackups.png',
              showFun: (row) => {
                return true
              }
            }]
          }}
        },
        { title: '角色名称', key: 'roleName', align: 'center' }
      ],
      userOptions: {
        fit: true,
        defaultExpandAll: true,
        highlightCurrentRow: true
      },
      editData: [],
      editColumns: [
        { title: '用户名', key: 'account', align: 'center', minWidth: 120 },
        { title: '姓名', key: 'name', align: 'center', minWidth: 120 },
        { title: '性别', key: 'sex', align: 'center', minWidth: 120 },
        { title: '电话', key: 'tel', align: 'center', minWidth: 120 },
        { title: '所属组织', key: 'org', align: 'center', minWidth: 120 },
        { title: '邮箱', key: 'email', align: 'center', minWidth: 120 },
        { title: '创建时间', key: 'createDate', align: 'center', minWidth: 120 }
      ],
      editOptions: {
        fit: true,
        defaultExpandAll: true,
        highlightCurrentRow: true
      },

      resourceData: [],
      tabs: [
        { id: '1', name: '分配用户' },
        { id: '2', name: '分配功能权限' },
        { id: '3', name: '分配菜单权限' },
        { id: '4', name: '分配场景权限' }
      ],
      resourceColumns: [
        { title: '操作', key: 'operation', align: 'center', minWidth: 50,
          component: {
            show: true,
            name: 'EditTableRow',
            props: {
              btns: [
                {
                  operation: '配置数据权限',
                  handleClick: (row, index) => {
                    if (row.hadPage) {
                      this.permissionKey++
                      this.permissionDialogVisible = true
                      this.row = row
                    } else {
                      this.$utils.showMessageError('请先勾选权限')
                    }
                  },
                  icon: '/icons/c-setting.png',
                  showFun: (row) => {
                    return !this.userInfo.innerFlag
                    // return row.typeName !== '页面'
                  }
                },
                {
                  operation: '复制权限表达式',
                  handleClick: (row, index) => {
                    this.copyDia = true
                    this.row = row
                  },
                  icon: '/icons/c-substituteob.png',
                  showFun: (row) => {
                    return !this.userInfo.innerFlag
                  }
                }]
            }
          }
        },
        { title: '权限名称', key: 'displayName', align: 'center', minWidth: 120 },
        { title: '权限代号', key: 'name', align: 'center', minWidth: 120 },
        { title: '数据权限', key: 'expression', align: 'center', minWidth: 120 }
      ],
      saveData: {},
      dialogVisible: false,
      roleDialogVisible: false,
      detailDialogVisible: false,
      form1: {},
      userId: {
        key: 'userId',
        title: '用户ID',
        component: {
          name: 'el-select',
          options: [
            {
              label: '1',
              value: '1'
            }
          ]
        }
      },
      sub_text: {
        key: 'sub_text',
        component: {
          name: 'custom'
        }
      },
      rules: {},
      rules1: {},
      rules2: {},
      assignTools: [
        {
          type: 'icon',
          name: '保存',
          icon: require('../../icons/home/mycreate.png'),
          handler: {
            click: () => {
              this.savePermission()
            }
          }
        }
      ],
      curNodeKey: null,
      treeData: [],
      treeCount: 0,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50]
      },
      selectedRows: [],
      planeTreeData: [],
      selectedPerm: [],
      topNode: [],
      modelId: '',
      checkRowDefault: [],
      appForm: {},
      apps: [],
      // 授权部门下拉列表
      authOrgOptions: [],
      permViewIdx: 1
    }
  },
  computed: {
    disSelectAll() {
      return this.userInfo.innerFlag
    },
    selectable() {
      return (row, index) => {
        return !this.userInfo.innerFlag
      }
    },
    userTools: function() {
      const arr = [
        {
          type: 'icon',
          name: '指定全部用户',
          icon: '/icons/c-add.png',
          show: this.tripleTreeNode.level === 1,
          handler: {
            click: () => {
              this.addAllUser()
            }
          }
        },
        {
          type: 'icon',
          name: '指定本组织用户',
          icon: '/icons/c-add.png',
          show: this.tripleTreeNode.level === 2,
          handler: {
            click: () => {
              this.addOwnOrgUser()
            }
          }
        },
        {
          type: 'icon',
          name: '添加特定用户',
          icon: '/icons/c-add.png',
          show: true,
          handler: {
            click: () => {
              this.addSpecificUser()
            }
          }
        },
        {
          type: 'icon',
          name: '添加团队角色',
          icon: '/icons/c-add.png',
          show: (this.tripleTreeNode.level === 1 && !this.userInfo.innerFlag) || (!this.userInfo.innerFlag && this.tripleTreeNode.level === 2 && this.currAppData.organizationId && this.currAppData.organizationId === this.tripleTreeNode.organizationId),
          handler: {
            click: () => {
              this.addTeamRole()
            }
          }
        },
        {
          type: 'icon',
          name: '删除',
          icon: '/icons/c-creatbackups.png',
          show: true,
          handler: {
            click: () => {
              this.removeUser()
            }
          }
        }
      ]
      return arr.filter(r => r.show)
    },
    userColumns() {
      const userColumns = [
        {
          title: '类型',
          key: 'type',
          align: 'center',
          minWidth: 120
          // fildProp: {
          //   type: 'DictDataVO',
          //   rule: {
          //     dictTypeCode: 'UserGroupType'
          //   }
          // }
        },
        {
          title: '名称',
          key: 'personnelName',
          align: 'center',
          minWidth: 120,
          sortable: true
          // component: {
          //   show: true,
          //   render: (h, row, column, $index) => {
          //     if (['上下文', '上下文类型'].includes(row.type)) {
          //       return <div><span style='vertical:middle;'>{row.personnelName}</span> <img src ={ require('@/icons/components/new/c-edit.png') }
          //         title = '角色详情'
          //         style = 'width:16px;height:16px;cursor:pointer;margin-right:10px;vertical:middle;'
          //         v-on:click= {() => { this.showDetailRole(row) }}
          //       />
          //       </div>
          //     } else {
          //       return <div><span>{row.personnelName}</span></div>
          //     }
          //   }
          // }
        },
        // {
        //   title: '角色',
        //   // key: 'personnelName',
        //   align: 'center',
        //   minWidth: 120,
        //   // sortable: true,
        //   component: {
        //     show: true,
        //     render: (h, row, column, $index) => {
        //       if (['上下文', '上下文类型'].includes(row.type)) {
        //         const resData = row.teamKeys.map(el => {
        //           return this.roleOptionsObj[el]
        //         })
        //         return <div>
        //           <span style='vertical:middle;'>
        //             {resData.join(',')}
        //           </span>
        //           <img src ={ require('@/icons/components/new/c-edit.png') }
        //             title = '角色详情'
        //             style = 'width:16px;height:16px;cursor:pointer;margin-right:10px;vertical:middle;'
        //             v-on:click= {() => { this.showDetailRole(row) }}
        //           />
        //         </div>
        //       } else {
        //         return <div>/</div>
        //       }
        //     }
        //   }
        // },
        {
          title: '内置',
          key: 'innerFlag',
          align: 'center',
          Width: 50,
          formatter(row, column) {
            return row.innerFlag ? '是' : '否'
          }
        }
      ]
      const findContextData = this.userData.find(el => {
        return el.type === '上下文' || el.type === '上下文类型'
      })
      if (findContextData) {
        userColumns.splice(
          2,
          0,
          {
            title: '角色',
            // key: 'personnelName',
            align: 'center',
            minWidth: 120,
            // sortable: true,
            component: {
              show: true,
              render: (h, row, column, $index) => {
                if (['上下文', '上下文类型'].includes(row.type)) {
                  const resData = row.teamKeys.map(el => {
                    return this.roleOptionsObj[el]
                  })
                  return <div>
                    <span style='vertical-align:middle;display:inline-block;width:calc(100% - 50px);white-space:nowrap;text-overflow:ellipsis;overflow:hidden;word-break:break-all;'>
                      {resData.join(',')}
                    </span>
                    <img src ={ require('@/icons/components/new/c-edit.png') }
                      title = '角色详情'
                      style = 'width:16px;height:16px;cursor:pointer;margin-right:10px;vertical-align:middle;'
                      v-on:click= {() => { this.showDetailRole(row) }}
                    />
                  </div>
                } else {
                  return <div>/</div>
                }
              }
            }
          }
        )
      }
      return userColumns
    },
    appFormData() {
      return [
        {
          split: 1,
          data: [{
            key: 'appId',
            title: '',
            component: {
              name: 'el-select',
              options: this.apps
            },
            handler: {
              'change': (val) => {
                this.$refs.permTree.getAllObj(val, this.apps)
              }
            }
          }
          ]
        }
      ]
    },
    groupInputTree() {
      const _this = this
      return [
        { checkStrictly: true,
          showAll: true,
          handler: {
            change(checkeds) {
              // eslint-disable-next-line vue/no-side-effects-in-computed-properties
              _this.groupcheckeds = JSON.parse(JSON.stringify(checkeds))
            }
          }}
      ]
    },
    // 用户群组
    userGroupInputTree() {
      const _this = this
      return [
        { checkStrictly: true,
          showAll: true,
          handler: {
            change(checkeds) {
              // eslint-disable-next-line vue/no-side-effects-in-computed-properties
              _this.userGroupcheckeds = JSON.parse(JSON.stringify(checkeds))
            }
          }}
      ]
    },
    groupInputTree2() {
      const _this = this
      return [
        { checkStrictly: true,
          showAll: true,
          handler: {
            change(checkeds) {
              // eslint-disable-next-line vue/no-side-effects-in-computed-properties
              _this.contextTreeArray = JSON.parse(JSON.stringify(checkeds))
            }
          }}
      ]
    },
    groupRemoteOptionsMap() {
      const groupRemoteOptions = this.reGroupRemoteOptions
      const createOption = optionData => {
        return optionData.map(item => {
          const obj = {}
          obj.label = item.orgName
          obj.value = item.id
          obj.key = item.id
          obj.checked = false
          if (item.orgState !== 'ENABLE') {
            obj.disabled = true
          } else {
            if (item.children && item.children.length) {
              obj.children = createOption(item.children)
            }
          }
          return obj
        })
      }
      return createOption(groupRemoteOptions)
    },
    groupRemoteOptionsMap2() {
      const groupRemoteOptions = this.treeData
      const createOption = optionData => {
        return optionData.map(item => {
          const obj = {}
          obj.label = item.name
          obj.value = item.id
          obj.key = item.id
          obj.checked = false
          if (item.children && item.children.length) {
            obj.children = createOption(item.children)
          }
          return obj
        })
      }
      return createOption(groupRemoteOptions)
    },
    showUserData() {
      if ((this.userInfo.isUserOrTeam === 'user' || this.userInfo.isUserOrTeam) && this.userData.length) {
        const getGroups = (groupList) => {
          const arr = []
          const searchGroup = (group) => {
            group.forEach(item => {
              arr.push(item)
              if (item.children && item.children.length) searchGroup(item.children)
            })
          }
          searchGroup(groupList)
          return arr
        }
        return this.userData.map(row => {
          if (row.userGroupType === 'GROUP') {
            const group = getGroups(this.reGroupRemoteOptions).find(r => row.userGroupId === r.id + '')
            if (group) {
              row.name = group.orgName
            } else {
              row.name = row.userGroupId
            }
          } else if (row.userGroupType === 'USER') {
            if (this.userRemoteOptions[row.userGroupId]) {
              row.name = this.userRemoteOptions[row.userGroupId].userName
            } else {
              row.name = row.userGroupId
            }
          } else if (row.userGroupType === 'TEAM') {
            const group = getGroups(this.reUserGroupRemoteOptions).find(r => row.userGroupId === r.id + '')
            if (group) {
              row.name = group.orgName
            } else {
              row.name = row.userGroupId
            }
          }
          row.show = true
          return row
        })
      } else {
        return this.userRoleData
      }
    },
    userGroupRemoteOptionsMap() {
      const groupRemoteOptions = this.reUserGroupRemoteOptions
      const createOption = optionData => {
        return optionData.map(item => {
          const obj = {}
          obj.label = item.orgName
          obj.value = item.id
          obj.key = item.id
          obj.checked = false
          if (item.orgState !== 'ENABLE') {
            obj.disabled = true
          } else {
            if (item.children && item.children.length) {
              obj.children = createOption(item.children)
            }
          }
          return obj
        })
      }
      return createOption(groupRemoteOptions)
    }
  },
  watch: {
    'appForm.appId': {
      handler: function(val) {
        if (val) {
          //
        }
      }
    }
  },
  created() {
    this.getContextList()
    this.getTree()
    this.getRoleList()
    // this.getUserPerson()
    this.getPersonList()
    this.getUserGroup()
    // 数据太大会造成卡顿,不能一开始就加载用不到的大批数据
    // this.getAuthOrgOptions()
  },
  mounted() {
    this.getUser()
    if (this.currAppData.id + '' === '1') {
      const params = {
        'searchItems': {
          'operator': 'AND',
          'items': [{
            'fieldName': 'scope',
            'operator': 'EQ',
            'value': 'ALL'
          }, {
            'fieldName': 'isDisable',
            'operator': 'EQ',
            'value': false
          }]
        }}
      this.currAppId = this.userInfo.appId
      // if (!this.apps.length) {

      this.$api.searchApi('DxApplication', params).then(res => {
        this.apps = res.items.content.map(item => {
          return {
            label: item.name,
            value: item.id,
            data: item
          }
        })
        this.currAppId = this.apps.length ? this.apps[0].value : this.userInfo.appId
      })
    }
  },
  methods: {
    // 指定全部用户
    addAllUser() {
      if (this.userData.length > 0) {
        if (this.grouBlen === true) {
          return this.$message.info('已经添加全部用户')
        }
        const hasTeam = !!this.userData.find(m => Array.isArray(m.teamKeys))
        return this.$message.info(hasTeam ? '已经添加团队角色' : '已经拥有特定用户')
      }
      this.$confirm('确认将该角色指定为全部用户?', {
        type: 'warning'
      })
        .then(_ => {
          const roleId = this.userInfo.id
          addusers2role(roleId, [{
            roleId: roleId,
            userGroupType: 'ALL_USER'
          }]).then(_ => {
            this.getUser()
          })
        })
        .catch(_ => {})
    },
    // 指定本组织用户
    addOwnOrgUser() {
      const userGroups = [{ 'roleId': this.userInfo.id, 'userGroupId': this.tripleTreeNode.organizationId, 'userGroupType': 'GROUP', 'name': '', 'authOrgId': '' }]
      addusers2role(this.userInfo.id, userGroups).then(r => {
        this.handleClose()
        this.$message.success('添加本组织用户成功')
        this.userInfo.isUserOrTeam = 'user'
        this.getUser()
      })
    },
    // 添加特定用户
    addSpecificUser() {
      if (this.userData.length > 0) {
        if (this.grouBlen === true) {
          return this.$message.info('已经添加全部用户')
        }
        const hasTeam = !!this.userData.find(m => Array.isArray(m.teamKeys))
        if (hasTeam) {
          return this.$message.info('已经添加团队角色')
        }
      }

      this.form1 = {}
      this.thirdPagination.currentPage = 1
      this.thirdPagination.pageSize = 10
      this.users = []
      this.groupcheckeds = []
      this.userGroupcheckeds = []
      this.dialogVisible = true
    },
    // 添加团队角色
    addTeamRole() {
      if (this.userData.length > 0) {
        if (this.grouBlen === true) {
          return this.$message.info('已经添加全部用户')
        }
        const hasTeam = !!this.userData.find(m => Array.isArray(m.teamKeys))
        if (!hasTeam) {
          return this.$message.info('已经拥有特定用户')
        }
      }
      this.roles = []
      this.contexts = []
      this.contextTreeArray = []
      this.form1 = {}
      this.roleDialogVisible = true
    },
    showDetailRole(row) {
      this.detailDialogVisible = true
      this.currentRow = row
      this.roleDetailData = []
      const roleNames = []
      row.teamKeys.map(name => {
        const item = this.roleOptions.find(role => role.value === name)
        if (item && item.label) {
          roleNames.push({
            value: name,
            label: item.label
          })
        }
      })
      if (row.type === '上下文') {
        this.roleDetailData = roleNames.map(({ value, label }) => {
          return {
            roleName: label,
            roleKey: value,
            cropType: row.type,
            contextId: row.personnelId
          }
        })
      } else if (row.type === '上下文类型') {
        this.roleDetailData = roleNames.map(({ value, label }) => {
          return {
            roleName: label,
            roleKey: value,
            cropType: row.personnelId
          }
        })
      }
    },
    removeRole(row, index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const roleId = this.userInfo.id
        const params = {
          roleId,
          contextId: row.contextId,
          cropType: row.cropType,
          teamKey: row.roleKey
        }
        deleteRole(roleId, { data: params }).then(r => {
          this.$message.success('删除成功')
          this.roleDetailData.splice(index, 1)
          this.getUser()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    getTree() {
      if (this.appId === null || this.appId === '') {
        return
      }
      getGlobalTree({

        'searchItems': {
          'items': [
            {
              'fieldName': 'id',
              'operator': 'NEQ',

              'value': 0
            }
          ],
          'operator': 'AND'
        }
      }).then(res => {
        this.treeData = res.items.content
        res.items.content.map(item => {
          item.children = []
        })
        this.planeTreeData = [...res.items.content]
        this.treeData = generateTree(res.items.content, {
          id: 'id',
          pid: 'parentId'
        })
      })
    },
    async getRoleList() {
      this.roleOptions = await this.$utils.getDicListByCode('TeamRole')
      this.roleOptions.forEach(el => {
        this.$set(this.roleOptionsObj, el.value, el.label)
      })
    },
    async getContextList() {
      this.contextOptions = await this.$utils.getDicListByCode('ContextType')
    },
    handleSelect() {},
    async getPersonList() {
      this.groupRemoteOptions = []
      await this.$getService('DxOrganization').query().search().then(res => {
        if (res.items && res.items.length) {
          this.$nextTick(() => {
            this.reGroupRemoteOptions = res.items
            this.groupRemoteOptions = res.items.map(row => {
              return {
                groupName: row.groupName || row.orgName,
                groupId: row.id
              }
            })
          })
        }
      })
    },
    getUserPerson(ids) {
      // this.userRemoteOptions = []
      const submitData = ids.filter((el) => {
        return !this.userRemoteOptions[el]
      })
      if (submitData.length) {
        const params = {
          'indices': [
            'USERS'
          ],
          'pageFrom': 1,
          'pageSize': 9999,
          'openProps': [
            {
              'name': 'userAccounts',
              'pageFrom': 1,
              'pageSize': 9999
            }
          ],
          'sortItem': [
            {
              'fieldName': 'modifyTime',
              'sortOrder': 'desc'
            }
          ],
          'keyWord': null,
          'searchItems': {
            'operator': 'AND',
            'items': [
              {
                'fieldName': 'id',
                'operator': 'IN',
                'value': ids
              }
            ]
          }
        }
        getUserList(params).then(res => {
          if (res.items && res.items.content) {
            res.items.content.forEach((el) => {
              this.$set(this.userRemoteOptions, el.id, el)
            })
          }
        })
      }
    },
    async getUserGroup() {
      this.reUserGroupRemoteOptions = []
      this.$getService('DxOrganization').query().search().then(res => {
        if (res.items && res.items.length) {
          this.$nextTick(() => {
            this.reUserGroupRemoteOptions = res.items
          })
        }
      })
    },
    remoteGroupMethod(query) {
      const params = {
        pageFrom: 1,
        pageSize: 1000,
        'searchItems': {
          'operator': 'AND',
          'items': [{
            'fieldName': 'groupName',
            'operator': 'LIKE',
            'searchItemType': 'string',
            'value': query
          }]
        }
      }
      getGroupPerson(params).then(res => {
        const resGroup = res.items.content
        this.groupRemoteOptions = resGroup
      })
    },
    remoteUserMethod(query) {
      if (query.length > 1) {
        const params = {
          userAccount: query.trim()
        }
        if (this.tripleTreeNode.level === 2) {
          params.orgId = this.tripleTreeNode.organizationId
        }
        getUsersByAccount(params).then(res => {
          if (res.items) {
            const items = Array.isArray(res.items) ? res.items : []
            this.tempUserRemoteOptions = items
          }
        })
        // const service = this.$getService('DxUserInfo')
        // const searchItems = service.newSearchItems().or()
        // searchItems.$addItem('name', name, 'LIKE')
        // searchItems.$addItem('userName', name, 'LIKE')
        // service.query()
        //   .search(searchItems)
        //   .then(res => {
        //     const items = Array.isArray(res.content) ? res.content : []
        //     this.tempUserRemoteOptions = items
        //   })
      }
    },
    savePermission() {
      const permIds = this.selectedPerm.map(el => el.permId).filter(el => !!el)
      const pageResourceIds = this.selectedPerm.map(el => el.id)
      savePerms(this.userInfo.id, permIds, pageResourceIds).then(({ code }) => {
        this.$message.success('保存成功')
      })
    },
    changePageSize(pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.currentPage = 1
      this.getUser()
    },
    changePageNum(pageNum) {
      this.pagination.currentPage = pageNum
      this.getUser()
    },
    checkrows(rows) {
      this.selectedRows = rows
    },
    async getUser() {
      const result = await get(`perm/Role/${this.userInfo.id}/userAndTeam`)
      this.userData = result.items
      this.grouBlen = !!this.userData.find(m => m.type === '所有用户')
    },
    goBack() {
      this.getPermByObjIdAndRoleId()
    },
    tabClick(tab) {
      if (tab.label === '分配功能权限') {
        this.$nextTick(() => {
          if (this.currAppData.id + '' === '1') {
            this.$set(this.appForm, 'appId', this.currAppId)
            this.$refs.permTree.getAllObj(this.currAppId, this.apps)
          } else {
            this.$refs.permTree.getAllObj(this.userInfo.appId, this.apps)
          }
        })
      } else {
        this.getUser()
      }
    },
    // 获取模型下的功能权限组
    getResourceData(val) {
      this.modelId = val ? val.id : ''
      this.getPermByObjIdAndRoleId()
    },
    getPermByObjIdAndRoleId() {
      this.selectedPerm = []
      this.resourceData = []
      this.checkRowDefault = []
      if (!this.modelId) {
        return
      }
      getPermByObjIdAndRoleId({ objId: this.modelId, roleId: this.userInfo.id }).then(res => {
        this.resourceData = res.items
        const idxs = []
        res.items.forEach((el, i) => {
          // hadPage === true 表示勾选中
          if (el.hadPage === true) {
            this.selectedPerm.push(el)
            idxs.push(i)
          }
        })
        this.$nextTick(() => {
          this.checkRowDefault = idxs
        })
      })
    },
    setCheckRowDefault() {
      const idxs = []
      this.resourceData.forEach((row, index) => {
        if (this.selectedPerm.find(r => r.id === row.id)) {
          idxs.push(index)
        }
      })
      this.checkRowDefault = idxs
    },
    getThirdUser() {
      const params = {
        page: this.thirdPagination.currentPage,
        size: this.thirdPagination.pageSize,
        appId: this.userInfo.appId,
        ...this.form1
      }
      // userData
      getThirdUser(params).then(({ code, message, items }) => {
        this.editData = items.content
        this.thirdPagination.total = items.totalElements
      })
    },
    changeThirdPageSize(pageSize) {
      this.thirdPagination.pageSize = pageSize
      this.thirdPagination.currentPage = 1
      this.getThirdUser()
    },
    changeThirdPageNum(pageNum) {
      this.thirdPagination.currentPage = pageNum
      this.getThirdUser()
    },
    thirdCheckrows(rows) {
      this.thirdSelectedRows = rows
    },
    handleClose() {
      this.dialogVisible = false
      this.copyDia = false
      this.permissionDialogVisible = false
      this.row = null
    },
    handleCloseRole() {
      this.roleDialogVisible = false
    },
    handleCloseDetailDialog() {
      this.detailDialogVisible = false
    },
    checkResourceRowAll(selection) {
      this.selectedPerm = selection
      const flag = !!selection.length
      const permIds = selection.length ? selection.map(r => r.id) : this.resourceData.map(r => r.id)
      this.savePerms(permIds, flag)
    },
    checkResourceRow(selection, row) {
      this.selectedPerm = selection
      const flag = !!selection.find(r => r.id === row.id)
      this.savePerms(row, flag)
    },
    savePerms(row, flag) {
      const permIds = Array.isArray(row) ? row : [row.id]
      saveRolePerms(this.userInfo.id, this.userInfo.appId, flag, permIds).then(({ code }) => {
        this.$message.success('保存成功')
        this.getPermByObjIdAndRoleId()
      }).catch(() => {
        this.$utils.showMessageError('保存失败')
        const table = this.$refs.resourceTable.$refs.deeTable
        if (Array.isArray(row)) {
          flag && table.clearSelection()
        } else {
          table.toggleRowSelection(row, !flag)
        }
      })
    },
    setResourceStatus(table, ids, flag) {
      if (flag) {
        table.forEach(el => {
          el.hadPage = true
          if (el.children && el.children.length > 0) {
            this.setResourceStatus(el.children, ids, true)
          }
        })
      } else {
        table.forEach(el => {
          el.hadPage = false
          if (ids.indexOf(el.id) > -1) {
            el.hadPage = true
            if (el.children && el.children.length > 0) {
              this.setResourceStatus(el.children, ids, true)
            }
          } else if (el.children && el.children.length > 0) {
            this.setResourceStatus(el.children, ids, false)
          }
        })
      }
      return table
    },
    handleCustomEvent({ index, row }) {
      row.appName = this.userInfo.appName
      this.$refs.permission.handleCustomEvent({ index, row })
    },
    back() {
      this.$emit('changePage', 'roleList', {})
    },
    removeUser() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择需要删除的数据')
        return
      }
      let flag = false
      this.selectedRows.forEach(m => {
        if (m.innerFlag) {
          flag = true
        }
      })
      if (flag) {
        this.$message.warning('内置数据不能删除')
        return
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const roleId = this.userInfo.id
        if (['所有用户', '群组', '用户', '组'].includes(this.selectedRows[0].type)) {
          const params = this.selectedRows.map(m => m.id)
          removeUserById(params).then(r => {
            this.$message.success('删除成功')
            this.getUser()
          })
        } else {
          const params = []
          this.selectedRows.map(item => {
            if (item.type === '上下文') {
              params.push({
                roleId,
                contextId: item.personnelId,
                cropType: item.type,
                teamKey: null
              })
            } else {
              params.push({
                contextId: null,
                roleId,
                cropType: item.personnelId,
                teamKey: null
              })
            }
          })
          deleteRoleBatch(roleId, { data: params }).then(r => {
            this.$message.success('删除成功')
            this.getUser()
          })
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    addRoleGroup() {
      if (this.selectType === '上下文类型') {
        if (this.roles.length === 0 || this.contexts.length === 0) {
          this.$message.warning('请先选择上下文类型或角色再进行确认')
          return
        }
      } else {
        if (this.roles.length === 0 || this.contextTreeArray.length === 0) {
          this.$message.warning('请先选择上下文或角色再进行确认')
          return
        }
      }
      const arr = []
      if (this.selectType === '上下文类型') {
        this.roles.map(roleItem => {
          this.contexts.map(contextItem => {
            arr.push({
              roleId: this.userInfo.id, // 外层id
              cropType: contextItem, // 上下文类型
              teamKey: roleItem, // 角色key
              contextId: ''
            })
          })
        })
      } else {
        this.roles.map(roleItem => {
          this.contextTreeArray.map(contextItem => {
            arr.push({
              roleId: this.userInfo.id,
              contextId: contextItem.key,
              teamKey: roleItem, // 角色key
              cropType: '上下文'
            })
          })
        })
      }
      addRole({ id: this.userInfo.id, arr }).then(r => {
        this.userInfo.isUserOrTeam = 'team'
        this.handleCloseRole()
        this.$message.success('添加团队角色成功')
        this.getUser()
      })
    },
    addUserGroup() {
      // groupcheckeds(组) userGroupcheckeds(群组) users(用户)
      if (this.users.length === 0 && this.groupcheckeds.length === 0 && this.userGroupcheckeds.length === 0) {
        return this.$message.warning('请先选择组或群组或用户再进行确认')
      }
      const userGroups = []
      this.groupcheckeds.forEach(m => {
        userGroups.push({
          roleId: this.userInfo.id,
          userGroupId: m.id,
          userGroupType: 'GROUP',
          name: m.name
        })
      })
      this.userGroupcheckeds.forEach(m => {
        userGroups.push({
          roleId: this.userInfo.id,
          userGroupId: m.id,
          userGroupType: 'TEAM',
          name: m.name
        })
      })
      console.log(this.users)
      this.users.forEach(el => {
        userGroups.push({
          userGroupType: 'USER',
          name: el.userName,
          userGroupId: el.id,
          roleId: this.userInfo.id
        })
      })
      // 添加授权部门
      userGroups.forEach(m => {
        m.authOrgId = this.authOrgIds.toString()
      })
      addusers2role(this.userInfo.id, userGroups).then(r => {
        this.handleClose()
        this.$message.success('添加特定用户成功')
        this.userInfo.isUserOrTeam = 'user'
        this.getUser()
      })
    },
    _addUserGroup() {
      if (this.users.length === 0 && this.groupcheckeds.length === 0 && this.userGroupcheckeds.length === 0) {
        this.$message.warning('请先选择组或群组或用户再进行确认')
        return
      }
      const userGroups = []
      const groups = JSON.parse(JSON.stringify(this.groupcheckeds))
      const getGroups = (groupList) => {
        const arr = []
        const searchGroup = (group) => {
          group.forEach(item => {
            arr.push(item)
            if (item.children && item.children.length) searchGroup(item.children)
          })
        }
        searchGroup(groupList)
        return arr
      }
      const reGroupRemoteOptions = JSON.parse(JSON.stringify(getGroups(this.reGroupRemoteOptions)))
      groups.forEach(groupId => {
        const group = reGroupRemoteOptions.find(r => r.id === groupId.value)
        if (group) {
          userGroups.push({
            roleId: this.userInfo.id,
            userGroupId: group.id,
            userGroupType: 'GROUP',
            name: group.orgName
          })
        }
      })
      this.users.forEach(el => {
        userGroups.push({
          userGroupType: 'USER',
          name: el.userName,
          userGroupId: el.id,
          roleId: this.userInfo.id
        })
      })
      // 群组
      const userGroup = JSON.parse(JSON.stringify(this.userGroupcheckeds))
      const reUserGroupRemoteOptions = JSON.parse(JSON.stringify(getGroups(this.reUserGroupRemoteOptions)))
      userGroup.forEach(groupId => {
        const group = reUserGroupRemoteOptions.find(r => r.id === groupId.value)
        if (group) {
          userGroups.push({
            roleId: this.userInfo.id,
            userGroupId: group.id,
            userGroupType: 'TEAM',
            name: group.orgName
          })
        }
      })
      // 添加授权部门
      userGroups.forEach(m => {
        m.authOrgId = this.authOrgIds.toString()
      })
      addusers2role(this.userInfo.id, userGroups).then(r => {
        this.handleClose()
        this.$message.success('添加特定用户成功')
        this.userInfo.isUserOrTeam = 'user'
        this.getUser()
      })
    },
    addUser() {
      // 只做接口测试
      if (this.thirdSelectedRows.length === 0) {
        this.$message.warning('请先选择用户再进行确认')
      } else {
        const userId = this.thirdSelectedRows.map(el => {
          return el.id
        }).join('&userId=')
        addusers2role(this.userInfo.id, userId).then(r => {
          this.handleClose()
          this.getUser()
          return
        })
      }
    },
    // 加载授权部门下拉列表数据
    async getAuthOrgOptions(cb) {
      const service = this.$getService('Organization')
      const searchItems = service.newSearchItems()
      searchItems.$addItem('orgType', 'ORGANIZATION', 'EQ')
      const res = await service.findReursion(searchItems)
      let options = []
      if (Array.isArray(res.content)) {
        options = res.content.map(m => ({
          label: m.orgName,
          value: m.id
        }))
      }
      this.authOrgOptions = options
      typeof cb === 'function' && cb()
    },
    onOpenEditAuthOrgDialog(row) {
      if (row.type === '用户') {
        const cb = () => {
          this.authOrgVisible = true
          this.authOrgForm.record = row
          this.authOrgForm.authOrgIds = (row.authOrgId || '').split(',').filter(m => !!m).map(m => parseInt(m))
        }
        if (Array.isArray(this.authOrgOptions) && this.authOrgOptions.length > 0) {
          cb()
        } else {
          this.getAuthOrgOptions(cb)
        }
      }
    },
    onCloseEditAuthOrgDialog(flag) {
      if (flag) {
        // 确定
        const { record, authOrgIds } = this.authOrgForm
        const params = {
          ...record,
          authOrgId: authOrgIds.toString()
        }
        changeAuthOrg(params).then(res => {
          record.authOrgId = params.authOrgId
          record.authOrgName = this.authOrgOptions
            .filter(m => authOrgIds.includes(m.value))
            .map(m => m.label)
            .toString()
          this.authOrgVisible = false
          this.authOrgForm = {}
        })
      } else {
        // 取消
        this.authOrgVisible = false
      }
    },
    changeView(idx, data) {
      this.modelId = data.id
      this.permViewIdx = idx
      this.getPermByObjIdAndRoleId()
    }
  }
}
</script>
<style lang="scss">
@import "../../styles/index";
@import "../../styles/variables";
@import "../../styles/mixin";
.del-right{
  position: absolute;
  float: right;
}
.flex, .attr {
  display: flex;
  margin-bottom: 10px;
  span {
    flex: 1;
  }
}
.auto-width {
  width: 100%;
}
.assignPermissions {
  height: 100%;
  position: relative;
  background-color: #fff;
  .menu-form{
    width: 346px!important;
    .dee-form2{
      .el-form-item{
        margin-bottom: 0;
      }
    }
  }
  .sub-title {
    display: flex;
    align-items: center;
    font-size: 14px;
    img {
      cursor: pointer;
      margin-right: 5px;
      &:hover {
        text-decoration: underline;
      }
    }
    img, span {
      vertical-align: middle;
    }
  }
  .assignPermissions-tab {
    padding-bottom: 0;
    &.dee-panel .el-tabs .el-tabs__content {
      height: calc(100% - 40px) !important;
      .el-tab-pane {
        margin-bottom: 0;
        height: 100%;
      }
    }
    .tree-wrap {
      .el-tree {
        width: fit-content;
        min-width: 300px;
      }
    }
  }
  .three-member-wrap{
    height: 100%;
    overflow: auto;
    .dee-form2{
      margin-top:6px;
      .el-form-item{
        margin-bottom: 0!important;
      }
    }
  }
  .resourceTable-wrap {
    height: 100%;
    overflow: auto;
    padding: 0 10px;
    box-sizing: border-box;
  }
  .splitter-pane-resizer.vertical {
    opacity: 1;
    background-color: #F1F4F5;
    width: 6px;
    border-left: 0;
    border-right: 0;
  }
  .detail-pane {
    width: 100%;
    height: calc(100% - 6px);
  }
  .permissiom-tree-com {
    padding-top: 10px;
  }
  .el-button--primary:focus,
  .el-button--primary:hover {
    background: #5591d8 !important;
    border-color: #5591d8 !important;
    color: #fff;
  }
  .el-button--mini {
    width: 100%;
    padding: 0 0;
    border: none;
  }

  .permission-contant-tree {
    padding: 8px;
    overflow-y: auto;
    height: 100%;
  }

  /deep/
    .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    @include colorWithOpacity(background-color, 0.2);
  }

  /deep/ .el-tabs__header {
    margin-bottom: 0;
  }

  .operability {
    cursor: pointer;
  }
}
</style>