<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <el-input v-model.trim="query.blurry" clearable size="small" placeholder="输入会议议题/会议介绍/备注搜索" style="width: 450px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">会议类型</label>
        <el-select v-model="query.meetingMode" filterable placeholder="会议类型" clearable style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in dict.dm_meeting_mode"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">会议状态</label>
        <el-select v-model="query.meetingStatus" filterable placeholder="请选择">
          <el-option
            v-for="item in dict.dm_meeting_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <date-range-picker
          v-model="query.startDate"
          start-placeholder="会议开始时间区间"
          end-placeholder="会议开始时间区间"
          class="date-item"
        />
        <date-range-picker
          v-model="query.endDate"
          start-placeholder="会议结束时间区间"
          end-placeholder="会议结束时间区间"
          class="date-item"
        />
        <rrOperation :crud="crud" />
      </div>
      <el-dialog :visible.sync="infoVisible" title="会议详情" width="1000px">
        <el-form>
          <el-row>
            <el-col :span="12">
              <el-form-item label="会议议题:">
                {{ meeting.meetingName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会议室:">
                {{ meeting.roomName }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="会议介绍:">
                {{ meeting.meetingDescribe }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="会议类型:">
                {{ dict.label.dm_meeting_mode[meeting.meetingStatus] }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="meeting.meetingProp == '1'">
            <el-col :span="24">
              <el-form-item label="权限用户:">
                {{ meeting.gcUserNames }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="参与人:">
                {{ meeting.attendeeUserNames }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="使用设备:">
                {{ deviceNames }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始时间:">
                {{ meeting.startDate }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间:">
                {{ meeting.endDate }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:">
                {{ meeting.remark }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider style="margin: 10px 0px;">人工签到</el-divider>
          <el-row>
            <el-col :span="24" style="margin-top: 10px;">
              <el-table :data="signLogList">
                <el-table-column property="userName" label="参与人" />
                <el-table-column property="sex" label="性别" />
                <el-table-column property="phone" label="电话" />
                <el-table-column property="type" label="是否签到" />
                <el-table-column property="date" label="签到时间" />
                <el-table-column property="signType" label="签到方式" />
                <el-table-column v-if="true" label="操作">
                  <template slot-scope="scope">
                    <el-button v-if="scope.row.isSign == 0 && scope.row.meetingStatus == 1" plain size="mini" @click="signOn(scope.row)">签到</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row v-if="closeVisible">
            <el-col :span="24">
              <el-button @click="updateMeetingStatus(meeting.meetingId)">结束会议</el-button>
            </el-col>
          </el-row>

        </el-form>
      </el-dialog>

      <el-dialog :visible.sync="uploadFile" title="上传会议文件">
        <el-form ref="upload-form" :model="form" size="small" label-width="120px">
          <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>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="closeUploadDialog">取消</el-button>
          <el-button :loading="uploadLoading" type="primary" @click="submitUpload">确认</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 width="15" />
        <el-table-column prop="meetingName" label="会议议题" />
        <el-table-column prop="roomName" label="会议室" />
        <el-table-column prop="meetingDescribe" 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="initiatorName" label="发起人" />
        <el-table-column prop="startDate" label="开始时间" />
        <el-table-column prop="endDate" label="结束时间" />
        <el-table-column prop="remark" label="备注" />
        <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 label="操作" width="250px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.isCancel">已取消</div>
            <!--会议详情-->
            <!-- <el-button :loading="crud.status.cu === 2" plain size="mini" type="info" icon="el-icon-document" @click="crud.toEdit(scope.row)" /> -->
            <el-button v-if="scope.row.approveStatus == 1" plain size="mini" type="info" icon="el-icon-document" @click="infoPage(scope.row)" />
            <!--会议开始前,上传会议文件-->
            <el-button v-if="scope.row.approveStatus == 1" type="primary" plain size="mini" icon="el-icon-upload" @click="toUploadFiles(scope.row)" />
            <!--文件列表-->
            <el-button v-if="scope.row.approveStatus == 1" type="warning" plain size="mini" icon="el-icon-download" @click="toDownloadFiles(scope.row)" />
            <!--重新发起审批-->
            <el-button v-if="scope.row.approveStatus == 2" type="warning" plain size="mini" icon="el-icon-download" @click="approve(scope.row.meetingId)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <!--上传文件-->
      <uploadDialog :upload-params.sync="uploadParams" @callback="callbackFunc" />
      <!--文件列表-->
      <fileList :params.sync="fileParams" />
    </div>
  </div>
</template>

<script>
import crudDmMeeting from '@/api/dm/meeting/dmMeeting'
import { getToken } from '@/utils/auth'
import { getAllRoom } from '@/api/dm/meeting/dmMeetingRoom'
import { insert } from '@/api/dm/meeting/dmMeetingFile'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import uploadDialog from '@/components/Upload/uploadFile'
import fileList from './file/index-dialog'
// 查询发起人
import { getCurrUser } from '@/api/dm/user/dmUser'
import { del } from '@/api/tools/localStorage.js'
import { mapGetters } from 'vuex'

const defaultForm = { meetingId: null, meetingName: null, room: { roomId: null }, meetingProp: '0', meetingDescribe: null, meetingType: null, dept: { id: null }, initiatorUser: { id: null }, startDate: null, endDate: null, approveStatus: null, approveSuggest: null, actualCount: null, planCount: null, isDelay: null, remark: null, meetingStatus: null, createBy: null, updateBy: null, createTime: null, updateTime: null, users: [], isApprove: true, sendType: null, gcAssignUsers: null, approveUsers: null, devices: null, meetingMode: null }
export default {
  name: 'DmMeeting',
  components: { pagination, rrOperation, DateRangePicker, uploadDialog, fileList },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['dm_meeting_mode', 'dm_approve_status', 'dm_meeting_status', 'dm_meeting_prop', 'dm_send_type'],
  cruds() {
    return CRUD({ title: '会议', url: 'api/dmMeeting/myMeetingList', idField: 'meetingId', sort: 'meetingId,desc', crudMethod: { ...crudDmMeeting }})
  },
  data() {
    true
    console.log('rrrrr')

    return {
      permission: {
        add: ['admin', 'dmMeeting:add'],
        edit: ['admin', 'dmMeeting:edit'],
        del: ['admin', 'dmMeeting:del']
      },
      headers: { 'Authorization': getToken() },
      signLogList: [],
      rooms: [],
      deviceIds: '',
      deviceNames: '',
      infoVisible: false, // 详情页面显示状态
      closeVisible: false, // 详情页面的结束会议按钮显示状态
      meeting: {}, // 会议信息
      roomId: null,
      isReadOnly: true,
      isEdit: false,
      gcAssignUser: '',
      gcAssignUserName: '',
      gcAssignUserVisible: false,
      approveIds: '',
      approveNames: '',
      approveUserVisible: true,
      uploadMeetingId: '', // 当前进行上传的会议
      uploadMeetingFiles: '', // 上传的文件id,以逗号隔开
      uploadParams: {
        fileIds: [],
        fileList: [],
        disabled: false,
        limit: 1000,
        isMultiple: true,
        uploadDialogVisible: false,
        uploadDialogTitle: '',
        uploadLoading: false
      },
      fileParams: {
        visible: false,
        meetingId: '',
        fileType: ''
      },
      queryTypeOptions: [
        { key: 'blurry', display_name: '模糊查询' },
        { key: 'room.roomId', display_name: '会议室' },
        { key: 'meetingDescribe', display_name: '会议介绍' },
        { key: 'meetingType', display_name: '会议类型' },
        { key: 'dept.id', display_name: '参与部门' },
        { key: 'initiatorUser.id', display_name: '发起人' },
        { key: 'approveStatus', display_name: '审批状态' },
        { key: 'approveSuggest', display_name: '审批者意见' },
        { key: 'actualCount', display_name: '实际签到人数' },
        { key: 'planCount', display_name: '应到人数/计划人数' },
        { key: 'remark', display_name: '备注' },
        { key: 'meetingStatus', display_name: '会议状态(未开始/进行中/已结束)' }
      ],
      // console.log(sssss);
      currDmUser: {},
      fileList: [],
      uploadLoading: false,
      uploadFile: false
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi', // 图片上传
      'fileUploadApi' // 文件上传
    ])
  },
  watch: {
    'form.meetingProp': {
      handler: function(val, oldVal) {
        if (val === '1') {
          this.gcAssignUserVisible = true
        } else {
          this.gcAssignUserVisible = false
        }
      }
    },
    'form.room.roomId': {
      handler: function(val, oldVal) {
        this.deviceNames = ''
        this.deviceIds = ''
      }
    },
    'uploadParams.uploadDialogVisible': {
      handler: function(val, oldVal) {
        console.log('监听上传弹框显示状态 || val : ' + val)
        if (!val) {
          this.uploadParams.uploadDialogTitle = ''
          this.uploadMeetingId = ''
          this.uploadMeetingFiles = ''
        }
      }
    }
  },
  created() {
    getCurrUser().then(res => {
      console.log('当前账号关联用户信息 ==>> ' + JSON.stringify(res))
      this.currDmUser = !res ? null : res
    })
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.findRoomList()
      if (form.meetingId !== null) {
        this.isEdit = true
      } else {
        this.isEdit = false
      }

      console.log('ssss')
    },
    // 添加前,清空选中数据
    [CRUD.HOOK.beforeToAdd]() {
      this.isReadOnly = false
      this.gcAssignUser = ''
      this.gcAssignUserName = ''
      this.approveIds = ''
      this.approveNames = ''
      this.deviceIds = ''
      this.deviceNames = ''
    },
    // 初始化编辑时候设置用户信息
    [CRUD.HOOK.beforeToEdit](crud, form) {
      // 获取权限用户/使用设备/审批人数据
      this.getRelationInfo()
      this.isReadOnly = true
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      return false
    },
    findRoomList() {
      getAllRoom().then(res => {
        this.rooms = res.content
      })
    },
    getRelationInfo() {
      crudDmMeeting.getRelationInfo({ meetingId: this.form.meetingId }).then(res => {
        this.gcAssignUser = res.gcAssignUser
        this.gcAssignUserName = res.gcAssignUserName
        this.approveIds = res.approveIds
        this.approveNames = res.approveNames
        this.deviceIds = res.deviceIds
        this.deviceNames = res.deviceNames
      })
    },
    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()
        })
      })
    },
    changeEnabled(form, isApprove) {
      this.approveUserVisible = isApprove
    },
    // 详情页面展示
    infoPage(row) {
      this.meeting = row
      this.infoVisible = true
      this.closeVisible = row.meetingStatus === '1'
      crudDmMeeting.signList({ meetingId: row.meetingId }).then(res => {
        this.signLogList = res
      })
    },
    signOn(row) {
      crudDmMeeting.signOn({ userId: row.userId, meetingId: this.meeting.meetingId }).then(res => {
        this.infoPage(this.meeting)
      })
    },
    // 更新会议状态为结束
    updateMeetingStatus(meetingId) {
      crudDmMeeting.close({ meetingId: meetingId }).then(() => {
        this.crud.notify('操作成功', 'success')
        this.closeVisible = false
        this.crud.refresh()
      })
    },
    // 展示到上传页面
    toUploadFiles(row) {
      this.uploadMeetingId = row.meetingId
      this.uploadFile = true
      // this.uploadParams.uploadDialogTitle = '上传会议文件'
    },
    // 展示下载页面
    toDownloadFiles(row) {
      console.log('下载文件列表')
      this.$set(this.fileParams, 'visible', true)
      this.$set(this.fileParams, 'meetingId', row.meetingId)
      console.log(this.fileParams)
    },
    // 上传回调
    callbackFunc(file_id) {
      console.log('会议文件上传返回 || fileIds =>> ' + file_id + ' || meetingId ==>> ' + this.uploadMeetingId + ' || currDmUserId ==>> ' + this.currDmUser.id)
      this.uploadMeetingFiles = file_id
      var meetingFile = {
        meetingId: this.uploadMeetingId,
        uploadUser: this.currDmUser.id,
        fileIds: file_id.split(',')
      }
      console.log(meetingFile)
      insert(meetingFile).then(() => {
        this.crud.notify('上传成功', 'success')
        this.uploadParams.uploadDialogVisible = false
      })
    },
    beforeUpload(file) {
      console.log('开始上传')
      console.log(file)
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 1024
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 1GB!')
      }
      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)
      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)
    },
    handleRemoveFile(file) {
      console.log('删除文件')
      del([file.response.storageId]).then(res => {
        this.removeFileListObj(file)
        // this.$refs.fileUpload.handleRemove(file)
      })
    },
    closeUploadDialog() {
      this.fileList = []
      this.uploadFile = false
    },
    submitUpload() {
      console.log('提交上传文件')
      if (this.fileList === [] || this.fileList === null || this.fileList === undefined) {
        this.$notify({
          title: '请上传需要提交的会议文件',
          type: 'error',
          duration: 2500
        })
        return false
      }
      const fileIds = []
      for (const f of this.fileList) {
        const fileId = { storageId: f.response.storageId, fileUrl: f.response.url }
        fileIds.push(fileId)
      }
      const meetingFile = {
        meetingId: this.uploadMeetingId,
        uploadUser: this.currDmUser.id,
        fileIds: fileIds
      }
      console.log(meetingFile)
      insert(meetingFile).then(() => {
        this.crud.notify('上传成功', 'success')
        this.uploadParams.uploadDialogVisible = false
      })
      this.fileList = []
      this.uploadFile = false
    },
    approve(meetingId) {
      crudDmMeeting.approve(meetingId).then(res => {
        this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      })
    }
  }
}
</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;
  }
  #form-dialog .el-input, #form-dialog .el-select{
    width:170px;
  }
  #form-dialog .el-textarea{
    width:440px !important;
  }
</style>
<style scoped>

</style>
