<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.nickname"  size="small" placeholder="输入用户昵称" style="width: 180px;" class="filter-item" @keyup.enter.native="crud.toQuery"/>
        <el-input v-model="query.phone"  size="small" placeholder="输入手机号" style="width: 180px;" class="filter-item" @keyup.enter.native="crud.toQuery"/>
        <el-select v-model="query.status"  size="small" placeholder="选择状态" class="filter-item" style="width: 180px" @change="crud.toQuery">
          <el-option key="" label="全部" value=""/>
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <rrOperation />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
    </div>

    <el-row :gutter="15">
      <!--用户管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">用户列表</span>
          </div>
          <el-table ref="table" v-loading="crud.loading" highlight-current-row style="width: 100%;" :data="crud.data" @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="nickname" label="用户昵称" />
            <el-table-column prop="avatar" label="头像" >
              <template slot-scope="{row}">
                <el-image
                  :src=" baseApi + row.avatar"
                  :preview-src-list="[baseApi + row.avatar]"
                  fit="contain"
                  lazy
                  class="el-avatar"
                >
                  <div slot="error">
                    <i class="el-icon-document" />
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号码" />
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status==1" style="color: #13ce66">正常</span>
                <span v-else style="color: #ff6d6d">禁止</span>
              </template>
            </el-table-column>
            <el-table-column prop="sex" label="性别">
              <template slot-scope="scope">
                <span v-if="scope.row.sex==0">未知</span>
                <span v-else-if="scope.row.sex==1">男</span>
                <span v-else>女</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column v-if="checkPer(['admin','busUser:edit','busUser:del'])" label="操作" width="150px" align="center">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status==1" type="danger" size="mini" title="禁用" @click="setStatus(scope.row.id, 0)"><svg-icon icon-class="lock"/></el-button>
                <el-button v-else type="success" size="mini" title="启用" @click="setStatus(scope.row.id, 1)"><svg-icon icon-class="unlock"/></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </el-card>
      </el-col>

      <!-- 设备 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定用户分配指令" placement="top">
              <span class="role-span">设备分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton"
              :loading="deviceLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveUserDevice"
            >保存</el-button>
          </div>
          <el-tree
            ref="device"
            lazy
            :data="deviceData"
            :default-checked-keys="deviceCommandIds"
            :load="getDeviceDatas"
            :props="defaultProps"
            check-strictly
            accordion
            show-checkbox
            node-key="id"
            @check="deviceChange"
          >
          </el-tree>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudBusUser, { edit, updUserCommands } from '@/api/bus/busUser/busUser'
import { getDeviceTree, getChild } from '@/api/bus/busDevice/busDevice'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'
import { mapGetters } from 'vuex'

const defaultForm = { id: null, realName: null, nickname: null, avatar: null, phone: null, status: null, token: null, sex: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'BusUser',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: 'busUser', url: 'api/busUser', idField: 'id', sort: 'id,desc', crudMethod: { ...crudBusUser }})
  },
  data() {
    return {
      thisUserId: 0,
      defaultProps: { children: 'children', label: 'label', isLeaf: 'leaf' },
      showButton: false,
      deviceLoading: false,
      deviceData: [],
      deviceCommandIds: [],
      permission: {
        del: ['admin', 'busUser:del']
      },
      statusList: [
        { 'label': '正常', 'value': 1 },
        { 'label': '禁用', 'value': 0 }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created() {
    this.crud.optShow = { add: false, edit: false, del: true, download: false, reset: true }
  },
  methods: {
    getDeviceDatas(node, resolve) {
      setTimeout(() => {
        getDeviceTree(node.data.id ? node.data.id : 0).then(res => {
          resolve(res)
        })
      }, 100)
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中
        this.$refs.device.setCheckedKeys([])
        // 保存当前的角色id
        this.thisUserId = val.id
        // 初始化默认选中的key
        this.deviceCommandIds = []
        val.commands.forEach(function(data) {
          _this.deviceCommandIds.push(data.id)
        })
        this.showButton = true
      }
    },
    // 保存用户设备
    saveUserDevice() {
      this.deviceLoading = true
      const userCommand = { id: this.thisUserId, commands: [] }
      // 得到已选中的 key 值
      this.deviceCommandIds.forEach(function(id) {
        const command = { id: id }
        userCommand.commands.push(command)
      })
      updUserCommands(userCommand).then(() => {
        this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.deviceLoading = false
        this.refreshUser()
      }).catch(err => {
        this.deviceLoading = false
        console.log(err.response.data.message)
      })
    },
    // 改变数据
    refreshUser() {
      // 无刷新更新 表格数据
      crudBusUser.get(this.thisUserId).then(res => {
        for (let i = 0; i < this.crud.data.length; i++) {
          if (res.id === this.crud.data[i].id) {
            this.crud.data[i] = res
            break
          }
        }
      })
    },
    deviceChange(device) {
      // 获取该节点的所有子节点，id 包含自身
      getChild(device.id).then(childIds => {
        // 判断是否在 menuIds 中，如果存在则删除，否则添加
        if (this.deviceCommandIds.indexOf(device.id) !== -1) {
          for (let i = 0; i < childIds.length; i++) {
            const index = this.deviceCommandIds.indexOf(childIds[i])
            if (index !== -1) {
              this.deviceCommandIds.splice(index, 1)
            }
          }
        } else {
          for (let i = 0; i < childIds.length; i++) {
            const index = this.deviceCommandIds.indexOf(childIds[i])
            if (index === -1) {
              this.deviceCommandIds.push(childIds[i])
            }
          }
        }
        this.$refs.device.setCheckedKeys(this.deviceCommandIds)
      })
    },
    async setStatus(id, status) {
      const params = { id: id, status: status }
      await edit(params).then(res => {
        this.crud.notify('操作成功', 'success')
      })
      this.crud.toQuery()
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  }
}
</script>

<style scoped>

</style>
