<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" />
      <dmUserTemp :params.sync="params" @on-change="dmUserCallbackFunc" />
      <!--表单组件-->
      <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" class="dialog_height" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="名称" prop="roomName">
            <el-input v-model.trim="form.roomName" style="width: 370px;" />
          </el-form-item>

          <el-form-item label="所在楼层" prop="dmFloor.floorId">
            <el-select
              v-model="form.dmFloor.floorId"
              style="width: 370px"
              :filterable="true"
              placeholder="请选择"
            >
              <el-option
                v-for="item in floors"
                :key="item.floorId"
                :label="item.floorName"
                :value="item.floorId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="简介">
            <el-input v-model.trim="form.description" :rows="3" type="textarea" 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="capacity">
            <el-input v-model.trim="form.capacity" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="所在位置" prop="position">
            <el-input v-model.trim="form.position" style="width: 370px;" />
          </el-form-item>
          <el-form-item v-if="!isEdit" label="是否审批" prop="isApprove">
            <el-switch
              v-model="form.isApprove"
              active-color="#409EFF"
              inactive-color="#E8EAED"
              style="width: 440px;"
              @change="changeEnabled(form, form.isApprove)"
            />
          </el-form-item>

          <el-form-item v-show="form.isApprove && !isEdit" label="审批人" prop="approveUsers">
            <el-input v-model="form.approverId" style="display: none;" />
            <el-input v-model="form.approver" style="width: 370px;" @click.native="openDmList(form,'2')" />
          </el-form-item>

          <el-form-item label="维护人">
            <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="备注">
            <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-dialog title="会议室设备详情" :visible.sync="deviceTableVisible">
        <el-table v-loading="crud.loading" :data="deviceData">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="deviceId" label="设备id" />
          <el-table-column prop="deviceName" label="设备名称" />
          <el-table-column prop="nameplate" 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 prop="creatBy" label="创建者" />
          <el-table-column prop="updateBy" label="更新者" />
        </el-table>
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" highlight-current-row style="width: 100%;" :data="crud.data" size="small" @selection-change="crud.selectionChangeHandler" @row-click="handleCurrentChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="roomName" label="会议室名称" />
        <el-table-column prop="dmFloor.floorName" label="所在楼层" />
        <el-table-column prop="description" label="会议室简介" />
        <el-table-column prop="capacity" label="容纳人数" />
        <el-table-column prop="position" label="会议室所在位置" />
        <!-- <el-table-column prop="imgPath" label="会议室图片" /> -->
        <el-table-column prop="contacts" label="联系方式" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="maintainer" label="维护人" />
        <el-table-column prop="approver" label="审批人" />

        <el-table-column v-if="checkPer(['admin','dmMeetingRoom:edit','dmMeetingRoom: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 crudDmMeetingRoom from '@/api/dm/meeting/dmMeetingRoom'
import crudDmDevice from '@/api/dm/meeting/dmDevice'
import { getAllFloor } from '@/api/dm/floor/dmFloor'
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 dmUserTemp from '@/components/User/dmUserIndex'
import { isvalidPhone } from '@/utils/validate'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import uploadDialog from '@/components/Upload/uploadImage'

const defaultForm = { approverId: null, approver: null, roomId: null, roomName: null, dmFloor: { floorId: null }, description: null, imgPath: null, contacts: null, remark: null, roomStatus: null, reserveStatus: null, environmental: null, createBy: null, updateBy: null, createTime: null, updateTime: null, maintainer: null, isApprove: true, approveUsers: null, storageId: null, capacity: null, position: null }
let attendeeList = []
// 自定义验证
const validPhone = (rule, value, callback) => {
  if (value && !isvalidPhone(value)) {
    callback(new Error('请输入正确的联系方式'))
  } else {
    callback()
  }
}

export default {
  name: 'DmMeetingRoom',
  components: { pagination, crudOperation, rrOperation, udOperation, dmUserTemp, uploadDialog },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '会议室', url: 'api/dmMeetingRoom', idField: 'roomId', sort: 'roomId,desc', crudMethod: { ...crudDmMeetingRoom }})
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'dmMeetingRoom:add'],
        edit: ['admin', 'dmMeetingRoom:edit'],
        del: ['admin', 'dmMeetingRoom:del']
      },
      floors: [], // 楼层列表
      approverId: '',
      approver: '',
      approveUserVisible: true,
      isEdit: false,
      params: {
        deptId: null, // 是否要查指定部门的用户
        max: 100000, // 可以选择用户个数最大限制
        dmUserIsApprove: null// 是否要查有审批权限的用户
      },
      selectDmUserType: '2', // 选择的用户类型(0-参与人,1-权限用户,2-审批人)
      rules: {
        roomName: [
          { required: true, message: '会议室名称不能为空', trigger: 'blur' }
        ],
        'dmFloor.floorId': [
          { required: true, message: '所在楼层不能为空', trigger: 'blur' }
        ],
        contacts: [
          { required: false, trigger: 'blur', validator: validPhone }
        ]
      },
      queryTypeOptions: [
        { key: 'roomName', display_name: '会议室名称' },
        { key: 'floorId', display_name: '所在楼层' },
        { key: 'description', display_name: '会议室简介' },
        { key: 'contacts', display_name: '联系方式' },
        { key: 'remark', display_name: '备注' },
        { key: 'maintainer', display_name: '维护人' }
      ],
      deviceTableVisible: false,
      deviceData: [],
      fileList: [],
      imageUrl: '',
      uploadParams: {
        fileIds: [],
        fileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        limit: 1
      }
    }
  },
  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.findFloorList()

      console.log(form)
      console.log()
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterValidateCU](crud) {
      // crud.form.approverId = this.approverId
      // crud.form.approver = this.approver
      return true
    },
    // 添加前,清空选中数据
    [CRUD.HOOK.beforeToAdd]() {
      this.approverId = ''
      this.approver = ''
    },
    // 查询楼层信息
    findFloorList() {
      getAllFloor().then(res => {
        this.floors = res.content
      })
    },
    //    findUserList(){
    //      getUsers().then(res=>{
    //        this.namess=res.content
    //      })
    // },
    callbackFunc(file_id, realName) {
      this.form.storageId = file_id
      this.form.imgPath = 'https://smartpark.caih.com/static/hyxtres/' + realName
    },
    changeEnabled(form, isApprove) {
      this.form.isApprove = isApprove
    },
    openDmList(form, searchType) {
      this.params.max = 1
      this.params.dmUserIsApprove = true
      this.$set(this.params, 'attendeeSet', null)
      this.$set(this.params, 'searchType', searchType)
      this.crud.doOpenDmUser(form)
      console.log()
    },
    dmUserCallbackFunc(userList, rowid) {
      var userIds = ''
      var userNames = ''
      userList.forEach((item, i) => {
        userIds += userList[i]['id'] + ','
        userNames += userList[i]['nickName'] + ','
      })
      // 参与人选择回调
      if (this.selectDmUserType === '0') {
        console.info('参与人选择回调')
        this.userIds = userIds.substring(0, userIds.length - 1)
        this.userNames = userNames.substring(0, userNames.length - 1)
        attendeeList = userList
        console.log('attendeeList ==>> ' + attendeeList)
      }
      // 权限人员选择回调
      if (this.selectDmUserType === '1') {
        // console.info('权限人员选择回调')
        this.gcAssignUser = userIds.substring(0, userIds.length - 1)
        this.gcAssignUserName = userNames.substring(0, userNames.length - 1)
      }

      // 审批人员选择回调
      if (this.selectDmUserType === '2') {
        // console.info('审批人员选择回调')
        this.crud.form.approverId = userIds.substring(0, userIds.length - 1)
        this.crud.form.approver = userNames.substring(0, userNames.length - 1)
        // console.log(this.approverId)
      }
    },
    handleCurrentChange(val) {
      console.log('handleCurrentChange val', val)
      if (val) {
        console.log('1111111')
        this.deviceTableVisible = true
        crudDmDevice.getDeviceListByRoomId(val.roomId).then(res => {
          console.info('deviceData ==>> ' + JSON.stringify(res))
          this.deviceData = res.data
        })
      }
    }
  }
}
</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;
  }
  .dialog_height{
    height: 500px;
    overflow: auto;
  }
</style>
