<template>
    <basic-block title="日历">
        <!--
        <div class="tag-tip">
          <el-tag size="small" color="#f08f00">审核中</el-tag>
          <el-tag size="small" color="#6bb377">已审核</el-tag>
          <el-tag size="small" color="#999">已结算</el-tag>
        </div>
        -->
        <el-row type="flex" justify="space-between">
            <!--
            <el-col :span="4">
              <div class="room-content">
                <div class="room-title">会议室列表</div>
                <div class="room-list" :class="{'active-list': index === activeNum}"
                     v-for="(item, index) in meetingRoomList" :key="index" @click="chooseRoom(index)">
                  <span>{{ item.name }}</span>
                </div>
              </div>
            </el-col>
            -->
            <el-col :span="19">
                <div class="calendar-box">
                    <full-calendar
                        ref="fullCalendar"
                        style="height: 100%"
                        :options="calendarOptions"
                    >
                    </full-calendar>
                </div>
            </el-col>
        </el-row>
        <!--日程新增弹窗start-->
        <el-dialog
            title="会议新增"
            :visible.sync="dialogVisible"
            :before-close="close"
            :modal="false"
            width="45%">
            <el-form :model="form" :rules="rules" ref="form" label-width="120px" size="small" class="demo-ruleForm" :disabled="auth? false: 'disabled'">
                <el-form-item label="会议名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="参会角色" prop="roleName">
                    <el-select v-model="form.roleName" clearable filterable placeholder="参会角色">
                        <el-option
                            v-for="item in roleNameList"
                            :key="item.userId"
                            :label="item.name"
                            :value="item.userId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否是党会" prop="isParty">
                    <el-select v-model="form.isParty" clearable filterable placeholder="是否是党会">
                        <el-option
                            v-for="item in isParrty"
                            :key="item.is_party"
                            :label="item.name"
                            :value="item.is_party">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发起科室" prop="leaderName">
                    <el-input v-model="form.leaderName"></el-input>
                </el-form-item>
                <el-form-item label="会议开始时间" required>
                    <el-col :span="11">
                        <el-form-item prop="begindate" style="margin-bottom: 0">
                            <el-date-picker type="date"
                                            format="yyyy-MM-dd"
                                            value-format="yyyy-MM-dd"
                                            placeholder="选择日期"
                                            v-model="form.begindate"
                                            style="width: 100%;" >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col class="line" :span="2">-</el-col>
                    <el-col :span="11">
                        <el-form-item prop="startTime" style="margin-bottom: 0">
                            <el-time-select placeholder="选择时间"
                                            v-model="form.startTime"
                                            :picker-options="{
                                start: '00:00',
                                step: '00:30',
                                end: '23:30 ',
                              }"
                                            @change="onStartTime"
                                            style="width: 100%;">
                            </el-time-select>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="会议结束时间" required>
                    <el-col :span="11">
                        <el-form-item prop="enddate" style="margin-bottom: 0">
                            <el-date-picker type="date"
                                            format="yyyy-MM-dd"
                                            value-format="yyyy-MM-dd"
                                            placeholder="选择日期"
                                            v-model="form.enddate"
                                            style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col class="line" :span="2">-</el-col>
                    <el-col :span="11">
                        <el-form-item prop="endTime" style="margin-bottom: 0">
                            <el-time-select placeholder="选择时间"
                                            v-model="form.endTime"
                                            :picker-options="{
                                start: '00:00',
                                step: '00:30',
                                end: '23:30 ',
                                minTime: form.startTime
                              }"
                                            style="width: 100%;">
                            </el-time-select>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="会议备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="resetForm('form')">取消</el-button>
                    <el-button type="primary" @click="submitForm('form')">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!--日程新增弹窗end-->
    </basic-block>
</template>

<script>
    import _ from 'lodash' //导入loadsh插件
    // 引入日历组件
    import FullCalendar from "@fullcalendar/vue";
    import dayGridPlugin from "@fullcalendar/daygrid";
    import interactionPlugin from "@fullcalendar/interaction";
    // 引入js数据
    // import array from '@/utils/home'

    export default {
        name: 'Home',
        components: {
            FullCalendar, // make the <FullCalendar> tag available
        },
        data() {
            return {
                activeNum: 0,
                dialogVisible: false,
                // meetingRoomList: [],
                subList: [],
                array: [],
                auth: false,
                roleNameList: [
                    {
                        userId: 1,
                        name: '分管公司领导/部门负责人'
                    }, {
                        userId: 2,
                        name: '部门负责人'
                    }, {
                        userId: 3,
                        name: '部门分管线条领导/科室主任'
                    }
                ],
                isParrty: [
                    {
                        is_party: '1',
                        name: '是'
                    },
                    {
                        is_party: '0',
                        name: '否'
                    },

                ],
                form: {
                    title: '',
                    userId: '',
                    begindate: '',
                    startTime: '',
                    enddate: '',
                    endTime: '',
                    remark: '',
                    leaderName: '',
                    roleId: '',
                    roleColor: '',
                    id: '',
                    isParty: '否',
                    roleName: '分管公司领导/部门负责人'
                },
                rules: {
                    title: [{required: true, message: '请输入会议主题', trigger: 'blur'}],
                    userid:[{required: true, message: '请选择会议室使用人', trigger: 'change'}],
                    begindate:[{required: true, message: '请选择开始日期', trigger: 'change'}],
                    startTime:[{required: true, message: '请选择开始时间', trigger: 'change'}],
                    enddate:[{required: true, message: '请选择结束日期', trigger: 'change'}],
                    endTime:[{required: true, message: '请选择结束时间', trigger: 'change'}],
                    remark:[{required: true, message: '请填写会议备注', trigger: 'blur'}],
                    leaderName:[{required: true, message: '发起科室', trigger: 'blur'}],
                    isParty:[{required: true, message: '是否是党会', trigger: 'change'}],
                    roleName:[{required: true, message: '参会角色', trigger: 'change'}]
        },
            calendarOptions: {
                //   timeGridPlugin  可显示每日时间段
                height: 700,
                    plugins: [dayGridPlugin, interactionPlugin],
                    headerToolbar: {
                    left: "prev,next today",
                    center: "title",
                    right: "dayGridMonth,dayGridWeek,dayGrid",
                    // right: 'agendaWeek,dayGridWeek,dayGrid'
                },
                buttonText: {
                    // 设置按钮
                    today: "今天",
                        month: "月",
                        week: "周",
                        dayGrid: "天",
                },
                // allDaySlot: false,
                editable: false,
                    selectable: true,
                    navLinks: true,
                    // displayEventEnd: true,//所有视图显示结束时间
                    initialView: "dayGridMonth", // 设置默认显示月，可选周、日
                    dateClick: this.handleDateClick,
                    eventClick: this.handleEventClick,
                    eventsSet: this.handleEvents,
                    select: this.handleDateSelect,
                    // timezone
                    // 设置日程
                    events: [
                    // {
                    // 	id: 1,
                    // 	title: '09:30~11:30 小破孩',
                    // 	start: '2020-12-11',
                    // 	end: '2020-12-13',
                    // 	color: '#f08f00',
                    // },
                    // {
                    // 	id: 2,
                    // 	title: '9:30~14:30 项目会议',
                    // 	start: '2020-12-14',
                    // 	end: '2020-12-14',
                    // 	color: '#6bb377',
                    // },
                ],
                    eventColor: "", // 修改日程背景色
                    locale: "zh-cn", // 设置语言
                    weekNumberCalculation: "ISO", // 周数
                    customButtons: {
                    prev: { // this overrides the prev button
                        text: "PREV",
                            click: () => {
                            this.prev();
                        }
                    },
                    next: { // this overrides the next button
                        text: "PREV",
                            click: () => {
                            this.next();
                        }
                    },
                    today: {
                        text: "今天",
                            click: () => {
                            this.today();
                        }
                    }
                }
            },
        }
        },
        mounted() {
            // 获取用户信息
            this.calendarApi = this.$refs.fullCalendar.getApi();

            // this.meetingRoomList = this.array.meetingRoomList;
            // console.log('this.array', this.array)
            // this.getReservationList(this.array.scheduleList0);
            this.queryRole();
            this.getList();
        },
        methods: {
            // 获取会议信息
            getList() {
                this.$http({
                    url: "/market/calendar/queryList",
                    method: "post",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    data: {isFile: "0"},
                }).then((res) => {
                    console.log('res', res)
                    if (res.data && res.data.length > 0) {
                        this.array = res.data;
                        // this.getReservationList(this.array.scheduleList0);
                        this.getReservationList(this.array);
                    }
                });
            },
            // 获取会议信息
            queryRole() {
                this.$http({
                    url: "/market/calendar/queryRole",
                    method: "post",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    data: {isFile: "0"},
                }).then((res) => {
                    console.log('res====', typeof res.data)
                    console.log(res.data)
                    this.auth = res.data;
                    console.log("res.data",res.data)

                });
            },
            getReservationList(arrayData) {
                let newArr = [];
                this.subList = arrayData;
                arrayData.forEach((item) => {
                    console.log('item', item)
                    newArr.push({
                        start: this.dealWithTime(item.begindate),
                        end: this.addDate(this.dealWithTime(item.enddate), 1),
                        color: item.roleColor,
                        id: item.id,
                        title: `${this.getTitle(item.begindate, item.enddate)}   ${item.title}    ${item.leaderName}`,
                    })
                });
                this.calendarOptions.events = newArr;
                console.log(newArr)
            },
            // 切换教室
            chooseRoom(index) {
                this.activeNum = index;
                // 查询该会议室下面的会议事件
                if (index === 0) {
                    this.getReservationList(this.array.scheduleList0);
                } else if (index === 1) {
                    this.getReservationList(this.array.scheduleList1);
                }
            },
            // 日期加1天
            addDate(date, days) {
                var d = new Date(date);
                d.setDate(d.getDate() + days);
                var mon = (d.getMonth() + 1) < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1;
                let endD = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
                return `${d.getFullYear()}-${mon}-${endD}`;
            },
            // 获取会议事件title
            getTitle(date1, date2) {
                let start = date1.substring(11, 16);
                let end = date2.substring(11, 16);
                return `${start}~${end}`;
            },
            getShowTime(beginDate, endDate) {
                this.form.begindate = this.dealWithTime(beginDate);
                this.form.startTime = this.getHoursMin(beginDate);
                this.form.enddate = this.dealWithTime(endDate);
                this.form.endTime = this.getHoursMin(endDate);
                // this.$forceUpdate()
                this.form = {...this.form}
            },
            // 获取时分时间
            getHoursMin(value) {
                return value.substring(11, 16);
            },
            // 处理会议时间格式
            dealWithTime(date) {
                let newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date)[0];
                return newDate;
            },
            // 点击日历
            handleDateClick: function (arg) {
                if (!this.auth) {
                    return;
                }
                this.$forceUpdate();
                console.log(arg, '事件1')
                this.dialogVisible = true;
            },
            // 日历日程点击事件
            handleEventClick(calEvent) {
                console.log(calEvent, '事件2');
                this.dialogVisible = true;
                let id = calEvent.event.id;
                let info = this.subList.filter((item) => {
                    return item.id == id
                });
                this.$nextTick(() => {
                    this.form = _.cloneDeep(info[0]);
                    // 处理时间回显
                    this.getShowTime(this.form.begindate, this.form.enddate);
                    console.log(info[0], '数据')
                });
            },
            handleEvents(events) {
                console.log(events, '事件3');
            },
            handleDateSelect(selectInfo) {
                console.log(selectInfo, '限制');
            },
            // 切换上一个按钮
            prev() {
                this.calendarApi.prev();
            },
            // 切换下一个按钮事件
            next() {
                this.calendarApi.next();
            },
            // 点击今天按钮
            today() {
                this.calendarApi.today();
            },
            // 提交数据
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.form.begindate = `${this.form.begindate} ${this.form.startTime}`;
                        this.form.enddate = `${this.form.enddate} ${this.form.endTime}`;
                        console.log(this.form, '数据');
                        this.dialogVisible = false;
                        this.$http({
                            url: this.form.id === '' ? '/market/calendar/add' : '/market/calendar/update',
                            method: "post",
                            headers: {
                                "Content-Type": "application/json",
                            },
                            data: this.form,
                        }).then((res) => {
                            this.loadinged = false;
                            if (res.data.result === 1) {
                                this.$message({
                                    message: res.data.desc,
                                    type: "error",
                                });
                            } else {
                                this.$message({
                                    message: "成功",
                                    type: "success",
                                });
                                location.reload();
                            }
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.dialogVisible = false;
                this.$refs[formName].resetFields();
            },
            //关闭弹窗，重置表单
            close() {
                this.dialogVisible = false;
                this.$refs['form'].resetFields();
            },
            onStartTime(val) {
                console.log('val', val)
                this.form.startTime = val
            }
        }
    }
</script>
<style lang="scss" scoped>
    @import "src/assets/calendar";
</style>
