<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <label class="el-form-item-label">会议议题</label>
      <el-input v-model="query.meetingName" clearable placeholder="会议议题" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <label class="el-form-item-label">会议室名称</label>
      <el-input v-model="query.roomName" clearable placeholder="会议室名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <label class="el-form-item-label">发起人名称</label>
      <el-input v-model="query.name" clearable placeholder="发起人名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <label class="el-form-item-label">会议开始时间</label>
      <DateRangePicker
        v-model="query.startDate"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        style="width: 300px;"
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
      />
      <label class="el-form-item-label">会议预约时间</label>
      <DateRangePicker
        v-model="query.createTime"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        style="width: 300px;"
        class="filter-item"
        @keyup.enter.native="crud.toQuery"
      />
      <rrOperation :crud="crud" />
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <dmUserTemp :params.sync="params" @on-change="dmUserCallbackFunc" />
      <dmRoomTemp :params.sync="params" @on-change="dmRoomCallbackFunc" />

      <!--弹出表单组件-->
      <el-dialog id="form-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="66px">
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker v-model="form.startDate" type="datetime" style="width: 170px;" :picker-options="pickerOptionsStart" />
          </el-form-item>
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker v-model="form.endDate" type="datetime" style="width: 170px;" :picker-options="pickerOptionsEnd" />
          </el-form-item>
          <el-form-item label="参与人" prop="usersList">
            <el-input v-model="userIds" style="display: none;" />
            <el-input v-model="userNames" :rows="3" type="textarea" style="width: 440px;" />
            <el-button type="primary" @click="openDmList(form,'0')">选择参与人</el-button>
          </el-form-item>
          <el-form-item label="会议议题" prop="meetingName">
            <el-input v-model.trim="form.meetingName" style="width: 170px;" />
          </el-form-item>
          <el-form-item label="会议介绍" prop="meetingDescribe">
            <el-input v-model.trim="form.meetingDescribe" :rows="3" type="textarea" style="width: 440px;" />
          </el-form-item>

          <el-form-item label="上传会议文件">
            <el-upload
              ref="fileUpload"
              :action="fileUploadApi +'?name='+ form.name"
              :limit="5"
              :auto-upload="true"
              :multiple="true"
              accept=".xlsx,.xls,.doc,.docx,.pdf,.dwg,.dxf,.dwt"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-preview="handleDownload"
              :on-remove="handleRemoveFile"
              :headers="headers"
              :file-list="fileList"
            >
              <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过100M</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="预约人" prop="initiatorUser.id">
            <el-input v-model="form.initiatorUser.id" style="display:none" />
            <el-input v-model="form. initiatorUser.name" readonly style="width: 170px;" />
          </el-form-item>
          <el-form-item label="会议模式" prop="meetingMode">
            <el-select v-model="form.meetingMode" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.dm_meeting_mode"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="sss" label="会议室" prop="room">
            <el-input :value="form.room.roomName" @click.native="openRoomList(form)" />
          </el-form-item>
          <el-form-item label="消息类型" prop="sendType">
            <el-select v-model="form.sendType" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.dm_send_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model.trim="form.remark" :rows="3" type="textarea" style="width: 440px;" />
          </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="meetingName" label="会议议题" />
        <el-table-column prop="room.roomName" label="会议室" />
        <el-table-column prop="meetingDescribe" label="会议介绍" />
        <el-table-column prop="initiatorUser.name" label="发起人" />
        <el-table-column prop="startDate" label="开始时间" />
        <el-table-column prop="endDate" label="结束时间" />
        <el-table-column prop="approveStatus" label="审批状态">
          <template slot-scope="scope">
            {{ dict.label.dm_approve_status[scope.row.approveStatus] }}
          </template>
        </el-table-column>
        <el-table-column prop="approveSuggest" label="审批者意见" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="meetingMode" label="会议模式">
          <template slot-scope="scope">
            {{ dict.label.dm_meeting_mode[scope.row.meetingMode] }}
          </template>
        </el-table-column>
        <el-table-column prop="meetingStatus" label="会议状态">
          <template slot-scope="scope">
            {{ dict.label.dm_meeting_status[scope.row.meetingStatus] }}
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','dmDevice:edit','dmMeeting:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.isCancel && scope.row.meetingStatus !== 2">已取消</div>
            <el-button v-if="!scope.row.isCancel && user.id === scope.row.initiatorUser.id" slot="reference" :disabled="disabledDle" type="danger" icon="el-icon-delete" size="mini" @click="toDelete(scope.row)" />
            <!--            <el-button v-if="!scope.row.isCancel" slot="reference" :disabled="disabledEdit" type="primary" icon="el-icon-edit" size="mini" @click="toEdit(scope.row)" />-->
            <el-button v-if="!scope.row.isCancel && scope.row.meetingStatus !== 2 && user.id === scope.row.initiatorUser.id" size="mini" @click="toCancel(scope.row.meetingId)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDmMeeting from '@/api/dm/meeting/dmMeeting'
// 查询所有房间
import { getAllRoom } from '@/api/dm/meeting/dmMeetingRoom'
// 查询发起人
import { getCurrUser } from '@/api/dm/user/dmUser'

import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'

import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
// 查询参与人弹出框
import dmUserTemp from '@/components/User/dmUserIndex'
// 弹出框会议室弹出框
import dmRoomTemp from '@/components/Room/dmMeetingRoom'
// 开始时间结束时间
import { parseTime } from '@/utils/index'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { del } from '@/api/tools/localStorage.js'

const defaultForm = { meetingName: null, room: {}, meetingDescribe: null, initiatorUser: { id: null }, startDate: null, endDate: null, remark: null, users: [], sendType: null, meetingMode: '1' }
let attendeeList = []
const validSelectUser = (rule, value, callback) => {
  if (attendeeList.length === 0) {
    callback(new Error('请选择参与用户'))
  } else {
    callback()
  }
}
const optShow = {
  add: true,
  edit: true,
  del: true,
  download: false,
  reset: false
}
export default {
  name: 'DmMeeting',
  components: { pagination, crudOperation, dmUserTemp, dmRoomTemp, rrOperation, DateRangePicker },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['dm_meeting_type', 'dm_approve_status', 'dm_meeting_prop', 'dm_send_type', 'dm_meeting_mode', 'dm_meeting_status'],
  cruds() {
    return CRUD({ title: '会议', url: 'api/dmMeeting', idField: 'meetingId', sort: 'meetingId,desc', crudMethod: { ...crudDmMeeting }, optShow: optShow })
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      fileList: [],
      permission: {
        add: [],
        edit: [],
        del: []
      },
      rooms: [],
      DUser: [],
      currDmUser: {},
      userIds: '',
      userNames: '',
      params: {
        max: 100000, // 可以选择用户个数最大限制
        dmUserIsApprove: null// 是否要查有审批权限的用户
      },
      dm_meeting_mode: [
        { value: '1', label: '' }
      ],
      deviceIds: '',
      deviceNames: '',
      roomId: null,
      roomName: '',
      isReadOnly: false,
      isEdit: false,
      disabledEdit: false,
      disabledDle: false,
      gcAssignUser: '',
      gcAssignUserName: '',
      sss: false,
      gcAssignUserVisible: false,
      approveIds: '',
      approveNames: '',
      approveUserVisible: true,
      selectDmUserType: '0', // 选择的用户类型(0-参与人,1-权限用户,2-审批人)
      del_mag: '确定删除本条数据吗？',
      rules: {
        meetingName: [
          { required: true, message: '会议议题不能为空', trigger: 'blur' }
        ],
        meetingDescribe: [
          { required: true, message: '会议介绍不能为空', trigger: 'blur' }
        ],
        'initiatorUser.name': [
          { required: true, message: '发起人不能为空', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '开始时间不能为空', trigger: 'blur' }
        ],
        endDate: [
          { required: true, message: '结束时间不能为空', trigger: 'blur' }
        ],
        meetingMode: [
          { required: true, message: '会议模式不能为空', trigger: 'blur' }
        ],
        room: [
          { required: true, message: '会议室不能为空', trigger: 'blur' }
        ],
        usersList: [
          { required: true, trigger: 'blur', validator: validSelectUser }
        ]
      },
      queryTypeOptions: [
        { key: 'blurry', display_name: '模糊查询' },
        { key: 'room.roomId', display_name: '会议室' },
        { key: 'meetingDescribe', display_name: '会议介绍' },
        { key: 'initiatorUser.id', display_name: '发起人' },
        { key: 'approveStatus', display_name: '审批状态' },
        { key: 'approveSuggest', display_name: '审批者意见' },
        { key: 'actualCount', display_name: '实际签到人数' },
        { key: 'remark', display_name: '备注' }
      ],
      startDateRange: null,
      endDateRange: null,
      // 时间限制，符合日期先后顺序的实际情况
      pickerOptionsStart: {
        disabledDate: time => {
          if (this.form.endDate) {
            return time.getTime() > this.form.endDate
          }
          return false
        },
        // selectableRange: this.startDateRange
        selectableRange: '00:00:00- 23:59:59'
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          if (this.form.startDate) {
            return time.getTime() + 24 * 60 * 60 * 999 < this.form.startDate
          }
          return false
        },
        selectableRange: this.endDateRange
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi', // 图片上传
      'fileUploadApi', // 文件上传
      'user'
    ])
  },
  watch: {
    'form.meetingMode': {
      handler: function(val, form) {
        if (val === '0' || val === '2') {
          this.sss = true
          // this.form.room.roomName=null;
        } else {
          this.sss = false
          // from.meetingMode=null
          // form.room.roomName=null
        }
      }
    },
    'form.room': {
      handler: function(val, oldVal) {
        this.deviceNames = ''
        this.deviceIds = ''
      }
    },
    'form.startDate': {
      handler: function(val, oldVal) {
        // console.log('开始时间', val)
        var endRange = '23:59:59'
        if (val) {
          var start_str1 = parseTime(val, '{y}-{m}-{d}')
          var start_str2 = parseTime(val, '{h}:{i}:{s}')
          if (this.form.endDate) {
            var end_str1 = parseTime(this.form.endDate, '{y}-{m}-{d}')
            var end_str2 = parseTime(this.form.endDate, '{h}:{i}:{s}')
            if (start_str1 === end_str1) {
              endRange = end_str2
            }
          }
          this.pickerOptionsStart.selectableRange = '00:00:00 - ' + endRange
          this.pickerOptionsEnd.selectableRange = start_str2 + '- 23:59:59'
        } else {
          this.pickerOptionsEnd.selectableRange = '00:00:00 - 23:59:59'
        }
      }
    },
    'form.endDate': {
      handler: function(val, oldVal) {
        // console.log('开始时间', val)
        var startRange = '00:00:00'
        if (val) {
          // console.log('有值')
          var end_str1 = parseTime(val, '{y}-{m}-{d}')
          var end_str2 = parseTime(val, '{h}:{i}:{s}')
          if (this.form.startDate) {
            var start_str1 = parseTime(this.form.startDate, '{y}-{m}-{d}')
            var start_str2 = parseTime(this.form.startDate, '{h}:{i}:{s}')
            // console.log(end_str1, start_str1)
            if (end_str1 === start_str1) {
              startRange = start_str2
            }
          }
          this.pickerOptionsStart.selectableRange = '00:00:00 - ' + end_str2
          this.pickerOptionsEnd.selectableRange = startRange + '- 23:59:59'
        } else {
          this.pickerOptionsStart.selectableRange = '00:00:00 - 23:59:59'
        }
      }
    }
  },
  created() {
    getCurrUser().then(res => {
      console.log('当前账号关联用户信息 ==>> ' + JSON.stringify(res))
      this.currDmUser = !res ? null : res
      defaultForm.initiatorUser = this.currDmUser != null ? this.currDmUser : { id: null }
    })
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.findRoomList()
      // this.findDeptList()
      this.findCurrDmUser()
      console.log('222222')
      console.log(form)
    },
    // 添加前,清空选中数据
    [CRUD.HOOK.beforeToAdd]() {
      this.userIds = ''
      this.userNames = ''
      this.room = ''
      this.roomId = ''
      this.roomName = ''
      this.isReadOnly = false
      this.gcAssignUser = ''
      this.gcAssignUserName = ''
      this.approveIds = ''
      this.approveNames = ''
      this.deviceIds = ''
      this.deviceNames = ''
    },
    // 初始化编辑时候设置用户信息
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.userIds = ''
      this.userNames = ''
      attendeeList = []
      const _this = this
      form.users.forEach(function(user, index) {
        _this.userIds += user.id + ','
        _this.userNames += user.name + ','
        const userInfo = { id: user.id }
        attendeeList.push(userInfo)
      })
      _this.userNames = _this.userNames.substring(0, _this.userNames.length - 1)
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      // console.info('提交 || crud.form ==>> ' + JSON.stringify(crud.form))
      if (!crud.form.initiatorUser.id) {
        this.$message({
          message: '发起人不能为空',
          type: 'warning'
        })
        return false
      } else if (this.userIds.length === 0) {
        this.$message({
          message: '参与人不能为空',
          type: 'warning'
        })
        return false
      }

      crud.form.users = attendeeList
      return true
    },
    // 查询所有房间
    findRoomList() {
      getAllRoom().then(res => {
        this.rooms = res.content
      })
      console.log('ccc')
      // console.log(this.rooms.roomName)
    },
    openRoomList(form) {
      this.params.max = 1
      // if()
      this.crud.doOpenDmRoom(form)
      // console.log( form)
    },

    findCurrDmUser() {
      getCurrUser().then(res => {
        this.currDmUser = res
      })
    },

    // 查询参与人
    openDmList(form, searchType) {
      this.selectDmUserType = searchType
      form.users = this.userIds
      this.params.max = 100000
      this.params.dmUserIsApprove = null
      this.$set(this.params, 'attendeeSet', null)
      this.$set(this.params, 'isEqualDept', null)
      this.$set(this.params, 'searchType', searchType)
      this.crud.doOpenDmUser(form)
      console.log('11111')
      console.log(form.users)
    },

    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)
      }
    },
    dmRoomCallbackFunc(roomList) {
      this.form.room = roomList
      // console.log(this.form.room)
    },
    // 会议室设备
    openDmDeviceList(form) {
      if (!form.room.roomId) {
        this.$message({
          message: '请选择会议室',
          type: 'warning'
        })
        return false
      }
      // form可以查找出来roomid 查不出房间名
      this.roomId = form.room.roomId
      this.crud.doOpenDmDevice(form)
    },
    toDelete(row) {
      this.$confirm(this.del_mag, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.doDelete(row)
      })
    },
    toEdit(row) {
      console.log('row.localStorages:', row.localStorages)
      this.fileList = row.localStorages || []
      this.crud.toEdit(row)
    },
    toCancel(meetingId) {
      this.$confirm('确认取消当前申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudDmMeeting.cancel({ meetingId: meetingId }).then(() => {
          this.crud.notify('取消成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.refresh()
        })
      })
    },
    toDelay(meetingId) {
      this.$confirm('确认对当前会议进行延期操作(后延30分钟,只可进行一次)?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudDmMeeting.delay({ meetingId: meetingId }).then(() => {
          this.crud.notify('延期成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.refresh()
        })
      })
    },
    beforeUpload(file) {
      console.log('开始上传')
      console.log(file)
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.name = file.name
      this.$set(this.form, 'name', file.name)
      console.log('fileName : ' + this.form.name)
      return isLt2M
      // return false
    },
    // 监听上传成功
    handleSuccess(response, file, fileList) {
      console.log('上传成功')
      console.log('response', response)
      console.log('file', file)
      console.log('fileList', fileList)
      file.id = response.id
      file.url = this.baseApi + '/file/' + response.type + '/' + response.realName
      if (this.form.localStorages) {
        this.form.localStorages.push(response)
      } else {
        this.form.localStorages = [response]
      }
      this.fileList = fileList
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    handleDownload(file) {
      console.log(file)
      this.download(file.url, file.name)
    },
    removeFileListObj(file) {
      console.log('移除文件')
      for (var i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].id === file.id) {
          this.fileList.splice(i, 1)
          break
        }
      }
      for (var item = 0; item < this.form.localStorages.length; item++) {
        if (this.form.localStorages[item].storageId === file.response.storageId) {
          this.form.localStorages.splice(item, 1)
          break
        }
      }
      console.log(this.fileList)
    },
    handleRemoveFile(file) {
      console.log('删除文件')
      del([file.response.storageId]).then(res => {
        this.removeFileListObj(file)
        // this.$refs.fileUpload.handleRemove(file)
      })
    }
  }
}
</script>
<style >
  #form-dialog .el-dialog {
    margin-top: 4vh !important;
    width:600px !important;
  }
  #form-dialog .el-form-item__label {
    width: 95px !important;
  }
  #form-dialog .el-form-item__content{
    margin-left: 96px !important;
  }
  #form-dialog .el-form-item{
    /* float:left; */
    display: inline-block;
  }
  #form-dialog .el-input, #form-dialog .el-select{
    width:170px;
  }
  #form-dialog .el-textarea{
    width:440px !important;
  }
</style>
<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-form {
    overflow: hidden;
  }
</style>
