/* eslint-disable no-undef */
import {
    courseInfo,
    courseNameList,
    courseAdd,
    courseDel,
} from "../../utils/api/course";
import { wxShowToast } from "../../utils/promisify";

const app = getApp();
let timer = null;
Page({
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        ImgUrl: app.globalData.ImgUrl,
        displayArea: app.globalData.displayArea,
        editIndex: null,
        nameAutoComplete: false,
        roomAutoComplete: null,
        courseNameList: null,
        autocompleList: [],
        ChooseWeek: 0,
        courseTime: [0, 0, 1],
        classTime: null,
        checkbox: [],
        multiArray: [],
        courseList: [],
    },
    /**
     * 后退一页
     */
    BackPage() {
        wx.navigateBack({
            delta: 1,
        });
    },
    /**
     * 高亮字符匹配
     * @param {*} str 匹配的字符串
     * @param {*} key 高亮的关键词
     * @return {*}
     */
    // highlightStr(str, key) {
    //     const regex = new RegExp(key, "g");
    //     return str.replace(
    //         regex,
    //         `<span style="color: #5E99FB;">${key}</span>`
    //     );
    // },
    /**
     * 生成模糊匹配的内容
     * @param {*}
     * @return {*}
     */
    // AutoComplete(data, key) {
    //     let autocompleList = data.map((item) => {
    //         return {
    //             content: item.content,
    //             key: key,
    //             nodeData: this.highlightStr(item.content, key),
    //         };
    //     });
    //     console.log(autocompleList);
    //     this.setData({
    //         autocompleList,
    //     });
    // },
    /**
     * 修改courseList数据
     * @param {*} type 需要修改的类型
     * @param {*} index 需要修改的数据下标
     * @param {*} params 修改的数据
     * @return {*} 新的courseList
     */
    modifyData(type, index, params) {
        let courseList = this.data.courseList;
        if (type === "nums") {
            courseList[index]["days"] = params[0] + 1;
            courseList[index]["nums"] = params[1] + 1;
            courseList[index]["enum"] = params[1] + params[2] + 1;
        } else {
            courseList[index][type] = params;
        }
        this.setData({
            courseList,
        });
        return courseList;
    },
    /**
     * 显示弹窗
     */
    showModal(e) {
        let { courseList, checkbox } = this.data;
        let { index, target } = e.currentTarget.dataset;
        let attend = courseList[index].attend.split(",");
        let _temp = null,
            val = null,
            _data = null;
        let { multiArray, classTime } = this.data;
        let quittingTime = [];
        // 关闭键盘
        wx.hideKeyboard({
            complete: (res) => {
                console.log("hideKeyboard res", res);
            },
        });
        // 不同内容的弹窗
        switch (target) {
        case "weeksModal":
            _temp = checkbox.map((v) => {
                if (attend.filter((e) => e == v.value)[0]) {
                    v.checked = true;
                } else {
                    v.checked = false;
                }
                return v;
            });
            this.setData({
                checkbox: _temp,
                ChooseWeek: null,
            });
            break;
        case "sectionModal":
            _data = courseList[index];
            val = [_data.days - 1, _data.nums - 1, _data.enum - _data.nums];
            // 下课时间
            for (let index = val[1]; index < classTime.length; index++) {
                quittingTime.push({
                    value: index + 1,
                    startTime: classTime[index].s_time,
                    endTime: classTime[index].e_time,
                });
            }
            multiArray = [multiArray[0], multiArray[1], quittingTime];
            this.setData({
                courseTime: val,
                multiArray,
            });
            break;
        default:
            break;
        }
        this.setData({
            modalName: target,
            editId: index,
        });
    },
    /**
     * 隐藏弹窗
     */
    hideModal() {
        this.setData({
            modalName: null,
            editId: null,
        });
    },
    /**
     * 多选框
     */
    ChooseCheckbox(e) {
        let items = this.data.checkbox;
        let values = e.currentTarget.dataset.value;
        for (let i = 0, lenI = items.length; i < lenI; ++i) {
            if (items[i].value == values) {
                items[i].checked = !items[i].checked;
                break;
            }
        }
        this.setData({
            checkbox: items,
        });
    },
    /**
     * 选择周数
     */
    ChooseWeeks(e) {
        let value = e.currentTarget.dataset.value;
        let checkbox = this.data.checkbox;
        console.log(value);
        const WeekFunc = (type) => {
            return checkbox.map((v) => {
                type == 0
                    ? (v.checked = true)
                    : type == 1
                        ? (v.checked = v.value % 2 != 0)
                        : (v.checked = v.value % 2 == 0);
                return v;
            });
        };
        let _temp = WeekFunc(value);
        console.log(_temp, "_temp");
        this.setData({
            ChooseWeek: value,
            checkbox: _temp,
        });
    },
    /**
     * 保存课程周数
     */
    saveWeek() {
        let { checkbox, editId } = this.data;
        let checkeds = checkbox.map((v) => {
            if (v.checked) {
                return v.value;
            }
        });
        checkeds = checkeds.filter((v) => v);
        console.log(checkeds);
        this.modifyData("attend", editId, checkeds.join(","));
        this.hideModal();
    },
    /**
     * 保存上课节数
     */
    saveCourseNum() {
        let { courseTime, editId } = this.data;
        console.log(courseTime, "courseTime");
        this.modifyData("nums", editId, courseTime);
        this.hideModal();
    },
    /**
     * 上课节数更改
     */
    sectionChange(e) {
        let { multiArray, classTime, courseTime } = this.data;
        let val = e.detail.value;
        // 下课时间
        let quittingTime = [];
        for (let index = val[1]; index < classTime.length; index++) {
            quittingTime.push({
                value: index + 1,
                startTime: classTime[index].s_time,
                endTime: classTime[index].e_time,
            });
        }
        multiArray = [multiArray[0], multiArray[1], quittingTime];
        if (val[1] !== courseTime[1]) {
            val[2] = 1;
        }
        this.setData({
            courseTime: val,
            multiArray,
        });
    },
    /**
     * 选择器内容创建
     */
    checkboxCreate() {
        let multiArray = [];
        let classTime = wx.getStorageSync("classTime");
        let checkbox = Array.from({ length: 20 }, (v, i) => {
            return {
                value: i + 1,
                checked: false,
            };
        });
        let courseNum = Array.from({ length: classTime.length }, (v, i) => {
            return {
                value: i + 1,
                startTime: classTime[i].s_time,
                endTime: classTime[i].e_time,
            };
        });
        multiArray[0] = [
            "周一",
            "周二",
            "周三",
            "周四",
            "周五",
            "周六",
            "周日",
        ];
        multiArray[1] = courseNum;
        multiArray[2] = courseNum;
        this.setData({
            checkbox,
            classTime,
            multiArray,
        });
    },
    /**
     * 加载开始
     */
    onLoad: function (query) {
        if (query.id) {
            courseInfo({
                subject_id: query.id,
            }).then((v) => {
                console.log(v, "courseInfo");
                let courseList = v.data;
                this.setData({
                    sname: v.data[0].sname,
                    courseList,
                });
            });
        } else {
            let addTime = query.addTime.split(",");
            addTime[0] !== "NaN"
                ? this.addCourseFunc(addTime)
                : this.addCourseFunc(null);
        }
        courseNameList().then((v) => {
            console.log(v, "courseNameList");
            this.setData({
                autocompleList: v.data,
            });
        });
        this.checkboxCreate();
    },
    /**
     * 聚焦课表名称,开始提示搜索
     */
    nameAutoComplete() {
        this.setData({
            nameAutoComplete: true,
        });
    },
    /**
     * 选择提示课程
     */
    compleChoose(e) {
        clearTimeout(timer);
        let sname = e.currentTarget.dataset.name;
        console.log(sname, "compleChoose");
        this.setData({
            sname,
            nameAutoComplete: false,
        });
    },
    /**
     * 删除课程(节)
     * @param {*}
     * @return {*}
     */
    delCourse(e) {
        let { id, index } = e.currentTarget.dataset;
        let { courseList } = this.data;
        console.log(e);
        wx.showModal({
            title: "课程删除",
            content: "删除后不可恢复,是否确认删除?",
            confirmText: "删除",
            confirmColor: "#e54d42",
            success: (res) => {
                if (res.confirm) {
                    console.log("用户点击确定");
                    if (id) {
                        courseDel({
                            usercourse_id: id,
                        }).then((v) => {
                            console.log(v);
                            v.code && wxShowToast(v.msg);
                            courseList.splice(index, 1);
                            app.getInfo();
                            this.setData({
                                courseList: [].concat(courseList),
                            });
                        });
                    } else {
                        console.log("noid");
                        courseList.splice(index, 1);
                        this.setData({
                            courseList: [].concat(courseList),
                        });
                    }
                } else if (res.cancel) {
                    console.log("用户点击取消");
                }
            },
        });
    },
    /**
     * 课表名称输入完成
     */
    courseNameConfirm(e) {
        timer = setTimeout(() => {
            let sname = e.detail.value;
            console.log(sname, "课表名称输入完成");
            this.setData({
                sname,
                nameAutoComplete: false,
            });
        }, 400);
    },
    courseNameChange(e) {
        let sname = e.detail.value;
        this.setData({
            sname,
        });
    },
    closeKeyboard() {
        this.setData({
            nameAutoComplete: false,
        });
    },
    /**
     * 教室名称输入完成
     */
    roomConfirm(e) {
        let index = e.currentTarget.dataset.index;
        let value = e.detail.value;
        this.modifyData("classroom", index, value);
        this.setData({
            roomAutoComplete: null,
            //   autocompleList: [],
        });
    },
    /**
     * 老师名字输入完成
     */
    tNameConfirm(e) {
        let index = e.currentTarget.dataset.index;
        let value = e.detail.value;
        this.modifyData("tname", index, value);
    },
    /**
     * 添加课程(节)
     */
    addCourse() {
        this.addCourseFunc(null);
    },
    addCourseFunc(addTime) {
        let { courseList, sname } = this.data;
        courseList.push({
            attend: courseList[0] ? courseList[0]["attend"] : "",
            classroom: courseList[0] ? courseList[0]["classroom"] : "",
            days: addTime ? parseInt(addTime[0]) + 1 : 1,
            enum: addTime ? parseInt(addTime[1]) + 2 : 2,
            nums: addTime ? parseInt(addTime[1]) + 1 : 1,
            tname: courseList[0] ? courseList[0]["tname"] : "",
            sname,
            usercourse_id: null,
        });
        this.setData({
            courseList,
        });
    },

    /**
     * 根据传入值判断课程冲突
     * @param {*}
     * @return {*}
     */
    courseConflict(v, o) {
        let n_attend = v.attend.split(",");
        let o_attend = o.attend.split(",");
        let intersection = n_attend.filter((v) => o_attend.includes(v));
        // 三元运算方法计算结构
        return intersection.length > 0
            ? v.days == o.days
                ? o.nums <= v.nums && v.nums <= o.enum
                    ? false
                    : o.enum >= v.enum && v.enum >= o.nums
                        ? false
                        : true
                : true
            : true;
        // if else运算方法计算结构
        // 判断是否有上课周重叠,如果有则进行继续判断
        //   if (intersection.length > 0) {
        //     // 判断是否有上课时间(日),如果有则进行继续判断
        //     if (v.days == o.days) {
        //       // 开始时间  大于开始时间小于结束时间
        //       if (o.nums <= v.nums && v.nums <= o.enum) {
        //         return false; //未通过
        //         // 结束时间  小于结束时间大于开始时间
        //       } else if (o.enum >= v.enum && v.enum >= o.nums) {
        //         return false; //未通过
        //       } else {
        //         return true;
        //       }
        //     } else {
        //       return true; //通过
        //     }
        //   } else {
        //     return true; //通过
        //   }
    },
    /**
     * 上课时间校验
     * @param {*}
     * @return {*} 数组格式 true为成功,表示没有冲突
     */
    classTimeCheck(oldData, newData) {
        let list = [];
        newData.map((v, idx) => {
            oldData.every((o) => {
                console.log(v, o, "classTimeCheck");
                if (v.ciid == o.ciid) {
                    return true;
                }
                return this.courseConflict(v, o);
            })
                ? null
                : list.push(idx + 1);
        });
        return list;
    },
    /**
     * 保存更改
     * @param {*}
     * @return {*}
     */
    saveButton() {
        let { sname, courseList } = this.data;
        // 课程名字
        if (!sname) {
            wxShowToast("请输入课程名字");
            return;
        }
        // 课程是否有
        if (courseList.length == 0) {
            wxShowToast("请添加课程");
            return;
        }
        // 课程信息完整度方法
        let checkData = (
            data,
            value = ["attend", "classroom", "days", "enum", "nums", "tname"]
        ) => {
            for (let index = 0; index < value.length; index++) {
                console.log(data[value[index]], "checkData");
                if (!data[value[index]]) {
                    return null;
                }
            }
        };
        // 判断是否课表内容填写完整
        let _check = courseList
            .map((v) => {
                return checkData(v);
            })
            .filter((v) => v === null);
        if (_check.length > 0) {
            wxShowToast("请填写完整课程信息");
            return;
        }

        let _courseCheck = []; // 冲突的数据index集合,如果为空则没有冲突
        // 判断新添加的课程是否有冲突
        for (let index = 0; index < courseList.length; index++) {
            const v = courseList[index];
            courseList.every((o, idx) => {
                if (index === idx) {
                    return true;
                }
                return this.courseConflict(v, o); //冲突判断 ,返回true为没有冲突,false为冲突
            })
                ? null
                : _courseCheck.push(index + 1);
        }
        console.log(_courseCheck, "_test");
        if (_courseCheck.length > 0) {
            wxShowToast(`第${_courseCheck.join("/")}课上课时间冲突`);
            return;
        }
        // 判断是否和已添加的课程冲突
        let my_course_info = app.globalData.userInfo.my_course_info;
        let _TimeCheck = this.classTimeCheck(
            my_course_info ? JSON.parse(my_course_info) : [],
            courseList
        );
        console.log(
            _TimeCheck,
            JSON.parse(app.globalData.userInfo.my_course_info),
            "params"
        );
        if (_TimeCheck.length > 0) {
            wxShowToast(
                `第${_TimeCheck.join("/")}课上课时间和已添加的课程冲突`
            );
            return;
        }
        let params = {
            sname,
            data: courseList,
        };
        courseAdd(params).then((v) => {
            console.log(v);
            wxShowToast(v.msg);
            if (v.code) {
                app.getInfo().then(() => {
                    this.BackPage();
                });
            }
        });
    },
});
