<template>
    <view>
        <nav-bar :navbarData="navbarData"></nav-bar>
        <view class="schedule" :style="'margin-top: ' + (height * 2 + 10) + 'rpx; height: calc(100vh - ' + (height * 2 + 10) + 'rpx)'">
            <view class="">选择需要设置的排班日期</view>

            <!-- 日历年月 -->
            <view class="defaultColor">
                <view class="calendar_title">
                    <view class="icon" @tap="lastMonth" :data-time="year + '/' + month + '/' + 1">
                        <view :class="nowYearMonth == '' + year + month ? 'lastMonthed' : 'lastMonth'">上个月</view>
                    </view>
                    <view class="yearMonth_title">{{ year }}年{{ month }}月</view>
                    <view class="icon" @tap="nextMonth">
                        <text class="nextMonth">下个月</text>
                    </view>
                </view>
            </view>
            <!-- 日历主体 -->
            <view class="calendar">
                <view class="header">
                    <view :class="index == todayIndex && isTodayWeek ? 'weekMark' : ''" v-for="(item, index) in date" :key="index">
                        <label :class="index == 0 || index == date.length - 1 ? 'changeColor' : ''">{{ item }}</label>
                    </view>
                </view>

                <view class="date-box">
                    <block v-for="(item, index) in dateArr" :key="index">
                        <view :class="m1.getClass(item.isToday, isToday, endDate)">
                            <!-- <view class='{{isToday == item.isToday ? "nowDay" : ""}}'> -->
                            <view
                                :class="(nowYearMonthDate <= item.nowYearMonthDate ? 'date-head' : 'date-headpast') + ' '"
                                @tap="lookHuoDong"
                                :data-year="year"
                                :data-month="month"
                                :data-datenum="item.dateNum"
                                :data-time="item.nowYearMonthDate"
                                :data-code="item.textCode"
                            >
                                <view :class="'head-number ' + (item.textCode == 'S' ? 'textU' : '')">
                                    {{ item.dateNum }}
                                    <text class="startTip">{{ item.isToday == isToday && endDate != '' ? '始' : '' }}</text>
                                    <text class="endTip">{{ item.isToday == endDate && endDate != '' ? '末' : '' }}</text>
                                </view>
                                <block v-if="item.textCode == 'U'">
                                    <view class="head-text textU">{{ item.dateSub }}</view>
                                </block>
                                <block v-else-if="item.textCode == 'N' || item.textCode == 'S'">
                                    <view class="head-text textN">{{ item.dateSub }}</view>
                                </block>
                                <block v-else>
                                    <view class="head-text textS">{{ item.dateSub }}</view>
                                </block>
                            </view>
                        </view>
                    </block>
                </view>
            </view>
            <view class="allChoose">
                <view class="chooseTip">
                    <view class="tipSqure canChoose"></view>
                    <text>可选</text>
                    <view class="tipSqure hasChoose"></view>
                    <text>已选</text>
                    <view class="tipSqure disableChoose"></view>
                    <text>不可选</text>
                </view>
                <view class="chooseAllTip">
                    <van-checkbox :value="checked" shape="square" color="#0079FE" @change="allChecked">全选（如需跨月批量设置，请依次切换至下个月）</van-checkbox>
                </view>
            </view>
            <view>
                <button class="handle-btn" :disabled="btnVisable" @tap="handleNext">下一步</button>
            </view>
        </view>
    </view>
</template>
<script module="m1" lang="wxs">
import Cache from '../../../../utils/cache';
var getClass = function(date, isToday, endDate) {
	if (date == isToday) {
		return "nowDay"
	}
	if (date == endDate) {
		return "nowDay"
	}
	if ((endDate != "") && (date > isToday) && (date < endDate)) {
		return "middleDay"
	}
	return ""
}
module.exports.getClass = getClass
</script>
<script module="m2" lang="wxs">
var getDate = function(str) {
	return str.substring(4, 6)+"/"+str.substring(6, 8);
}
module.exports.getDate = getDate
</script>
<script>
import navBar from '@/pages/components/navbar/index';
// pages/oneselfCenter/page/batchScheduling.js
import { $http } from '../../../../config/https.js';
const app = getApp();
import util from '../../../../utils/util.js';
export default {
    components: {
        navBar
    },
    data() {
        return {
            year: 0,
            month: 0,
            monthstr: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
            date: ['日', '一', '二', '三', '四', '五', '六'],
            dateArr: [],
            isToday: 0,
            isTodayWeek: false,
            todayIndex: 0,

            // 当前年月时间
            nowYearMonth: '',

            nowYearMonthDate: 0,
            nowYearAndMonth: 0,

            // 下拉选项
            accounts: [],

            accountIndex: 0,

            // 排班日历
            schedulings: [],

            // 排班情况列表
            schedulingsArr: [],

            // 初始状态
            isOnload: false,

            // 查看的日期 不使用isToday判断
            lookDate: '',

            endDate: '',

            //按照时间段排班
            // 时间段内的排班情况列表
            rangeSchedulingsArr: [],

            checked: false,

            //全选复选框
            activeNames: ['1'],

            navbarData: {
                background: '',
                title: '批量排班',
                //导航栏 中间的标题
                height: '100',
                bottom: true,
                isGoBack: true
            },

            height: app.globalData.height,
            backFlag: false,

            // 回退标志
            //选中日期段[已过滤非未排班日期]
            dataList: [],

            resourceTypeID: '',
            resourceTypeDesc: '',
            btnVisable: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log('options:', options);
        let { resourceTypeID, resourceTypeDesc } = options;
        this.initData(resourceTypeID, resourceTypeDesc, false);
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('this.data:', this);
        let { resourceTypeID, resourceTypeDesc, backFlag } = this;
        if (backFlag) {
            this.initData(resourceTypeID, resourceTypeDesc, backFlag);
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        /**
         * 修改
         */
        allChecked: function (event) {
            this.setData({
                checked: !this.checked
            });
        },

        onInitData: function () {
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1;
            let isToday = '' + year + month + now.getDate();
            if (month < 10) {
                isToday = '' + year + ('0' + month) + now.getDate();
            }
            if (now.getDate() < 10) {
                isToday = '' + year + month + '0' + now.getDate();
            }
            if (month < 10 && now.getDate() < 10) {
                isToday = '' + year + '0' + month + '0' + now.getDate();
            }
            this.setData({
                year: year,
                month: month,
                isToday: isToday,
                endDate: '',
                lookDate: year + '-' + month + '-' + now.getDate(),
                nowYearMonth: '' + year + month,
                nowYearAndMonth: new Date(year + '/' + month + '/' + 1).getTime(),
                nowYearMonthDate: new Date(year + '/' + month + '/' + now.getDate()).getTime()
            });
            this.getSchedulingType();
        },

        /**判断日期之间是否存在非未排班的情况 */
        judgeHasOther: function (dateSpace) {
            let flag = false;
            let { schedulings } = this;
            let dataList = [];
            dateSpace.map((item) => {
                let array = schedulings.filter((detail) => item === detail.date && detail['totalNum'] !== '');
                if (array.length === 1) {
                    flag = true;
                } else {
                    dataList.push(item);
                }
            });
            //同时重新设置开始日期
            this.setData({
                dataList,
                isToday: dataList.length > 0 ? `${dataList[0].split('-')[0]}${dataList[0].split('-')[1]}${dataList[0].split('-')[2]}` : this.isToday
            });
            return flag;
        },

        // 排班类型
        getSchedulingType: function () {
            let userData = Cache.get('userData');
            let { hospID } = userData;
            let data = {
                params: [
                    {
                        hospID: hospID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100079',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        if (res.result.length > 0) {
                            this.setData(
                                {
                                    accounts: res.result
                                },
                                () => {
                                    let tempIndex = '';
                                    res.result.forEach((item, index) => {
                                        if (item.defaultFlag) {
                                            if (item.defaultFlag == 'Y') {
                                                tempIndex = index;
                                            }
                                        }
                                    });
                                    this.changeCalendarAndDetail();
                                }
                            );
                        }
                    }
                }
            });
        },

        // 排班切换修改日历和排班情况
        changeCalendarAndDetail: function () {
            this.getSchedulingCalendar();
            // 默认选择排班
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1;
            let isToday = '' + year + month + now.getDate();
            if (month < 10) {
                isToday = '' + year + '0' + month + now.getDate();
            }
            if (now.getDate() < 10) {
                isToday = '' + year + month + '0' + now.getDate();
            }
            if (month < 10 && now.getDate() < 10) {
                isToday = '' + year + '0' + month + '0' + now.getDate();
            }
            this.setData({
                year: year,
                month: month,
                isToday: isToday
            });
            let lookDate = year + '-' + month + '-' + now.getDate();
            // this.getSchedulingInfo(lookDate);
        },

        // 排班日历
        getSchedulingCalendar: function (setYear, setMonth) {
            let userData = Cache.get('userData');
            let { hospID, userID, groupID, locID } = userData;
            let { resourceTypeID } = this;
            let obj = {
                params: [
                    {
                        userID: userID,
                        groupID: groupID,
                        locID: locID,
                        hospID: hospID,
                        resourceTypeID: resourceTypeID,
                        //出诊类型ID
                        year: setYear ? setYear : new Date().getFullYear(),
                        month: setMonth ? setMonth : new Date().getMonth() + 1
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100044',
                data: obj,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setData(
                            {
                                schedulings: res.result
                            },
                            () => {
                                this.dateInit(setYear, setMonth - 1);
                            }
                        );
                    }
                }
            });
        },

        dateInit: function (setYear, setMonth) {
            //全部时间的月份都是按0~11基准，显示月份才+1
            let dateArr = []; //需要遍历的日历数组数据
            let arrLen = 0; //dateArr的数组长度
            let now = setYear ? new Date(setYear, setMonth) : new Date();
            let year = setYear || now.getFullYear();
            let nextYear = 0;
            let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
            let nextMonth = month + 1 > 11 ? 1 : month + 1;
            let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay(); //目标月1号对应的星期
            let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
            let obj = {};
            let num = 0;
            if (month + 1 > 11) {
                nextYear = year + 1;
                dayNums = new Date(nextYear, nextMonth, 0).getDate();
            }
            arrLen = startWeek + dayNums;
            for (let i = 0; i < arrLen; i++) {
                if (i >= startWeek) {
                    num = i - startWeek + 1;
                    let isToday = '' + year + (month + 1) + num;
                    if (month + 1 < 10) {
                        isToday = '' + year + ('0' + (month + 1)) + num;
                    }
                    if (num < 10) {
                        isToday = '' + year + (month + 1) + ('0' + num);
                    }
                    if (num < 10 && month + 1 < 10) {
                        isToday = '' + year + ('0' + (month + 1)) + ('0' + num);
                    }
                    obj = {
                        isToday: isToday,
                        dateNum: num,
                        nowYearMonthDate: new Date(year + '/' + (month + 1) + '/' + num).getTime()
                    };
                    if (this.schedulings.length > 0) {
                        let sObj = this.schedulings[num - 1];
                        obj.dateSub = sObj.text;
                        //排过班日期置灰
                        obj.textCode = sObj.totalNum !== '' ? 'S' : sObj.textCode;
                    }
                } else {
                    obj = {};
                }
                dateArr[i] = obj;
            }
            this.setData({
                dateArr: dateArr
            });
        },

        /**
         * 上月切换
         */
        lastMonth: function (e) {
            //全部时间的月份都是按0~11基准，显示月份才+1
            let year = this.month - 2 < 0 ? this.year - 1 : this.year;
            let month = this.month - 2 < 0 ? 11 : this.month - 2;
            let now = new Date();
            let nowyear = now.getFullYear();
            let nowmonth = now.getMonth() + 1;
            if (nowyear + '-' + nowmonth == this.year + '-' + (this.month - 1)) {
                let lookDate = nowyear + '-' + nowmonth + '-' + now.getDate();
                let isToday = '' + nowyear + nowmonth + now.getDate();
                if (month < 10) {
                    isToday = '' + nowyear + ('0' + nowmonth) + now.getDate();
                }
                if (num < 10) {
                    isToday = '' + nowyear + nowmonth + ('0' + now.getDate());
                }
                if (num < 10 && month < 10) {
                    isToday = '' + nowyear + ('0' + nowmonth) + ('0' + now.getDate());
                }
                this.setData({
                    year: year,
                    month: month + 1,
                    isToday: isToday,
                    lookDate: lookDate
                });
                this.getSchedulingCalendar(year, month + 1);
                // this.getSchedulingInfo(lookDate);
            } else {
                let { time } = e.currentTarget.dataset;
                if (this.nowYearAndMonth < this.getSelectTime(time)) {
                    let isToday = '' + year + (month + 1) + 1;
                    if (month + 1 < 10) {
                        isToday = '' + year + ('0' + (month + 1)) + '01';
                    }
                    let lookDate = year + '-' + (month + 1) + '-' + '1';
                    this.setData({
                        year: year,
                        month: month + 1,
                        isToday: isToday,
                        //默认选中1号
                        lookDate: lookDate
                    });
                    // this.dateInit(year, month);
                    this.getSchedulingCalendar(year, month + 1);
                    // this.getSchedulingInfo(lookDate);
                } else {
                    uni.showToast({
                        title: '历史月份排班，不允许修改',
                        icon: 'none'
                    });
                }
            }
        },

        /**
         * 下月切换
         */
        nextMonth: function () {
            //全部时间的月份都是按0~11基准，显示月份才+1
            let year = this.month > 11 ? this.year + 1 : this.year;
            let month = this.month > 11 ? 0 : this.month;
            let lookDate = year + '-' + (month + 1) + '-' + '1';
            let isToday = '' + year + (month + 1) + '01'; //默认选中1号
            if (month + 1 < 10) {
                isToday = '' + year + ('0' + (month + 1)) + '01'; //默认选中1号
            }

            this.setData({
                year: year,
                month: month + 1,
                isToday: isToday,
                //默认选中1号
                lookDate: lookDate,
                endDate: ''
            });
            // this.dateInit(year, month);
            this.getSchedulingCalendar(year, month + 1);

            // this.getSchedulingInfo(lookDate);
        },

        getSelectTime: function (str) {
            let selectNumber = new Date(str).getTime();
            return selectNumber;
        },

        lookHuoDong: function (e) {
            let { year, month, datenum, time, code } = e.currentTarget.dataset;
            let lookDate = year + '-' + month + '-' + datenum;
            let { isToday, endDate, schedulings } = this;
            let currentDay = '' + year + month + datenum;
            if (month < 10) {
                currentDay = '' + year + ('0' + month) + datenum;
            }
            if (datenum < 10) {
                currentDay = '' + year + month + ('0' + datenum);
            }
            if (datenum < 10 && month < 10) {
                currentDay = '' + year + ('0' + month) + ('0' + datenum);
            }
            if (this.nowYearMonthDate <= time) {
                if (code === 'S') {
                    uni.showToast({
                        title: '已存在排班的日期，不允许批量排班',
                        icon: 'none'
                    });
                    return;
                }
                // this.getSchedulingInfo(lookDate);
                if (endDate == '') {
                    if (Number(isToday) < Number(currentDay)) {
                        //在开始日期之后设为截至日期
                        let dateList = [];
                        try {
                            dateList = util.getDateOfSpace(isToday, currentDay);
                        } catch (e) {
                            console.log('CatchClause', e);
                            console.log('CatchClause', e);
                            console.log('programErrorName:', e.name);
                            console.log('programError:', e.message);
                            return [];
                        }
                        if (dateList.length > 0 && this.judgeHasOther(dateList)) {
                            uni.showToast({
                                title: '所选择日期之前存在非未排班情况，已过滤非未排班日期！',
                                icon: 'none'
                            });
                        }
                        this.setData(
                            {
                                endDate: currentDay,
                                lookDate: lookDate
                            },
                            () => {
                                //this.getRangeSchedulingInfo();
                            }
                        );
                    } else {
                        //在第一个日期之前
                        this.setData({
                            isToday: currentDay,
                            lookDate: lookDate
                        });
                    }
                } else {
                    this.setData({
                        endDate: '',
                        lookDate: lookDate,
                        isToday: currentDay
                    });
                }
            } else {
                uni.showToast({
                    title: '历史日期排班，不允许修改',
                    icon: 'none'
                });
            }
        },

        handleNext: function () {
            let { dataList, isToday, endDate, resourceTypeID, resourceTypeDesc } = this;
            console.log('this.data:', this);
            if (isToday == '' || endDate == '') {
                uni.showToast({
                    title: '请选择开始截至日期',
                    icon: 'none'
                });
                return;
            }
            let url =
                '../batchSchedullingHandle/batchSchedullingHandle?resourceTypeID=' +
                resourceTypeID +
                '&resourceTypeDesc=' +
                resourceTypeDesc +
                '&dateList=' +
                JSON.stringify(dataList);
            uni.navigateTo({
                url: url
            });
        },

        /** */
        onShowCall: function (options) {
            let { resourceTypeID, resourceTypeDesc } = options;
            this.setData({
                resourceTypeID,
                resourceTypeDesc,
                backFlag: true
            });
        },

        /**设置页面初始化以及回退跳转数据 */
        initData: function (resourceTypeID, resourceTypeDesc, backFlag) {
            this.setData({
                resourceTypeID: resourceTypeID,
                resourceTypeDesc: resourceTypeDesc,
                backFlag: backFlag,
                navbarData: {
                    background: '',
                    title: resourceTypeDesc !== '' ? `批量排班(${resourceTypeDesc})` : '批量排班',
                    //导航栏 中间的标题
                    height: '100',
                    bottom: true,
                    isGoBack: true
                }
            });
            this.onInitData();
        }
    }
};
</script>
<style>
/* pages/oneselfCenter/page/batchScheduling.wxss */

page {
    height: 100%;
}
.schedule {
    width: 100%;
    overflow: auto;
    display: flex;
    flex-direction: column;
}
.picker-border {
    border-bottom: 1px solid var(--weui-FG-3);
}
.defaultColor {
    background-color: #ffffff;
}

.calendar_title {
    display: flex;
    justify-content: space-around;
    height: 100rpx;
    line-height: 100rpx;
    padding: 0px 10px;
}
.lastMonthed {
    color: #666666;
}

.nextMonth {
    color: #0079fe;
}
.yearMonth_title {
    color: #333333;
    /* flex: 1; */
}

.calendar {
    width: 100%;
    background: #fff;
    border-bottom-right-radius: 20rpx;
    border-bottom-left-radius: 20rpx;
    font-family: FZZhunYuan-M02S;
}

.header {
    font-size: 0;
    margin: 0 auto;
    border-top: 1px solid var(--weui-FG-3);
    border-bottom: 1px solid var(--weui-FG-3);
    padding: 0 20rpx;
}

.header > view {
    display: inline-block;
    width: 14.285%;
    color: #666;
    font-size: 30rpx;
    text-align: center;
    padding: 20rpx 0;
}

.weekMark {
    position: relative;
    margin: 0 auto;
}

.weekMark view {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    border-bottom: 2px solid #69f;
}

.date-box {
    font-size: 0;
    margin: 0 auto;
    padding: 0 20rpx;
}

.date-box > view {
    position: relative;
    display: inline-block;
    width: 14.285%;
    color: #666;
    text-align: center;
    vertical-align: middle;
}

.date-head {
    font-size: 10pt;
}

.date-head .head-number {
    color: #333333;
    font-size: 18px;
}

.date-head .head-text {
    font-size: 12px;
}

.date-head .textN {
    color: #1890ff;
}

.date-head .textU {
    color: #cccccc;
}

.date-head .textS {
    color: #ff0000;
}

.date-headpast {
    font-size: 10pt;
}

.date-headpast .head-number {
    color: #cccccc;
    font-size: 18px;
}

.date-headpast .head-text {
    color: #cccccc;
    font-size: 12px;
}

.nowDay .date-head {
    background-color: #1890ff;
    color: #fff;
    border-radius: 5px;
}

.nowDay .date-head .head-number {
    color: #fff;
    font-size: 18px;
}

.nowDay .date-head .head-text {
    color: #fff;
}

/* 排班 */
.picker-border {
    border-bottom: 1px solid var(--weui-FG-3);
}

.picker-border .weui-cell__bd {
    color: #666666;
}

.picker-border .weui-cell__ft {
    color: #666666;
}

.lastMonth {
    color: #0079fe;
    flex: 1;
}

.lastMonthed {
    color: #666666;
}

.nextMonth {
    color: #0079fe;
}

.changeColor {
    color: #ff7200;
}

.scheduling-bottom .weui-cells__title {
    color: #333333;
    font-weight: bold;
    height: 100rpx;
    background-color: #f5f4f4;
    line-height: 100rpx;
    margin: 0;
}

.scheduling-range .weui-cell_access .weui-cell__ft {
    color: #0079fe;
}

.startDate {
    background-color: #ff0000;
}

.endDate {
    background-color: #ff0000;
}

.startTip {
    font-size: 22rpx;
    float: right;
    padding-right: 5rpx;
}

.endTip {
    font-size: 22rpx;
    float: right;
    padding-right: 5rpx;
}

.middleDay .date-head {
    background-color: #e6f2ff;
    color: #0079fe;
}

.middleDay .date-head .head-number {
    color: #0079fe;
    font-size: 18px;
}

.middleDay .date-head .head-text {
    color: #0079fe;
}

.rangeTitle {
    color: #0079fe;
    font-weight: 600;
    font-size: 34rpx;
    height: 100rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #eee;
    border-top: 1px solid #eee;
}

.allChoose {
    flex: 1;
    background-color: #ffffff;
    padding-left: 40rpx;
    padding-top: 20rpx;
}
.chooseTip {
    display: flex;
    align-items: center;
}
.tipSqure {
    width: 30rpx;
    border: 2rpx;
    height: 16rpx;
    margin-right: 10rpx;
}
.canChoose {
    border: 2rpx solid #cccccc;
}
.disableChoose {
    background-color: #cccccc;
    margin-left: 40rpx;
}
.hasChoose {
    background-color: #0079fe;
    margin-left: 40rpx;
}
.handle-btn {
    background-color: #0079fe;
    color: #ffffff;
    border-radius: 30px;
    margin: 20px 10px;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
}
</style>
