<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model.trim="query.blurry" clearable size="small" placeholder="输入设备名称/铭牌/维护人/联系方式/备注搜索" style="width: 450px;" class="filter-item" @keyup.enter.native="crud.toQuery"  />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model.trim="form.deviceName" style="width: 370px;"  />
          </el-form-item>
          <el-form-item label="设备图片">
            <uploadDialog :upload-params.sync="uploadParams" @callback="callbackFunc" />
          </el-form-item>
          <el-form-item label="设备铭牌" prop="nameplate">
            <el-input v-model.trim="form.nameplate" style="width: 370px;"  />
          </el-form-item>
          <el-form-item label="所属会议室" prop="room.roomId">
            <el-select
              v-model="form.room.roomId"
              style="width: 370px"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in rooms"
                :key="item.roomId"
                :label="item.roomName"
                :value="item.roomId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="登记时间" prop="registerDate">
            <el-date-picker v-model="form.registerDate" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="维护人" prop="maintainer">
            <el-input v-model.trim="form.maintainer" style="width: 370px;"  />
          </el-form-item>
          <el-form-item label="联系方式" prop="contacts">
            <el-input v-model.trim="form.contacts" style="width: 370px;"  />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model.trim="form.remark" :rows="3" type="textarea" style="width: 370px;"  />
          </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" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="deviceName" label="设备名称" />
        <!-- <el-table-column prop="imgPath" label="设备图片">
          <template slot-scope="{row}">
            <el-image
              :src="getDeviceImg(row)"
              :preview-src-list="[getDeviceImg(row)]"
              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="nameplate" label="设备铭牌" />
        <el-table-column prop="room.roomName" label="所属会议室" />
        <el-table-column prop="registerDate" label="登记时间" />
        <el-table-column prop="maintainer" label="维护人" />
        <el-table-column prop="contacts" label="联系方式" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column v-if="checkPer(['admin','dmDevice:edit','dmDevice:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDmDevice from '@/api/dm/meeting/dmDevice'
import { getAllRoom } from '@/api/dm/meeting/dmMeetingRoom'
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 { isvalidPhone } from '@/utils/validate'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import uploadDialog from '@/components/Upload/uploadImage'
// import { getFiles } from '@/api/tools/localStorage.js'
// import { mapGetters } from 'vuex'

const defaultForm = { deviceId: null, deviceName: null, imgPath: null, nameplate: null, room: { roomId: null }, registerDate: null, maintainer: null, contacts: null, remark: null, createBy: null, updateBy: null, createTime: null, updateTime: null, storageId: null }
// 自定义验证
const validPhone = (rule, value, callback) => {
  if (value && !isvalidPhone(value)) {
    callback(new Error('请输入正确的联系方式'))
  } else {
    callback()
  }
}

export default {
  name: 'DmDevice',
  components: { pagination, crudOperation, rrOperation, udOperation, uploadDialog },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '会议室设备', url: 'api/dmDevice', idField: 'deviceId', sort: 'deviceId,desc', crudMethod: { ...crudDmDevice }})
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'dmDevice:add'],
        edit: ['admin', 'dmDevice:edit'],
        del: ['admin', 'dmDevice:del']
      },
      rooms: [],
      uploadParams: {
        fileIds: [],
        fileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        limit: 1
      },
      rules: {
        deviceName: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        'room.roomId': [
          { required: true, message: '所属会议室不能为空', trigger: 'blur' }
        ],
        registerDate: [
          { required: true, message: '登记时间不能为空', trigger: 'blur' }
        ],
        maintainer: [
          { required: true, message: '维护人不能为空', trigger: 'blur' }
        ],
        contacts: [
          { required: false, trigger: 'blur', validator: validPhone }
        ]
      },
      queryTypeOptions: [
        { key: 'deviceName', display_name: '设备名称' },
        { key: 'nameplate', display_name: '设备铭牌' },
        { key: 'roomId', display_name: '所属会议室' },
        { key: 'maintainer', display_name: '维护人' },
        { key: 'contacts', display_name: '联系方式' },
        { key: 'remark', display_name: '备注' }
      ],
      fileList: [],
      imageUrl: ''
    }
  },
  /* computed: {
    ...mapGetters([
      'baseApi'
    ])
  }, */
  watch: {
    // 编辑框隐藏时,更新图片展示状态
    'crud.status.cu': {
      handler: function(val, oldVal) {
        // console.log('val ===> ',)
        if (val <= 0) {
          // console.log('清空图片')
          this.$set(this.uploadParams, 'fileList', [])
          this.$set(this.uploadParams, 'fileIds', [])
        } else if (val === 1) {
          this.$set(this.uploadParams, 'fileIds', this.form.storageId != null ? this.form.storageId.split(',') : [])
        }
      },
      immediate: true
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi'
    ])
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.findRoomList()
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      return true
    },
    findRoomList() {
      getAllRoom().then(res => {
        this.rooms = res.content
      })
    },
    callbackFunc(file_id, realName) {
      this.form.storageId = file_id
      this.form.imgPath = 'https://smartpark.caih.com/static/hyxtres/' + realName
    }
  }
}
</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;
  }
</style>
