<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <el-col :span="4">
        <div class="head-container">
          <el-input
            v-model="deptName"
            clearable
            size="mini"
            placeholder="请输入部门名称"
            prefix-icon="el-icon-search"
            class="filter-item"
            @input="getDeptDatas"
          />
        </div>
        <el-tree
          :data="deptDatas"
          :props="defaultProps"
          @node-click="handleNodeClick"
        />
      </el-col>
      <!--用户数据-->
      <el-col :span="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="mini"
              placeholder="输入账号或者名称"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <el-select
              v-model="query.is_used"
              clearable
              size="mini"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
            <rrOperation />
          </div>
          <crudOperation show="" :permission="permission" />
        </div>
        <!--新增跟修改表单渲染-->
        <el-dialog
          append-to-body
          :close-on-click-modal="false"
          :before-close="crud.cancelCU"
          :visible.sync="crud.status.cu > 0"
          :title="crud.status.title"
          width="700px"
        >
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="mini" label-width="100px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model.number="form.phone" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="姓名" prop="preson_name">
              <el-input v-model="form.person_name" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" style="width: 200px;" />
            </el-form-item>
            <br v-if="!crud.status.edit">
            <el-form-item v-if="crud.status.add" label="部门" prop="depts" :rules="[{ required: true, message: '请选择部门', trigger: 'change' }]">
              <treeselect
                v-model="form.depts"
                :load-options="loadDepts"
                :options="deptDatas"
                style="width: 370px;"
                :multiple="true"
                :flat="true"
                :normalizer="normalizer"
                placeholder="选择部门类目"
              />
            </el-form-item>
            <br v-if="!crud.status.add">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" style="width: 200px;" show-password auto-complete="new-password" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="form.gender" style="width: 178px">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="is_uesd">
              <el-switch
                v-model="form.is_used"
                active-color="#409EFF"
                inactive-color="#F56C6C"
              />
            </el-form-item>
            <br v-if="!crud.status.edit">
            <el-form-item v-if="crud.status.add" style="margin-bottom: 0;" label="角色" prop="roles">
              <el-select
                v-model="roleDatas"
                style="width: 512px"
                multiple
                active-value="1"
                inactive-value="0"
                placeholder="请选择"
                @remove-tag="deleteTag"
                @change="changeRole"
              >
                <!--:disabled="level !== 1 && item.level <= level"-->
                <el-option
                  v-for="item in roles"
                  :key="item.role_id"
                  :label="item.name"
                  :value="item.role_id"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          style="width: 100%;"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column :selectable="checkboxT" type="selection" width="55" />
          <el-table-column prop="username" label="用户名" :min-width="flexWidth('username',crud.data,'用户名')" />
          <el-table-column
            prop="person_name"
            label="姓名"
            :min-width="flexWidth('person_name',crud.data,'姓名')"
          />
          <el-table-column prop="gender" label="性别" :min-width="flexWidth('gender',crud.data,'性别')" />
          <el-table-column prop="phone" label="电话" :min-width="flexWidth('phone',crud.data,'电话')" />
          <el-table-column prop="email" label="邮箱" :min-width="flexWidth('email',crud.data,'邮箱')" />
          <el-table-column show-overflow-tooltip prop="depts" label="部门" :min-width="flexWidth('depts',crud.data,'邮箱')">
            <template slot-scope="scope">
              <span v-for="(item, index) in scope.row.depts" :key="index">
                {{ item.name }}<span v-if="index !== scope.row.depts.length - 1">、</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="enabled">
            <template slot-scope="scope">
              <span :style="{'color': caseStatusColorFilter(scope.row.is_used)}">{{ enabledTypeOptions.find(item => {return item.key == scope.row.is_used}).display_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建日期" :min-width="flexWidth('create_time',crud.data,'创建日期')" />
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="crud.toEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handdeleted(scope.row)">删除</el-button>
              <el-dropdown v-hasPermi="['system:user:resetPwd', 'system:user:edit']" size="mini">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item icon="el-icon-refresh-right"><span @click="resetPassword(scope.row)">重置密码</span></el-dropdown-item>
                  <el-dropdown-item icon="el-icon-key">
                    <span @click="openDeptDrawer(scope.row)">部门权限</span>
                  </el-dropdown-item>
                  <el-dropdown-item icon="el-icon-key">
                    <span @click="openDataDialog(scope.row)">数据权限</span>
                  </el-dropdown-item>
                  <el-dropdown-item icon="el-icon-lock"><span @click="changeEnabled(scope.row)">{{ enabledTypeOptions.find(item => {return item.key !== scope.row.is_used}).display_name }}账号</span></el-dropdown-item>
                  <el-dropdown-item icon="el-icon-circle-check">
                    <span @click="openRoleDrawer(scope.row)">分配角色</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
    <el-drawer
      :title="drawerTitle"
      :visible.sync="syncDrawer"
      direction="rtl"
      :before-close="handleClose"
      :wrapper-closable="false"
      size="35%"
      @close="clearCheck"
    >
      <div style="margin: 0 20px 0 20px; height: 100%">
        <div style="height: 90%">
          <el-tree
            v-if="flag"
            ref="deptUser"
            show-checkbox
            default-expand-all
            :data="deptsDatas"
            :default-checked-keys="depChecked"
            :props="deptProps"
            node-key="dept_id"
            highlight-current
            check-strictly
            @check="handCheck"
            @check-change="checkChange"
            @close="clearCheck"
          />
          <el-table
            v-if="!flag"
            ref="roleTable"
            highlight-current-row
            style="width: 100%;"
            :data="rolesDatas"
            @selection-change="crud.selectionChangeHandler"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="角色名称" min-width="100" show-overflow-tooltip />
          </el-table>
        </div>
        <div style="height: 10%">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="saveChecked">保 存</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      :close-on-click-modal="true"
      :visible.sync="dataPerm"
      :title="dataPermissionTitle"
      width="700px"
    >
      <el-form ref="form" :inline="true" :model="dataDialog" :rules="rules" size="mini" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dataDialog.username" disabled style="width: 200px;" />
        </el-form-item>
        <el-form-item label="姓名" prop="person_name">
          <el-input v-model="dataDialog.person_name" disabled style="width: 200px;" />
        </el-form-item>
        <el-table
          ref="dialogTable"
          :data="dataDialog.dataScopeType"
          style="width: 100%;"
          @selection-change="getRows"
        >
          <el-table-column :selectable="checkboxT" type="selection" width="55" />
          <el-table-column prop="label" label="权限范围" />
          <el-table-column label="数据权限">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.permission_id"
                placeholder="请选择"
                @change="openRelevance(scope.row, scope.$index)"
              >
                <el-option
                  v-for="item in permissions"
                  :key="item.permission_id"
                  :label="item.name"
                  :value="item.permission_id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="showDatas(scope.row)">查看明细</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDataPerm">取消</el-button>
        <el-button type="primary" @click="savePermise()">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="true"
      :visible.sync="showData"
      :title="dataPermissionTitle"
      width="700px"
    >
      <el-table
        ref="dialogTable"
        :data="dataPermissions"
        style="width: 100%; max-height: 500px"
      >
        <el-table-column prop="permission_scope_type" label="权限类型" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ dict.label.permission_scope_type[scope.row.permission_scope_type] }}
          </template>
        </el-table-column>
        <el-table-column prop="permissionName" label="权限范围" min-width="100" show-overflow-tooltip />
        <el-table-column prop="deptName" label="部门名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="person_name" label="用户名称" min-width="100" show-overflow-tooltip />
      </el-table>
    </el-dialog>
    <relevance-user-dialog :dialog-show.sync="relevanceUser" :is-single="false" :users="userIds" @selectUsers="selectUsers" />
    <relevance-dept-dialog :dialog-show.sync="relevanceDept" :is-single="false" :depts="deptIds" @selectDepts="selectDepts" />
  </div>
</template>

<script>
import crudUser from '@/views/system/user/user'
import crudDept from '../dept/dept'
import crudDataPermission from '@/views/system/dataPermission/dataPermission'
import { getAll, getLevel } from '@/views/system/role/role'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import { mapGetters } from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import RelevanceUserDialog from '@/views/system/user/dialog/relevanceUserDialog'
import RelevanceDeptDialog from '@/views/system/user/dialog/relevanceDeptDialog'

let userRoles = []
const defaultForm = {
  dept_id: null,
  depts: [],
  username: null,
  person_name: null,
  gender: '男',
  email: null,
  is_used: true,
  roles: [],
  phone: null,
  password: null
}
export default {
  name: 'User',
  components: { RelevanceDeptDialog, RelevanceUserDialog, Treeselect, crudOperation, rrOperation, udOperation, pagination },
  cruds() {
    return CRUD({ title: '用户', idField: 'user_id', url: 'api/users', crudMethod: { ...crudUser }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status', 'permission_scope_type'],
  data() {
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], level: 3, roles: [],
      roleDatas: [], // 多选时使用
      defaultProps: { children: 'children', label: 'name' },
      deptProps: { children: 'children', label: 'name' },
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del']
      },
      enabledTypeOptions: [
        { key: true, display_name: '激活' },
        { key: false, display_name: '锁定' }
      ],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        person_name: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      syncDrawer: false,
      depChecked: [],
      depCheckedId: '',
      deptsDatas: [],
      rolesDatas: [],
      drawerTitle: '',
      flag: true,
      dataPerm: false,
      dataDialog: {},
      permissions: [],
      permission_id: '',
      multipleSelection: [], // 选中
      relevanceUser: false, // 关联用户
      rowData: {}, // 当行数据
      relevanceDept: false, // 关联部门
      deptIds: [],
      userIds: [],
      showData: false,
      dataPermissions: [],
      dataPermissionTitle: '数据权限'
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  beforeMount() {
    this.deptTree()
  },
  created() {
    this.crud.msg.add = '新增成功'
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    changeRole(value) {
      userRoles = []
      value.forEach(function(data, index) {
        const role = { id: data }
        userRoles.push(role)
      })
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    caseStatusColorFilter(is_used) {
      if (is_used === true) {
        return '#378be2'
      }
      return '#F56C6C'
    },
    handdeleted(datas) {
      this.$confirm(`确认删除选中的1条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles()
      if (form.dept_id == null) {
        crudDept.getDepts()
      } else {
        this.getSupDepts(form.dept_id)
      }
      // this.getRoleLevel() 暂时不用
      // form.is_used = form.enabled.toString()
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.form.password = '123456'
      this.roleDatas = []
    },
    // 初始化编辑时候的角色与岗位
    [CRUD.HOOK.beforeToEdit](crud, form) {
      crud.status.edit
      this.roleDatas = []
      userRoles = []
      const _this = this
      if (form.roles !== null && form.roles.length > 0) {
        form.roles.forEach(function(role, index) {
          _this.roleDatas.push(role)
          const rol = { id: role }
          userRoles.push(rol)
        })
      }
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.depts) {
        this.$message({
          message: '部门不能为空',
          type: 'warning'
        })
        return false
      } else if (this.roleDatas.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }
      const roles = []
      userRoles.forEach(function(data, index) {
        roles.push(data.id)
      })
      crud.form.roles = roles
      return true
    },
    // 获取左侧部门数据
    getDeptDatas(node, resolve) {
      setTimeout(() => {
        var q = {}
        // eslint-disable-next-line eqeqeq
        if (node != '') {
          q = { name: node }
        }
        crudDept.getDeptTree(q).then(res => {
          if (resolve) {
            resolve(res.content)
          } else {
            this.deptDatas = res.content
          }
        })
      }, 100)
    },

    deptTree() {
      setTimeout(() => {
        crudDept.getDeptTree().then(res => {
          this.deptDatas = res.content
        })
      }, 100)
    },
    getDepts() {
      crudDept.getDepts({ is_used: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupDepts(deptId) {
      crudDept.getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDept.getDeptvo({ is_used: true, pid: parentNode.dept_id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            obj.children = null
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    normalizer(node) {
      return {
        id: node.dept_id,
        label: node.name,
        children: node.children
      }
    },
    // 切换部门
    handleNodeClick(data) {
      this.query.dept_id = data.dept_id
      this.query.needAll = true
      this.crud.toQuery()
      this.query.dept_id = null
    },
    // 改变状态
    changeEnabled(row) {
      const satus = this.enabledTypeOptions.find(item => { return item.key !== row.is_used })
      this.$confirm('此操作将' + satus.display_name + '账号：' + row.username + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.is_used = satus.key
        crudUser.edit(row).then(res => {
          this.crud.toQuery()
          this.crud.notify('账号' + row.username + '已' + satus.display_name)
        })
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => {
      })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => {
      })
    },
    checkboxT(row, rowIndex) {
      // return row.id !== this.user.id
      return true
    },
    resetPassword(row) {
      this.$confirm(`确认重置密码？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.password = '123456'
        crudUser.edit(row).then(res => {
          this.crud.toQuery()
          this.crud.notify('密码重置成功，密码:123456', CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
      })
    },
    // 部门权限
    openDeptDrawer(row) {
      crudDept.getDeptTree().then(res => {
        this.deptsDatas = res.content
      })
      this.openDrawer() // 打开抽屉
      this.drawerTitle = '分配部门权限'
      this.flag = true
      // 默认选中
      const deptIds = []
      for (var index in row.depts) {
        deptIds.push(row.depts[index].dept_id)
      }
      this.$nextTick(() => {
        this.$refs.deptUser.setCheckedKeys(deptIds)
      })
      this.giveValue(row)
    },
    // 角色权限
    openRoleDrawer(row) {
      this.rolesDatas = []
      getAll().then(res => {
        this.rolesDatas = res
        // 回显默认选中
        this.$nextTick(function() {
          for (let j = 0; j < row.roles.length; j++) {
            for (let i = 0; i < this.rolesDatas.length; i++) {
              if (this.rolesDatas[i].roleId == row.roles[j].roleId) {
                this.$refs.roleTable.toggleRowSelection(this.rolesDatas[i], true)
                break
              }
            }
          }
        })
      })
      this.openDrawer()
      this.drawerTitle = '分配角色权限'
      this.flag = false
      this.giveValue(row)
    },
    openDataDialog(row) {
      // 清空数据 应该需要初始化赋值
      this.dataDialog = {}
      this.multipleSelection = []
      // 获取权限范围
      crudDataPermission.getDataScopeType().then(res => {
        console.log('权限范围', res)
        this.dataDialog.dataScopeType = res
        // permissions
        crudDataPermission.getDataPermissionOption().then(res => {
          console.log('数据权限', res)
          this.permissions = res
          this.dataDialog.person_name = row.person_name
          this.dataDialog.username = row.username
          this.dataDialog.user_id = row.user_id
          this.dataPermissionTitle = '[' + row.person_name + '] 数据权限'
          this.dataPerm = true
          // 回显数据
          crudDataPermission.getDataShow(row.user_id).then(res => {
            console.log('要回显的数据', res)
            this.$nextTick(function() {
              for (var index = 0; index < res.length; index++) {
                for (var i = 0; i < this.dataDialog.dataScopeType.length; i++) {
                  if (this.dataDialog.dataScopeType[i].value == res[index].permissionScopeType) {
                    this.dataDialog.dataScopeType[i].permission_id = res[index].permission_id
                    if (res[index].users) this.dataDialog.dataScopeType[i].users = res[index].users
                    if (res[index].depts) this.dataDialog.dataScopeType[i].depts = res[index].depts
                    // 选中
                    this.$refs.dialogTable.toggleRowSelection(this.dataDialog.dataScopeType[i], true)
                    break
                  }
                }
              }
            })
          })
        })
      })
    },
    getRows(val) { // 获取行数据
      this.multipleSelection = val
    },
    openRelevance(row, index) {
      for (var i = 0; i < this.permissions.length; i++) {
        if (this.permissions[i].permission_id != undefined && this.permissions[i].permission_id && this.permissions[i].permission_id != row.permission_id) {
          this.$delete(this.dataDialog.dataScopeType[index], this.permissions[i].permission_id.toString())
        }
      }
      this.$set(this.dataDialog.dataScopeType[index], this.dataDialog.dataScopeType[index].permission_id, row.permission_id)
      this.rowData = {}
      this.deptIds = []
      this.userIds = []
      if (row.permission_id == '1605129738328870912') { // 选择用户
        this.userIds = this.dataDialog.dataScopeType[index].users
        this.rowData = row
        this.relevanceUser = true
      } else if (row.permission_id == '1605129882164137984') { // 选择部门
        this.deptIds = this.dataDialog.dataScopeType[index].depts
        this.rowData = row
        this.relevanceDept = true
      } else if (row.permission_id == '1605128919449735168') { // 自身
        const param = {
          userId: this.dataDialog.userId
        }
        this.dataDialog.dataScopeType[index].users = []
        this.dataDialog.dataScopeType[index].users.push(param)
      } else { // 其他应该清空
        this.dataDialog.dataScopeType[index].depts = []
        this.dataDialog.dataScopeType[index].users = []
      }
    },
    selectUsers(row) { // row对话框传来的数据
      for (var i = 0; i < this.dataDialog.dataScopeType.length; i++) {
        if (this.dataDialog.dataScopeType[i].dict_id == this.rowData.dict_id) {
          if (this.dataDialog.dataScopeType[i].depts != undefined && this.dataDialog.dataScopeType[i].depts.length > 0) this.dataDialog.dataScopeType[i].depts = []
          this.dataDialog.dataScopeType[i].users = row
          break
        }
      }
      this.rowData = {}
    },
    selectDepts(row) {
      for (var i = 0; i < this.dataDialog.dataScopeType.length; i++) {
        if (this.dataDialog.dataScopeType[i].dict_id == this.rowData.dictId) {
          if (this.dataDialog.dataScopeType[i].users != undefined && this.dataDialog.dataScopeType[i].users.length > 0) this.dataDialog.dataScopeType[i].users = []
          this.dataDialog.dataScopeType[i].depts = row
          break
        }
      }
      this.rowData = {}
    },
    cancelDataPerm() {
      this.dataPerm = false
    },
    savePermise() {
      const param = {
        user_id: this.dataDialog.user_id,
        datas: this.multipleSelection
      }
      crudDataPermission.saveDataPermission(param).then(res => {
        this.dataPerm = false
        this.crud.notify('添加数据权限成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.toQuery()
      })
    },
    openDrawer() {
      this.syncDrawer = true
      this.depCheckedId = ''
      this.depChecked = []
    },
    giveValue(row) {
      this.depCheckedId = row.user_id
    },
    clearCheck() { // 清空选中
      if (this.flag) this.$refs.deptUser.setCheckedKeys([])
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    cancelForm() { // 关闭
      this.syncDrawer = false
      if (this.flag) this.clearCheck()
    },
    saveChecked() {
      const user = {
        user_id: this.depCheckedId
      }
      if (this.flag) {
        user.deptIds = this.$refs.deptUser.getCheckedKeys()
      } else {
        user.rolesIds = this.crud.selections.map(item => (item.role_id))
      }
      crudUser.edit(user).then(res => {
        this.cancelForm()
        this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.crud.toQuery()
      })
    },
    // 覆盖原有勾选功能，父与子关联，子与父不关联
    handCheck(data, node) {
      this.hanleCheck(data, node, 'deptUser')
    },
    hanleCheck(data, node, treeName) {
      const _this = this
      // 获取当前节点是否被选中
      const isChecked = _this.$refs[treeName].getNode(data).checked
      // 如果当前节点被选中，则遍历下级子节点并选中，如果当前节点取消选中，则遍历下级节点并取消
      if (isChecked) {
        // 判断该节点是否有下级节点，如果有那么遍历设置下级节点为选中
        data.children && data.children.length > 0 && setChildreChecked(data.children, true)
      } else {
        // 如果节点取消选中，则取消该节点下的子节点选中
        data.children && data.children.length > 0 && setChildreChecked(data.children, false)
      }
      function setChildreChecked(node, isChecked) {
        node.forEach(item => {
          item.children && item.children.length > 0 && setChildreChecked(item.children, isChecked)
          // 修改勾选状态
          _this.$refs[treeName].setChecked(item.name, isChecked)
        })
      }
    },
    checkChange(data, checked, indeterminate) {
      const _this = this
      // console.log(data, checked, indeterminate);
      // 选中全部子节点，父节点也默认选中，但是子节点再次取消勾选或者全部子节点取消勾选也不会影响父节点勾选状态
      const checkNode = _this.$refs.deptUser.getNode(data)// 获取当前节点
      // 勾选部分子节点，父节点变为半选状态
      if (checkNode.parent && checkNode.parent.childNodes.some(ele => ele.checked)) {
        checkNode.parent.indeterminate = true
      }
      // 勾选全部子节点，父节点变为全选状态
      if (checkNode.parent && checkNode.parent.childNodes.every(ele => ele.checked)) {
        checkNode.parent.checked = true
        checkNode.parent.indeterminate = false
      }
      // 如果取消所有第二节点的勾选状态，则第一层父节点也取消勾选
      if (checkNode.level == 2 && checkNode.parent.childNodes.every(ele => !ele.checked)) {
        checkNode.parent.checked = false
        checkNode.parent.indeterminate = false
      }
    },
    showDatas(row) {
      const param = {
        userId: this.dataDialog.userId,
        permissionScopeType: row.value
      }
      crudDataPermission.getDataDetail(param).then(res => {
        this.dataPermissions = res
      })
      this.showData = true
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
