// pages/meeting/subscribe/index.js
import {
    insertMeetingRecord,
    appointmentDateRecordList,
    checkTurnMeeting
} from '../../../utils/api/meeting'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        type: '',
        itemData: {},
        appointmentList: [],
        form: {
            meetingNum: 1,
            appointmentDate: null,
            aircondition: false,
            projection: false,
            meetingMonogramStatus: false
        },
        logoList: [{
                name: '需要',
                id: true
            },
            {
                name: '不需要',
                id: false
            },
        ],
        leftList: [],
        rightList: [],
        timePeriodList: [],
        subscribeYear: null,
        startDate: '',
        endDate: '',
        startTime: '',
        endTime: '',
        timeDisabled: false,
    },
    // 获取会议室布局
    getSeat() {
        let seatNum = this.data.itemData.seatNum
        let leftList = []
        let rightList = []
        for (let i = 0; i < seatNum; i++) {
            let data = {
                monogram: '',
                snack: false,
                teaWater: '',
            }
            if (i % 2 == 0) {
                leftList.push(data)
            } else {
                rightList.push(data)
            }
        }
        this.setData({
            leftList,
            rightList
        })
    },
    // 茶水
    getTeaWater(e) {
        let dataset = e.detail.currentTarget.dataset
        let name = "leftList[" + dataset.index + "].teaWater"
        let name1 = "rightList[" + dataset.index + "].teaWater"
        if (dataset.type === 'left') {
            this.setData({
                [name]: this.data.itemData.meetingBeforeTeaList[e.detail.detail.value]
            })
        }
        if (dataset.type === 'right') {
            this.setData({
                [name1]: this.data.itemData.meetingBeforeTeaList[e.detail.detail.value]
            })
        }
    },
    // 清除茶水
    getCleaeTea(e) {
        let dataset = e.detail.currentTarget.dataset
        let name = "leftList[" + dataset.index + "].teaWater"
        let name1 = "rightList[" + dataset.index + "].teaWater"
        if (dataset.type === 'left') {
            this.setData({
                [name]: ''
            })
        }
        if (dataset.type === 'right') {
            this.setData({
                [name1]: ''
            })
        }
    },
    // 点心
    getSnack(e) {
        let dataset = e.detail.currentTarget.dataset
        let name = "leftList[" + dataset.index + "].snack"
        let name1 = "rightList[" + dataset.index + "].snack"
        if (dataset.type === 'left') {
            this.setData({
                [name]: !this.data.leftList[dataset.index].snack
            })
        }
        if (dataset.type === 'right') {
            this.setData({
                [name1]: !this.data.rightList[dataset.index].snack
            })
        }
    },
    // 桌签
    getMonogram(e) {
        let dataset = e.detail
        let name = "leftList[" + dataset.index + "].monogram"
        let name1 = "rightList[" + dataset.index + "].monogram"
        if (dataset.type === 'left') {
            this.setData({
                [name]: dataset.val
            })
        }
        if (dataset.type === 'right') {
            this.setData({
                [name1]: dataset.val
            })
        }
    },
    getValue(e) {
        let type = e.currentTarget.dataset.type
        this.setData({
            [`form.${type}`]: e.detail
        });
        if (type == "appointmentDate") {
            this.appointmentDateRecordList(e.detail)
        }
    },
    getValue1(e) {
        this.setData({
            [`form.${e.detail}`]: !this.data.form[e.detail]
        })
    },
    // 会议时间赋值
    chooseTime(e) {
        let item = e.currentTarget.dataset.item
        if (item.type == 1) {
            this.setData({
                'form.appointmentStartTime': item.startTime,
                'form.appointmentEndTime': item.endTime,
                startTime: item.startTime,
                endTime: item.endTime,
            })
        }
    },
    // 提交
    submit() {
        let {
            form,
            itemData,
            leftList,
            rightList,
            type,
            timePeriodList
        } = this.data
        let that = this
        let isType=false
        timePeriodList.forEach(item=>{
            if(item.type==1){
                isType=true
            }
        })
        if(!itemData.meetingTurnRecordId &&!isType){
            wx.showToast({
                title: '当天会议室已经约满',
                icon: 'none'
            })
            return
        }
        if (!form.appointmentStartTime || !form.appointmentEndTime) {
            wx.showToast({
                title: '点击绿色时间段选择会议时间',
                icon: 'none'
            })
            return
        }
        if (!form.meetingMonogramStatus) {
            form.meetingMonogram = null
        }
        form.meetingRoomId = itemData.meetingRoomId
        form.meetingDeskVoList = leftList
        form.meetingDeskOtherSideVoList = rightList
        if (type == 'transfer-audit') {
            form.status = itemData.status
            form.refuseReason = itemData.refuseReason
            form.meetingTurnRecordId = itemData.meetingTurnRecordId
        }
        wx.requestSubscribeMessage({
            tmplIds: ['mJs6TXjIFuwgPu2JOEIpu3lO9ym9rnai-schUPuLuok'],
            success() {
                that.check()
            }
        })
    },
    async check() {
        let {
            form,
            type
        } = this.data
        let res
        if (type == 'transfer-audit') {
            res = await checkTurnMeeting(form)
        } else {
            res = await insertMeetingRecord(form)
        }
        if (res.code == 200) {
            wx.showToast({
                title: '提交成功',
                icon: 'none',
                duration: 800,
                mask: true,
                success: function () {
                    setTimeout(function () {
                        wx.switchTab({
                            url: '/pages/home/home',
                        })
                    }, 800)
                }
            })
        }
    },
    // 获取预约日期
    getStartDate() {
        let {
            subscribeYear,
            type
        } = this.data
        this.setData({
            startDate: subscribeYear,
            'form.appointmentDate': subscribeYear,
        })
        if (type != 'transfer-audit') {
            this.appointmentDateRecordList(this.data.form.appointmentDate)
        }
    },

    // 获取已预约时间段
    appointmentDateRecordList(year) {
        let data = {
            appointmentDate: year,
            meetingRoomId: this.data.itemData.meetingRoomId
        }
        appointmentDateRecordList(data).then(res => {
            this.setData({
                appointmentList: res.data
            })
            this.getTime()
        })
    },
    // 获取时间段
    getTime() {
        let {
            appointmentList,
            itemData,
            form
        } = this.data
        if (appointmentList.length == 0) {
            let timePeriodList = []
            timePeriodList.push({
                startTime: itemData.canAppointmentStartTime,
                endTime: itemData.canAppointmentEndTime,
                type: 1
            })
            this.setData({
                'form.appointmentStartTime': itemData.canAppointmentStartTime,
                'form.appointmentEndTime': itemData.canAppointmentEndTime,
                startTime: itemData.canAppointmentStartTime,
                endTime: itemData.canAppointmentEndTime,
                timePeriodList
            })
        } else {
            let timePeriodList = []
            let ttt = itemData.meetingInterval * 60 * 1000; //获取间隔时间（时间戳）
            // 会议总的预约时间（时间戳）
            let orderStartTime = Date.parse(form.appointmentDate + ' ' + itemData.canAppointmentStartTime + ':00')
            let orderEndTime = Date.parse(form.appointmentDate + ' ' + itemData.canAppointmentEndTime + ':00')
            appointmentList.forEach((item, index) => {
                let timeStart = Date.parse(form.appointmentDate + ' ' + item.appointmentStartTime + ':00')
                let timeEnd = Date.parse(form.appointmentDate + ' ' + appointmentList[(index == 0 ? index : index - 1)].appointmentEndTime + ':00')
                let timeEnd1 = Date.parse(form.appointmentDate + ' ' + appointmentList[(index == 0 ? index : index - 1)].appointmentEndTime + ':00')
                timePeriodList.push({
                    startTime: index==0 ? itemData.canAppointmentStartTime : this.convertTime(timeEnd + ttt),
                    endTime: this.convertTime(timeStart - ttt),
                    type: 1, //1：可点击；2：禁用
                    id: index + 'q'
                }, {
                    startTime: item.appointmentStartTime,
                    endTime: item.appointmentEndTime,
                    type: 2,
                    id: index + 'w'
                }, )
                // 如果已经预约开始时间-间隔时间<会议预约开始时间，去掉前面一项
                let index1 = timePeriodList.findIndex(item => {
                    return item.id == index + 'q'
                })
                if (index == 0) {
                    if (timeStart - ttt <= orderStartTime) {
                        timePeriodList.splice(index1, 1)
                    }
                } else {
                    if ((timeStart - ttt) <= timeEnd1) {
                        timePeriodList.splice(index1, 1)
                    } else if ((timeEnd + ttt) >= (timeStart - ttt)) {
                        // 如果开始时间>结束时间，去掉前面一项
                        timePeriodList.splice(index1, 1)
                    }
                }
            })

            // 获取最后可点击一项
            let cc = appointmentList[appointmentList.length - 1].appointmentEndTime
            let dd = Date.parse(form.appointmentDate + ' ' + cc + ':00')
            if (dd + ttt < orderEndTime) {
                timePeriodList.push({
                    startTime: this.convertTime(dd + ttt),
                    endTime: itemData.canAppointmentEndTime,
                    type: 1
                })
            }
            this.setData({
                timePeriodList
            })
        }
    },
    // 时间补零
    convertTime(timestamp) {
        let time = new Date(timestamp)
        let hours = time.getHours()
        let minute = time.getMinutes()
        if (hours < 10) {
            hours = '0' + hours
        }
        if (minute < 10) {
            minute = '0' + minute
        }
        return hours + ":" + minute
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.type) {
            this.setData({
                type: options.type,
                itemData: JSON.parse(options.itemData),
                appointmentList: options.appointmentList ? JSON.parse(options.appointmentList) : [],
                endDate: options.endDate,
                subscribeYear: options.subscribeYear
            })
        }
        // 转让，禁止修改日期时间
        if (this.data.type == 'transfer-audit') {
            let {
                itemData
            } = this.data
            this.setData({
                startTime: itemData.appointmentStartTime,
                endTime: itemData.appointmentEndTime,
                'form.appointmentStartTime': itemData.appointmentStartTime,
                'form.appointmentEndTime': itemData.appointmentEndTime,
                timeDisabled: true,
            })
        }
        this.getStartDate()
        this.getSeat()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})