<template>
  <div class="app-container ">
    <div id="full-calendar" class="conference">
    <div class='conference-right'>
      <FullCalendar
        ref="fullCalendar"
        class='calendar-full'
        :options='calendarOptions'>
      </FullCalendar>
    </div>
    <div style="position: absolute; top:40px; left:200px">
      会议室：
            <el-select v-model="queryParams.roomId" placeholder="请选择会议室" style="width:300px; " size='small'@change="handleQuery" >
              <el-option
                v-for="dict in roomOptions"
                :key="dict.id"
                :label="dict.roomName"
                :value="dict.id"
              >
              </el-option>
            </el-select>
    </div>

    <div style="position: absolute; top:40px; right:300px">
      <el-button
        type="primary"
        size="mini"
        @click="goToList"
      >预约记录
      </el-button>
    </div>

    <!-- 添加或修改会议预约信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会议主题" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入会议主题" />
        </el-form-item>
        <el-form-item label="召集人" prop="convenerId">
          <el-input v-model="form.convenerId" placeholder="请输入召集人" />
        </el-form-item>

        <el-form-item label="会议室名称" prop="roomId">
          <el-select v-model="form.roomId">
            <el-option
              v-for="dict in roomOptions"
              :key="dict.id"
              :label="dict.roomName"
              :value="dict.id"
            ></el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="参会人" prop="participantsList">
          <el-input v-model="form.participantsList" placeholder="请输入参会人" />
        </el-form-item>
        <el-form-item label="会议开始时间" prop="beginDatetime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.beginDatetime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          align="right"
                          :picker-options="pickerOptions"
                          placeholder="选择会议开始时间">

          </el-date-picker>
        </el-form-item>
        <el-form-item label="会议结束时间" prop="endDatetime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.endDatetime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          align="right"
                          :picker-options="pickerOptions"
                          placeholder="选择会议结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" show-alpha></el-color-picker>
        </el-form-item>
        <el-form-item label="全天显示" prop="isAllday">
          <el-select v-model="form.isAllday" placeholder="请输入全天显示 ">
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="生成频率" prop="genFrequency">
          <el-select v-model="form.genFrequency" placeholder="请输入生成频率 ">
            <el-option label="只生成一次" value="1-N" />
            <el-option label="一天一次" value="1-D" />
            <el-option label="一周一次" value="1-W" />
            <el-option label="一月一次" value="1-M" />
          </el-select>
        </el-form-item>-->
<!--        <el-form-item label="生成月" prop="genMonth">
          <el-input v-model="form.genMonth" placeholder="请输入生成月" />
        </el-form-item>
        <el-form-item label="生成日" prop="genDay">
          <el-input v-model="form.genDay" placeholder="请输入生成日" />
        </el-form-item>
        <el-form-item label="生成日期" prop="genDate">
          <el-input v-model="form.genDate" placeholder="请输入生成日期" />
        </el-form-item>
        <el-form-item label="生成时间" prop="genDatetime">
          <el-input v-model="form.genDatetime" placeholder="请输入生成时间" />
        </el-form-item>-->
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listConfInfo,
  getConfInfo,
  delConfInfo,
  addConfInfo,
  updateConfInfo,
  exportConfInfo,
  importTemplate
} from "@/api/plant/confInfo";
import {treeselect} from "@/api/system/dept";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import momentPlugin from '@fullcalendar/moment'
import listPlugin from '@fullcalendar/list';
import bootstrapPlugin from '@fullcalendar/bootstrap';
import {INITIAL_EVENTS, createEventId} from '@/utils/event-utils'
import 'bootstrap/dist/css/bootstrap.css';
import {dateFormat} from '@/utils/date';
import {listConfRoom} from "@/api/plant/confRoom";

export default {
  name: "ConfInfo",
  components: {Treeselect, FullCalendar},
  data() {
    return {
      // 遮罩层
      loading: true,
      calendarOptions: {
        plugins: [
          //resourceTimeGridPlugin,
          bootstrapPlugin,
          listPlugin,
          momentPlugin,
          dayGridPlugin,
          timeGridPlugin,
          interactionPlugin // needed for dateClick
        ],
        //schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
        themeSystem: 'bootstrap',
        headerToolbar: {
          left: 'prev,next,today',
          center: 'title',
          right: 'listWeek,dayGridMonth,timeGridWeek,timeGridDay'
        },
        initialView: 'dayGridMonth',
        resources: [
          {id: 'a', title: 'Auditorium A'},
          {id: 'b', title: 'Auditorium B'},
          {id: 'c', title: 'Auditorium C'}
        ],
        initialEvents: INITIAL_EVENTS, // alternatively, use the `events` setting to fetch from a feed
        editable: true,
        dayMaxEvents: true,
        weekends: true,
        select: this.handleDateSelect,
        eventClick: this.handleEventClick,
        eventsSet: this.handleEvents,
        dateClick: this.handleDateClick,
        // dayCellDidMount: function(info) {
        //   //this.$console.log('info===',info);
        //   return 'test001'
        // },
        eventDidMount: function (info) {
          //$(info.el).tooltip({title: '11111'});
          //this.$console.log('info===',info);
          // var tooltip = new Tooltip(info.el, {
          //   title: info.event.extendedProps.description,
          //   placement: 'top',
          //   trigger: 'hover',
          //   container: 'body'
          // });
        },
        eventRender: function (event, element) {
          element.attr('title', event.tip);
        },
        height: '100%',
        events: [],
        week: 'narrow',
        buttonText: {
          next: '>',
          prev: '<',
          allday: '整天',
          today: '今天',
          month: '月',
          week: '周',
          day: '天',
          listWeek: '周列表'
        },
        // titleFormat: {
        //   month: 'long',
        //   year: 'numeric',
        //   day: 'numeric',
        //   weekday: 'long'
        // },

        // 整体控制月、周、天顶部的日期显示
        dayHeaderFormat: {
          weekday: 'short',
          // year: 'numeric',
          // month: 'numeric',
          // day: 'numeric',
          omitCommas: true
        },
        // 单独控制月、周、天顶部的日期显示
        views: {
          timeGridWeek: {
            dayHeaderFormat: {
              weekday: 'short',
              // year: 'numeric',
              month: 'numeric',
              day: 'numeric',
              omitCommas: true
            },
          },
        },
        selectMirror: 'true',
        slotMinTime: '06:00:00',
        slotMaxTime: '24:00:00',
        selectable: 'true',
        locale: 'zh-cn',
        slotEventOverlap: 'false',
        unselectAuto: 'false',
        selectOverlap: 'false',
        businessHours: [],
        firstDay: 1,
        allDaySlot: 'true',
        slotDuration: '00:30',
        slotLabelFormat: 'HH:mm',
        allDayContent: '全天',
        // 随时判断时间是否合法，通过返回true/false来判断是否能够选择
        selectAllow: info => {
          const currentDate = new Date()
          const start = info.start
          const end = info.end
          return (start <= end && start >= currentDate) || (dateFormat(start).substring(0, 10) === dateFormat(currentDate).substring(0, 10))
        },
        eventMouseEnter: this.eventMouseEnter,
        //eventDragStop: this.eventDragStop,
        // 拖拽结束后
        eventDrop: this.eventDragStop,
        // 调整大小
        eventResize: this.eventResize,

        dragOpacity: {
          agenda: .1, //对于agenda试图
          '': 1.0 //其他视图
        },

        //dayCellContent: ''
        /* you can update a remote database when these fire:
        eventAdd:
        eventChange:
        eventRemove:
        */
      },
      // 会议控制
      conferenceInfo: {
        defultConferenceRoomId: '',
        conferenceRoom: [],
        // 参会人options
        participantsOptions: [],
        // 召集人options
        convenerOptions: [],
        // 当前日期所在的时间段的开始时间和结束时间
        currentStartTime: '',
        currentEndTime: '',
        conferenceVisible: false,
        isAdd: false,
        isEdit: false,
        validFlag: false,
        conferenceList: [],
        loading: false,
        conferenceTypeOptions: [],
        isTencentMeeting: false,
        shareVisible: false,
        shareText: '',
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 会议预约信息表格数据
      confInfoList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      roomOptions: [],
      pickerOptions: {
        selectableRange: '00:00:00 - 23:59:59',
        disabledDate(time) {
          const date = new Date();
          let timeStr = dateFormat(time).substring(0, 10);
          let nowStr = dateFormat(date).substring(0, 10);
          return new Date(timeStr)  < new Date(nowStr);
        },
        shortcuts: [
          {
            text: '现在',
            onClick(picker) {
              const date = new Date();
              picker.$emit('pick', date);
            }
          },
          {
            text: '一小时后',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000);
              picker.$emit('pick', date);
            }
          },
          {
            text: '两小时后',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 7200 * 1000);
              picker.$emit('pick', date);
            }
          },
          {
            text: '三小时后',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 10800 * 1000);
              picker.$emit('pick', date);
            }
          }
        ]
      },
      clientHeight: 300,
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/plant/confInfo/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        roomId: null,
        subject: null,
        convenerId: null,
        convenerName: null,
        roomName: null,
        beginDatetime: null,
        endDatetime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roomId: [
          { required: true, message: "会议室不能为空", trigger: "blur" }
        ],
        subject: [
          { required: true, message: "会议主题不能为空", trigger: "blur" }
        ],
        beginDatetime: [
          { required: true, message: "会议开始时间不能为空", trigger: "blur" }
        ],
        endDatetime: [
          { required: true, message: "会议结束时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    // 在组件内部

    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = document.body.clientHeight - 250
    })
    listConfRoom({}).then(response => {
      this.roomOptions = response.rows;

    });
    this.getList();
    this.getTreeselect();
  },
  mounted() {
    let _self = this;
    this.$nextTick(() => {
      // 监听fullcalendar的事件
      let fullCalDom = document.querySelectorAll('.fc-header-toolbar .fc-toolbar-chunk .btn-group >button');
      for (let button of fullCalDom) {
        button.addEventListener('click', function () {
          _self.changeDurationTime();
        });
      }

      let calendarApi = this.$refs.fullCalendar.getApi()
      this.conferenceInfo.currentStartTime = dateFormat(new Date(calendarApi.view.currentStart));
      this.conferenceInfo.currentEndTime = dateFormat(new Date(calendarApi.view.currentEnd));

      this.getList()
    });

  },
  methods: {
    /** 查询会议预约信息列表 */
    getList() {
      this.loading = true;
      listConfInfo(this.queryParams).then(response => {
        this.confInfoList = response.rows;
        let result = response.rows;
        if(result.length > 0){
          this.calendarOptions.events = [];
          result.forEach(item => {
            let allDay = false;
            let end = item.endDatetime;
            if(item.isAllday === '0'){
              allDay = false;
            }else if(item.isAllday === '1'){
              allDay = true;
              if(item.endDatetime.substring(11, 19) !== '00:00:00'){
                end = new Date(new Date(item.endDatetime).getTime() + 1000 * 60 * 60 * 24);
              }
            }
            this.calendarOptions.events.push({
              id: item.id,
              description: item.remarks,
              title: item.subject + ' [' + item.roomName + ']',
              start: item.beginDatetime,
              end: end,
              color: item.color,
              allDay: allDay
            })
          });
        }
        else{
          this.calendarOptions.events = [];
          //改写No Event To Display;
          var ele =document.getElementsByClassName('fc-list-empty-cushion');
          console.log(ele)
          if(ele.length > 0){
            setTimeout(() => {
              ele[0].innerText = '没有更多数据！';
            }, 100);
          }
        }
        // 保存当前页面上的日程信息
        this.conferenceInfo.conferenceList = result;
        this.conferenceInfo.loading = false;
      }, error => {
        //this.$console.log(error);
        this.conferenceInfo.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roomId: null,
        subject: null,
        convenerId: null,
        convenerName: null,
        roomName: null,
        participantsList: null,
        beginDatetime: null,
        endDatetime: null,
        color: null,
        isAllday: null,
        genFrequency: null,
        genMonth: null,
        genDay: null,
        genDate: null,
        genDatetime: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会议预约信息";
    },
    /**
     * 打开新建时初始化日期
     */
    handleDateSelect(selectInfo) {
      console.log(selectInfo)
      this.reset();
      this.open = true;
      this.title = "添加会议预约信息";
      let startDate = selectInfo.start
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getConfInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会议预约信息";
      });
    },
    /**
     * 点击会议查询当前会议记录
     */
    handleEventClick(clickInfo) {
      this.reset();
      const id = clickInfo.event.id
      getConfInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会议预约信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConfInfo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfInfo(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delConfInfo(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    // 修改日程查询的开始和结束日期
    changeDurationTime() {
      //
      let calendarApi = this.$refs.fullCalendar.getApi()
      this.conferenceInfo.currentStartTime = dateFormat(new Date(calendarApi.view.activeStart));
      this.conferenceInfo.currentEndTime = dateFormat(new Date(calendarApi.view.activeEnd));
      console.log("=========changeDurationTime========")
      this.getConferenceList();
    },
    goToList() {
      this.$router.push("/plant/confInfoList");
    }
  }
};
</script>
<style lang='css' scoped>
.conference {
  display: flex;
  min-height: 100%;
  height: 800px;
  font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
  font-size: 14px;
  background-color: #fff;
}


  .conference .el-calendar__header {
    padding: 12px 10px;
  }

  .conference .el-calendar__header .el-calendar__button-group {
    width: 35%;
    text-align: right;
  }

  .conference .el-calendar__header .el-calendar__button-group .el-button-group > button:nth-of-type(1) {
    width: 20%;
    border: 0;
    padding: 5px 10px 5px 5px;
    font-size: 12px;
  }

  .conference .el-calendar__header .el-calendar__button-group .el-button-group > button:nth-of-type(2) {
    border: 0;
    padding: 5px 5px 5px 5px;
  }

  .conference .el-calendar__header .el-calendar__button-group .el-button-group > button:nth-of-type(3) {
    width: 20%;
    border: 0;
    padding: 5px 5px 5px 5px;
  }

  .is-selected {
    color: #1989FA;
  }

  .conference-right {
    flex-grow: 1;
    padding: 1em;
  }

  .fc { /* the calendar root */
    /* max-width: 1100px; */
    margin: 0 auto;
  }

  .conference-right .fc-header-toolbar .btn {
    line-height: 1 !important;
  }

  .is-selected {
    color: #1989FA;
  }

  .calendar-add-icon:hover {
    border: 1px solid #cccccc;
    border-radius: 3px;
    background-color: #f1f1f1;
  }

  .conference .el-input {
    border-bottom: 0 !important;
  }

  .conference .dialogFormItem {
    width: 450px;
  }

  .conference .dialogFormItem .half-input .el-input__inner {
    width: 320px;
  }

  .conference .mini-dialogFormItem .mini-input .el-input__inner {
    width: 120px;
  }

  .conference .full-dialogFormItem .full-input .el-input__inner {
    width: 780px;
  }

  .conference .full-dialogFormItem .full-input .el-textarea__inner {
    width: 780px;
  }

  .send-wechat-div {

  }

  .el-col-slotBtn {
    width: 25% !important;
  }

  .el-col-slotBtn .el-form-item__content {
    margin-left: 40px !important;
  }
.fc {
  width: 100%; /* 固定宽度 */
  height: 600px; /* 固定高度 */
}

.fc-toolbar .fc-center h2 {
  font-size: 20px; /* 根据需要调整字体大小 */
}
.fc-toolbar .fc-today-button,.fc-toolbar .fc-prev-button,.fc-toolbar .fc-next-button,
.fc-toolbar .fc-listWeek-button,
.fc-toolbar .fc-dayGridMonth-button,
.fc-toolbar .fc-timeGridWeek-button,
.fc-toolbar .fc-timeGridDay-button
{
  font-size: 14px !important; /* 设置按钮字体大小 */
  padding: 8px 12px !important; /* 设置按钮内边距 */
  height: 40px; /* 设置按钮高度 */
  line-height: 24px; /* 设置按钮行高，使文本居中 */
  border-radius: 3px;
}
.fc-view-container {
  overflow: hidden; /* 禁用溢出滚动 */
}
.fc-toolbar.btn-primary:not(:disabled):not(.disabled).active:focus{
  box-shadow: 0 0 0 0 !important;
}

</style>
