<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; right:300px">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['shiftmgr:roster:add']"
        >导入
        </el-button>
      </div>

      <!-- 添加或修改排班计划管理对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="排班日期" prop="shiftDate">
            <el-date-picker clearable size="small" style="width: 200px"
                            v-model="form.shiftDate"
                            type="date"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择排班日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="白班" prop="dclass">
            <el-select v-model="form.dclass" clearable>
              <el-option value="10" label="A"/>
              <el-option value="12" label="B"/>
              <el-option value="14" label="C"/>
              <el-option value="16" label="D"/>
            </el-select>
          </el-form-item>
          <el-form-item label="夜班" prop="nclass">
            <el-select v-model="form.nclass" clearable>
              <el-option value="10" label="A"/>
              <el-option value="12" label="B"/>
              <el-option value="14" label="C"/>
              <el-option value="16" label="D"/>
            </el-select>
          </el-form-item>
          <el-form-item label="节假日" prop="vacation">
            <el-radio-group v-model="form.vacation">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="归属部门" prop="deptId">
            <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" 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 :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
            </div>
            <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
              <input name="type" :value="upload.type" hidden/>
            </form>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {addRoster, delRoster, exportRoster, getRoster, listRoster, updateRoster} from "@/api/shiftmgr/roster";
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} from '@/utils/event-utils'
import 'bootstrap/dist/css/bootstrap.css';
import {dateFormat} from '@/utils/date';

export default {
  name: "Roster",
  components: {Treeselect, FullCalendar},
  data() {
    return {
      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.handleAdd,
        eventClick: this.handleUpdate,
        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:
        */
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 排班计划管理表格数据
      rosterList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight: 300,
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        //下载模板请求地址
        downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
        type: 'shiftRoster',
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/shiftmgr/roster/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5000,
        shiftDate: null,
        dclass: null,
        nclass: null,
        week: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        vacation: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        shiftDate: [
          {required: true, message: "排班日期不能为空", trigger: "blur"}
        ],
        dclass: [
          {required: true, message: "白班不能为空", trigger: "blur"}
        ],
        nclass: [
          {required: true, message: "夜班不能为空", trigger: "blur"}
        ],
        vacation: [
          {required: true, message: "节假日不能为空", trigger: "blur"}
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  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();
        });
      }

      this.getList()
    });

  },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = document.body.clientHeight - 250
    })
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询排班计划管理列表 */
    getList() {
      this.loading = true;
      listRoster(this.queryParams).then(response => {
        this.rosterList = response.rows;
        let result = response.rows;
        if (result.length > 0) {
          this.calendarOptions.events = [];
          result.forEach(item => {
            let title = "";
            let color = "";
            let end = null;
            if (item.shiftDate != null) {
              end = new Date(item.shiftDate)
            }
            if (item.nclass != null) {
              title = "晚班：" + this.getClassName(item.nclass);
              color = "rgb(0,0,0,1)";
              this.calendarOptions.events.push({
                id: item.id,
                description: item.remarks,
                title: title,
                start: item.shiftDate,
                end: end,
                color: color,
                allDay: true
              })
            }
            if (item.dclass != null) {
              title = "早班：" + this.getClassName(item.dclass);
              color = "rgba(0, 140, 255, 1)";
              this.calendarOptions.events.push({
                id: item.id,
                description: item.remarks,
                title: title,
                start: item.shiftDate,
                end: end,
                color: color,
                allDay: true
              })
            }
          })
        } 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);
          }
        }
      }, error => {
        //this.$console.log(error);
      });
    },
    getClassName(val) {
      switch (val) {
        case '10':
          return 'A';
        case '12':
          return 'B';
        case '14':
          return 'C';
        case '16':
          return 'D';
      }
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shiftDate: null,
        dclass: null,
        nclass: null,
        week: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        vacation: 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(selectInfo) {
      console.log(selectInfo)
      this.reset();
      this.open = true;
      this.title = "添加排班计划管理";
      var currentTime = selectInfo.start;
      var targetOffset = 480; // 假设目标时区为中国标准时间（UTC+8），偏移量为-480分钟
      var targetTime = new Date(currentTime.getTime() + (targetOffset * 60 * 1000));
      var formattedTime = targetTime.toLocaleString(); // 使用默认的本地化格式

      console.log("目标时区时间：" + formattedTime);
      this.form.shiftDate = targetTime
    },
    /** 修改按钮操作 */
    handleUpdate(clickInfo) {
      console.log(clickInfo)
      this.reset();
      const id = clickInfo.event.id || this.ids
      getRoster(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) {
            updateRoster(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRoster(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 delRoster(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有排班计划管理数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportRoster(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.$refs['downloadFileForm'].submit()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</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>
