<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <el-col class="shudao" :xs="9" :sm="6" :md="5" :lg="6" :xl="4">
        <div class="head-container">
          <el-input
            v-model="deptName"
            clearable
            size="small"
            placeholder="输入部门名称搜索"
            prefix-icon="el-icon-search"
            class="filter-item"
            @input="getDeptDatas"
          />
        </div>
        <el-tree
          :data="deptDatas"
          :load="getDeptDatas"
          :props="defaultProps"
          highlight-current
          :expand-on-click-node="false"
          lazy
          @node-click="handleNodeClick"
        />
      </el-col>
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="18" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入名称/联系方式/邮箱搜索"
              style="width: 250px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <date-range-picker v-model="query.createTime" class="date-item" />
            <rrOperation />
          </div>
          <crudOperation :permission="permission" />
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-edit"
            :disabled="crud.selections.length !== 1"
            @click="faceConfigClick(crud.selections[0])"
          >配置人脸照
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-edit"
            :disabled="crud.selections.length !== 1"
            @click="toRoomDevice(crud.selections[0])"
          >配置门禁权限
          </el-button>
        </div>
        <!--配置人脸照-->
        <el-dialog title="配置人脸照片" :visible.sync="faceConfig">
          <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
            <el-form-item label="姓名:">
              <el-input v-model="form.name" style="width: 370px;" :disabled="true" />
            </el-form-item>
            <el-form-item label="员工工号:">toRoomDevice
              <el-input v-model="form.userNumber" style="width: 370px;" :disabled="true" />
            </el-form-item>
            <!--   上传文件   -->
            <el-form-item label="人脸照片">
              <el-upload
                class="avatar-uploader"
                :headers="headers"
                :action="imagesUploadApi"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :file-list="fileList"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <div slot="tip" class="el-upload__tip">照片要求：<span style="color: red;font-size: 15px">420*780/1080*1080</span> </div>
                <div slot="tip" class="el-upload__tip">照片用途：人脸照片将用于门禁/考勤/消费类结算，请务必上传本人近照，照片务必为人脸照；且清晰呈现人脸面部</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="cancelFaceConfigClick">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="submitFaceConfigClick">确认</el-button>
          </div>
        </el-dialog>
        <!-- 配置门禁权限 -->
        <el-dialog :visible.sync="devicePz" title="配置门禁权限" width="50%">
          <!--用户数据-->
          <el-row>
            <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
              <el-descriptions style="margin-left:20px">
                <el-descriptions-item label="姓名">
                  <span style="color:red">{{ roomDeviceItem.name }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="员工工号">
                  <span style="color:red">{{ roomDeviceItem.userNumber }}</span>
                </el-descriptions-item>
              </el-descriptions>
              <br>
              <!--工具栏-->
              <div class="head-container">
                <!-- 搜索 -->
                <el-input
                  v-model="name"
                  type="text"
                  size="small"
                  placeholder="输入设备名称"
                  style="width: 200px;"
                  class="filter-item"
                />
                <span>
                  <el-button
                    class="filter-item"
                    size="mini"
                    type="success"
                    icon="el-icon-search"
                    @click="queryRoomUser()"
                  >搜索</el-button>
                  <el-button
                    class="filter-item"
                    size="mini"
                    type="warning"
                    icon="el-icon-refresh-left"
                    @click="resetQuery()"
                  >重置</el-button>
                </span>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="17">
              <el-table
                ref="multipleTable"
                v-loading="crud.loading"
                :data="devices"
                tooltip-effect="dark"
                height="500"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  width="55"
                  :selectable="selectable"
                />
                <el-table-column :show-overflow-tooltip="true" prop="id" label="id" />
                <el-table-column :show-overflow-tooltip="true" prop="doorID" label="门禁id" />
                <el-table-column :show-overflow-tooltip="true" prop="code" label="设备编号" />
                <el-table-column :show-overflow-tooltip="true" prop="name" label="设备名称" />
                <el-table-column prop="buildAddress" label="设备安装位置" />
              </el-table>
              <!--分页组件-->
              <!-- <el-pagination
                :page-size.sync="size"
                :total="total"
                :current-page.sync="page"
                style="margin-top: 8px;"
                layout="total, prev, pager, next, sizes"
                @size-change="getAllDevices()()"
                @current-change="getAllDevices()"
              /> -->
            </el-col>
            <el-col :span="6" :push="1">
              <el-card style="height: 100%;">
                <div>您已选择:</div>
                <!-- <div>{{ getMultipleSelection(multipleSelection) }}</div> -->
                <div style="height: 443px;overflow: auto;">{{ checkInfo }}</div>
              </el-card>
            </el-col>
          </el-row>
          <div slot="footer">
            <el-row>
              <el-col :xs="10" :sm="10" :md="10" :lg="15" :xl="15">
                <el-button style="" class="filter-item" @click="toggleSelection()">取消选择</el-button>
                <el-button class="filter-item" style="margin-left:20% ;" @click="selected()">选择</el-button>
              </el-col>
            </el-row>
          </div>
        </el-dialog>
        <!--详情信息-->
        <el-dialog :visible.sync="detailsConfig" width="40%">
          <img v-if="form.picture" :src="form.picture" style="width:70px;height:70px">
          <div style="display: inline-block;">
            <label style="font-size:20px">{{ form.name }}</label><br>
            <label>{{ form.dept.name }}/{{ form.jobs && form.jobs.map(item => item.name).join(',') }}</label>
          </div>
          <br><br>
          <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
            <el-tabs type="border-card">
              <el-tab-pane label="基本信息">
                <el-descriptions title="基本信息">
                  <el-descriptions-item label="员工姓名">{{ form.name }}</el-descriptions-item>
                  <el-descriptions-item label="员工工号">{{ form.userNumber }}</el-descriptions-item>
                  <el-descriptions-item label="所属部门">{{ form.dept.name }}</el-descriptions-item>
                  <el-descriptions-item label="当前职务">
                    {{ form.jobs && form.jobs.map(item => item.name).join(',') }}
                  </el-descriptions-item>
                  <el-descriptions-item label="人员种类">{{ dict.label.user_type[form.usertype] }}</el-descriptions-item>
                  <el-descriptions-item label="手机号">{{ form.contacts }}</el-descriptions-item>
                  <el-descriptions-item label="邮箱地址">{{ form.email }}</el-descriptions-item>
                  <el-descriptions-item label="是否审批人">{{ dict.label.is_true[form.isApprover] }}</el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
              <el-tab-pane label="人脸照片">
                <el-descriptions title="人脸照片" :column="1" :colon="false">
                  <el-descriptions-item>
                    <img v-if="form.picture" :src="form.picture" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-descriptions-item>
                  <el-descriptions-item label="照片要求：">人脸照片将用于门禁/考勤/消费类结算，请务必上传本人近照，照片务必为人脸照；且清晰呈现人脸面部
                  </el-descriptions-item>
                </el-descriptions>
              </el-tab-pane>
              <el-tab-pane label="门禁权限">
                <h3>门禁权限</h3>
                <el-table :data="dataRoomXq" border>
                  <el-table-column prop="id" label="id" />
                  <el-table-column prop="code" label="设备编号" />
                  <el-table-column prop="name" label="设备名称" />
                  <el-table-column prop="buildAddress" label="设备安装位置" />
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </el-dialog>

        <!--表单渲染-->
        <el-dialog
          append-to-body
          :close-on-click-modal="false"
          :before-close="crud.cancelCU"
          :visible="crud.status.cu > 0"
          :title="crud.status.title"
          width="570px"
        >
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="form.sex" style="width: 178px">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系方式">
              <el-input v-model="form.contacts" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" style="width: 370px;" />
            </el-form-item>
            <el-form-item label="部门" prop="dept.id">
              <treeselect
                v-model="form.dept.id"
                :options="depts"
                :load-options="loadDepts"
                style="width: 178px"
                placeholder="选择部门"
              />
            </el-form-item>
            <el-form-item label="岗位" prop="jobs">
              <el-select
                v-model="jobDatas"
                style="width: 178px"
                multiple
                placeholder="请选择"
                @remove-tag="deleteTag"
                @change="changeJob"
              >
                <el-option
                  v-for="item in jobs"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否是访客审批人">
              <el-radio-group v-model="form.isApprover" style="width: 370px">
                <el-radio
                  v-for="item in dict.is_true"
                  :key="item.id"
                  :label="item.value"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="margin-bottom: 0;" label="角色" prop="roles">
              <el-select
                v-model="roleDatas"
                style="width: 437px"
                multiple
                placeholder="请选择"
                @remove-tag="deleteTag"
                @change="changeRole"
              >
                <el-option
                  v-for="item in roles"
                  :key="item.name"
                  :disabled="level !== 1 && item.level <= level"
                  :label="item.name"
                  :value="item.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 :show-overflow-tooltip="true" prop="userNumber" label="人员编号" />
          <el-table-column :show-overflow-tooltip="true" prop="name" label="姓名" />
          <el-table-column :show-overflow-tooltip="true" prop="sex" label="性别" />
          <el-table-column :show-overflow-tooltip="true" prop="cardId" label="卡号" />
          <el-table-column :show-overflow-tooltip="true" prop="contacts" label="联系方式" />
          <el-table-column :show-overflow-tooltip="true" prop="email" label="邮箱" />
          <el-table-column :show-overflow-tooltip="true" prop="dept" label="部门">
            <template slot-scope="scope">
              <div>{{ scope.row.dept.name }}</div>
            </template>
          </el-table-column>
          <!--          <el-table-column :show-overflow-tooltip="true" prop="isApprover" label="是否是访客审批者">-->
          <!--            <template slot-scope="scope">-->
          <!--              <div v-if="scope.row.isApprover == 1">是</div>-->
          <!--              <div v-if="scope.row.isApprover == 0">否</div>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column :show-overflow-tooltip="true" prop="picture" label="人脸">
            <template slot-scope="scope">
              <el-image :src="scope.row.picture" />
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="updateTime" width="135" label="最后更新日期" />
          <el-table-column
            v-if="checkPer(['admin','dmUser:edit','dmUser:del'])"
            label="操作"
            width="115"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <!--              <udOperation-->
              <!--                :data="scope.row"-->
              <!--                :permission="permission"-->
              <!--                :disabled-edit="scope.row.usertype === '00'"-->
              <!--                :disabled-dle="scope.row.id === user.id"-->
              <!--              />-->
              <el-dropdown>
                <el-button type="primary">
                  更多<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="faceConfigClick(scope.row)">配置人脸照片</el-dropdown-item>
                  <el-dropdown-item @click.native="toRoomDevice(scope.row)">配置门禁权限</el-dropdown-item>
                  <el-dropdown-item @click.native="openDetailsConfig(scope.row)">详情</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudDmUser from '@/api/dm/user/dmUser'
import { isvalidPhone } from '@/utils/validate'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import { getAll, getLevel } from '@/api/system/role'
import { getAllJob } from '@/api/system/job'
import CRUD, { presenter, header, form, crud } 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 DateRangePicker from '@/components/DateRangePicker'
import Treeselect from '@riophae/vue-treeselect'
import { mapGetters } from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import { queryRoomDeviceByUser, queryRoomAllDevice } from '@/api/dmRoomDevice'
import { getToken } from '@/utils/auth'

let userRoles = []
let userJobs = []
const defaultForm = {
  id: null,
  name: null,
  nickName: null,
  sex: '男',
  email: null,
  enabled: 'false',
  roles: [],
  jobs: [],
  dept: { id: null },
  contacts: null,
  isApprover: '0',
  picture: null,
  usertype: null
}//, isApprover: null
const optShow = {
  add: false,
  edit: false,
  del: false,
  download: true,
  reset: true
}
export default {
  name: 'User',
  components: { Treeselect, crudOperation, rrOperation, pagination, DateRangePicker },
  cruds() {
    return CRUD({
      title: '用户管理',
      url: 'api/dmUser',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudDmUser },
      optShow
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status', 'is_true', 'user_type'],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      headers: { 'Authorization': getToken() },
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], jobs: [], level: 3, roles: [],
      jobDatas: [],
      roleDatas: [], // 多选时使用
      devicePz: false,
      detailItem: {}, // 详情
      roomDeviceItem: {}, // 门禁设备
      devices: [], // 全部设备的容器
      deviceByUser: [], // 用户自己的
      name: '', // 设备名称
      deviceType: 1, // 设备类型
      checkInfo: '', // 设备右边选择后显示
      size: 0,
      page: 0,
      total: 0,
      fileList: [],
      pictureIsMax: false,
      imageUrl: '',
      faceConfig: false,
      detailsConfig: false,
      dataRoomXq: [], // 门禁设备详情
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '激活' },
        { key: 'false', display_name: '锁定' }
      ],
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' }/* ,
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' } */
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        'dept.id': [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        contacts: [
          { required: true, trigger: 'blur', validator: validPhone }
        ]
      },
      multipleSelection: crud.selectData || []
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi',
      'imagesUploadApi'
    ])
  },
  watch: {
    'query.blurry': {
      handler: function(val) {
        this.query.blurry = val.toString().replaceAll(' ', '')
        console.log(this.query.blurry)
      }
    },
    'crud.selectData': {
      handler: function(datainfo) {
        this.$nextTick(function() {
          console.info('crud.selectData', crud.selectData)
          this.toggleSelection()
          this.devices.forEach((item, i) => {
            datainfo.forEach(row => {
              if (this.devices[i].id === row) {
                this.$refs.multipleTable.toggleRowSelection(this.devices[i])
                this.setCheckInfo()
              }
            })
          })
        })
      },
      deep: true
    },
    multipleSelection: {
      handler: function() {
        this.setCheckInfo()
      }
    }
  },
  created() {
    this.crud.msg.add = '新增成功'
    // 查询全部设备
    this.getAllDevices()
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    resetQuery() {
      this.name = null
    },
    getMultipleSelection(arr) {
      if (arr) {
        const names = []
        arr.forEach(ar => {
          names.push(ar.name)
        })
        return names.join()
      }
    },
    toDetail(row) {
      console.log(row)
    },
    // 配置设备
    toRoomDevice(row) {
      console.log(row)
      this.roomDeviceItem = row
      this.getDevices()
      // 开启菜单
      this.devicePz = true
    },
    // 查询所有设备
    async getAllDevices() {
      await queryRoomAllDevice({
        buildAddress: null,
        code: null,
        // deviceType: this.deviceType,
        deviceType: null,
        name: this.name
        // page:this.page,
        // size:this.size
      }).then(res => {
        this.devices = res
        // this.total = res.totalElements
      }).catch(() => {
      })
    },
    // 根据用户查询设备
    async getDevices() {
      queryRoomDeviceByUser({
        code: this.roomDeviceItem.id,
        // deviceType: this.deviceType
        deviceType: null
      }).then(res => {
        this.deviceByUser = res
        this.dataRoomXq = res
        // this.devicePz = true
        this.$nextTick(function() {
          this.$refs.multipleTable.clearSelection()
          // 开始替换数据
          this.devices.forEach(ite => {
            this.deviceByUser.forEach(user => {
              if (ite.id === user.id) {
                this.$refs.multipleTable.toggleRowSelection(ite)
                //  this.multipleSelection.push(ite)
              }
            })
          })
        })
      }).catch(() => {
      })
    },
    queryRoomUser() {
      const _this = this
      _this.getAllDevices().then(res => {
        _this.getDevices()
      })
      // setTimeout(function() {
      //   _this.getDevices()
      // }, 1100)
      // new Promise(function(resolve, reject) {
      //   try {
      //     _this.getAllDevices()
      //     resolve()
      //   } catch (error) {
      //     reject()
      //   }
      // }).then(() => {
      //   _this.getDevices()
      // }, () => {
      // })
    },
    selectable(row, index) {
      // 设备状态(00-启用、01-禁用、02-待维修)
      if (row.status !== '01' && row.status !== '02') {
        // 可选返回true
        return true
      } else {
        // 禁用返回false
        return false
      }
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function(data, index) {
        const role = { id: data }
        userRoles.push(role)
      })
    },
    changeJob(value) {
      userJobs = []
      value.forEach(function(data, index) {
        const job = { id: data }
        userJobs.push(job)
      })
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles()
      if (form.id == null) {
        this.getDepts()
      } else {
        this.getSupDepts(form.dept.id)
      }
      this.getRoleLevel()
      this.getJobs()
      form.enabled = form.enabled.toString()
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.jobDatas = []
      this.roleDatas = []
    },
    // 初始化编辑时候的角色与岗位
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.getJobs(this.form.dept.id)
      this.jobDatas = []
      this.roleDatas = []
      userRoles = []
      userJobs = []
      const _this = this
      form.roles.forEach(function(role, index) {
        _this.roleDatas.push(role.id)
        const rol = { id: role.id }
        userRoles.push(rol)
      })
      form.jobs.forEach(function(job, index) {
        _this.jobDatas.push(job.id)
        const data = { id: job.id }
        userJobs.push(data)
      })
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.dept.id) {
        this.$message({
          message: '部门不能为空',
          type: 'warning'
        })
        return false
      } else if (this.jobDatas.length === 0) {
        this.$message({
          message: '岗位不能为空',
          type: 'warning'
        })
        return false
      } else if (this.roleDatas.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }
      crud.form.roles = userRoles
      crud.form.jobs = userJobs
      return true
    },
    // 获取左侧部门数据
    getDeptDatas(node, resolve) {
      const sort = 'id,desc'
      const params = { sort: sort }
      if (typeof node !== 'object') {
        if (node) {
          params['name'] = node
        }
      } else if (node.level !== 0) {
        params['pid'] = node.data.id
      }
      setTimeout(() => {
        getDepts(params).then(res => {
          if (resolve) {
            resolve(res.content)
          } else {
            this.deptDatas = res.content
          }
        })
      }, 100)
    },
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupDepts(deptId) {
      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) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 切换部门
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.query.deptId = null
      } else {
        this.query.deptId = data.id
      }
      this.crud.toQuery()
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => {
      })
    },
    // 获取弹窗内岗位数据
    getJobs() {
      getAllJob().then(res => {
        this.jobs = res.content
      }).catch(() => {
      })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => {
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    },
    // 人脸照片
    handleAvatarSuccess(res, file) {
      this.form.picture = 'https://smartpark.caih.com/static/yktres/' + res.realName
      this.imageUrl = (process.env.NODE_ENV !== 'production' ? this.baseApi + '/file/' + res.realName : 'https://smartpark.caih.com/static/yktres/' + res.realName)
      console.log('res', res)
      console.log('file', file)
    },
    beforeAvatarUpload(file) {
      // eslint-disable-next-line no-unused-vars
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG和PNG 格式!')
        return false
      } else {
        // // 调用[限制图片尺寸]函数
        const _this = this
        const MIN_WIDTH = 420
        const MIN_HEIGHT = 780
        const MAX_WIDTH = 1080
        const MAX_HEIGHT = 1080
        // eslint-disable-next-line no-unused-vars
        let imgWidth = ''
        // eslint-disable-next-line no-unused-vars
        let imgHeigth = ''
        // eslint-disable-next-line no-unused-vars
        const isSize = new Promise(function(resolve, reject) {
          const _URL = window.URL || window.webkitURL
          const img = new Image()
          img.src = _URL.createObjectURL(file)
          img.onload = function() {
            imgWidth = img.width
            imgHeigth = img.height
            // const MAX_VALID = img.width === MAX_WIDTH && img.height === MAX_HEIGHT
            const wid = (img.width >= MIN_WIDTH && img.height >= MIN_HEIGHT) && (img.width <= MAX_WIDTH && img.height <= MAX_HEIGHT)
            if (!wid) {
              // _this.$message.warning('图片不符合规则: 当前图片的高为: ' + imgWidth + ' 宽为: ' + imgHeigth)
              reject()
            } else {
              resolve()
            }
          }
        }).then(() => {
          return file
        }, () => {
          _this.$message.warning('图片不符合规则: 当前图片的高为: ' + imgWidth + ' 宽为: ' + imgHeigth)
          return Promise.reject()
        })
        console.log(isSize)
        return isSize
      }
    },
    faceConfigClick(data) {
      this.form = data
      this.faceConfig = true
    },
    cancelFaceConfigClick() {
      this.faceConfig = false
    },
    submitFaceConfigClick() {
      crudDmUser.edit(this.form)
      this.imageUrl = ''
      this.$refs.table.clearSelection()
      this.faceConfig = false
      this.$message({
        message: '操作成功',
        type: 'success'
      })
    },
    // 详情
    openDetailsConfig(data) {
      this.form = data
      this.roomDeviceItem = data
      this.detailsConfig = true
      this.getDevices()
    },
    // 设备权限
    toggleSelection(rows) {
      console.log(rows)
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      var selectOne = this.crud.selectOne
      if (selectOne === false) { // 不限制选项
        this.multipleSelection = val
      }
      if (selectOne === true) {
        this.multipleSelection = val
        this.multipleSelection = val[0]
        if (val.length > 1) {
          this.$refs.multipleTable.clearSelection()
          this.$refs.multipleTable.toggleRowSelection(val.pop())
        }
      }
    },
    selected: function() {
      console.log(this.multipleSelection)
      // const code = this.multipleSelection.map(item => item.code)
      // const doorID = this.multipleSelection.map(item => item.doorID)
      const param = {
        // dmRoomDevices : this.multipleSelection.map(item => {
        roomDeviceId: this.multipleSelection,
        userId: this.roomDeviceItem.id
      }
      crudDmUser.addUserDevice(param).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch((res) => {
      })
      this.$refs.multipleTable.clearSelection()
      this.$refs.table.clearSelection()
      this.crud.doCloseDevice()
      this.devicePz = false
    },
    setCheckInfo() {
      var checkedDevices = this.$refs.multipleTable.selection
      var info = ''
      checkedDevices.forEach(row => {
        info += row.name + ','
      })
      this.checkInfo = info.substring(0, info.length - 1)
    }
  }
}
</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;
}

::v-deep .el-descriptions__table {
  font-size: 16px;
}

.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  ::v-deep .el-upload:hover {
    border-color: #409EFF;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

>>> .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: gray;
}

.shudao {
  border-right: 1px solid #000000;
  overflow: hidden;
}
</style>
