/* eslint-disable no-undef */
//index.js
import config from "../../config";
import { serializePathQuery } from "../../utils/api/http";
import {
    couplesMsgList,
    couplesInfoAdd,
    couplesInfoDel,
    couplesAdd,
} from "../../utils/api/user";
import { wxShowToast, wxShowMaskLoading } from "../../utils/promisify";
import dayjs from "../../utils/dayjs/dayjs.min";

//获取应用实例
const app = getApp();
Page({
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        displayArea: app.globalData.displayArea,
        ImgUrl: app.globalData.ImgUrl,
        colorList: config.colorList, // 色彩列表
        haveCouple: null, // 情侣ID,用于判断是否绑定情侣
        couplesInvite: false, // 显示情侣绑定弹窗
        userInfo: null, //用户数据
        newMessage: false, // 给情侣发消息
        messageValue: "", //消息输入框的值
        editMessage: false, // 编辑信息
        sendTime: "现在", // 信息发送时间
        classTime: null,
        showAllMsg: false, // 显示所有信息
        message: null, // 我收到的消息
        messageList: [], // 我要发送的消息列表
        editMessageId: null, // 正在编辑的信息的ID
        ScheduleId: 0, // 自己(0) & 情侣(1)课表切换
        courseInfo: null, //课表信息
        loverCourse: null, // 情侣课表信息
    },
    /**
     * 计算课程表是否符合当前周
     * @param {*} week 显示周
     * @param {*} userInfo 数据
     */
    weekCourseInfo(week, userInfo) {
        if (!userInfo) {
            return null;
        } else {
            let courseInfo = userInfo
                .map((v) => {
                    let attend = v.attend.split(",").filter((e) => e == week);
                    if (attend[0]) {
                        return v;
                    }
                })
                .filter((v) => v);
            return courseInfo.length > 0 ? courseInfo : [];
        }
    },
    /**
     * 处理当天课程信息
     */
    courseInfoSet(info, classTime = wx.getStorageSync("classTime")) {
        if (!(typeof info === "string" && info && classTime)) {
            return null;
        }
        let _info = JSON.parse(info);
        // 获取当前周
        let week = wx.getStorageSync("currentWeek");
        // 筛选当周
        _info = this.weekCourseInfo(week, _info);
        if (_info.length == 0) {
            // 如果本周没有课程就 return掉
            return null;
        }
        // 筛选当天
        let today = dayjs().day() ? dayjs().day() : 7;
        _info = _info.filter((v) => v.days == today);
        if (_info.length == 0) {
            // 如果今天没有课程就 return掉
            return null;
        }
        console.log(today, _info, classTime, "info");
        // 对比时间
        let checkdate = (t1, t2) => {
            let t11 = t1.split(":");
            let t21 = t2.split(":");
            let sj1 = parseInt(t11[0] * 12 + t11[1]);
            let sj2 = parseInt(t21[0] * 12 + t21[1]);
            return sj1 > sj2 ? false : true;
        };
        // 计算课程状态
        let Remind = (data) => {
            let now = dayjs().format("HH:mm");
            let tipEvent = dayjs().subtract(30, "minute").format("HH:mm");
            let stime = classTime[data.nums - 1].s_time;
            let etime = classTime[data.enum - 1].e_time;
            if (checkdate(etime, now)) {
                return 3; // 已结束
            } else if (checkdate(stime, now)) {
                return 2; // 进行中
            } else if (!checkdate(stime, tipEvent)) {
                return 1; // 即将开始
            } else {
                return 0; //不显示
            }
        };
        let courseTime = (data) => {
            let stime = classTime[data.nums - 1].s_time;
            let etime = classTime[data.enum - 1].e_time;
            return `${stime}-${etime}`;
        };
        let courseInfo = _info.map((v) => {
            return {
                courseTime: courseTime(v),
                courseRemind: Remind(v), // 0,1,2,3分别代表不显示,即将开始,进行中,已结束
                sname: v.sname,
                classroom: v.classroom,
            };
        });
        console.log(courseInfo);
        return courseInfo;
    },
    // 初始化用户信息
    initUserInfo(userInfo) {
        console.warn(userInfo, "getInfogetInfogetInfo");
        let courseInfo = this.courseInfoSet(
            userInfo.my_course_info,
            JSON.parse(userInfo.class_time)
        );
        let loverCourse = this.courseInfoSet(
            userInfo.lover_course_info,
            JSON.parse(userInfo.class_time)
        );
        let tid = userInfo.lovers_id; // 获取情侣id
        let message = null;
        let couplesBG = null;
        if (userInfo.loversinfo && userInfo.loversinfo.length > 0) {
            message = userInfo.loversinfo.filter((v) => v.love_sort == "0")[0];
            couplesBG = userInfo.loversinfo.filter(
                (v) => v.love_sort == "1"
            )[0];
        }
        userInfo.courseInfo = userInfo.my_course_info
            ? JSON.parse(userInfo.my_course_info)
            : null;
        userInfo.loverCourseInfo = userInfo.lover_course_info
            ? JSON.parse(userInfo.lover_course_info)
            : null;
        if (message) {
            message.time = dayjs
                .unix(message.starttime)
                .format("MM月DD日 HH:mm");
        }
        this.setData({
            userInfo: userInfo,
            haveCouple: tid,
            courseInfo,
            loverCourse,
            message: message ? message : null,
            couplesBG: couplesBG ? couplesBG : null,
        });
        if (tid) {
            this.getMessage(tid);
        }
    },
    /**
     * 显示所有信息
     */
    showAllMsg() {
        let { showAllMsg } = this.data;
        showAllMsg = !showAllMsg;
        this.setData({
            showAllMsg,
        });
    },
    /**
     * 获取情侣留言
     */
    getMessage(tid) {
        couplesMsgList({
            is_show: 0, // 显示所有未发送消息
            tid,
        }).then((e) => {
            let messageList = e.data.data ? e.data.data : [];
            messageList = messageList.map((v) => {
                v.state = dayjs(dayjs.unix(v.starttime)).isBefore(dayjs())
                    ? 1
                    : 0; //
                v.time = dayjs.unix(v.starttime).format("MM月DD日 HH:mm");
                return v;
            });
            console.log(messageList, "couplesMsgList");
            this.setData({
                messageList: messageList,
            });
        });
    },
    /**
     * 检查情侣绑定信息
     */
    checkCoupleBind(userInfo) {
        let { loverInfo } = this.data;
        // 判断是否弹窗绑定情侣 ( 有传入情侣id,不是自己打开自己的链接,并且没有绑定过情侣)
        if (
            loverInfo.couplesAdd &&
            loverInfo.couplesAdd != userInfo.user_id &&
            !userInfo.lovers_id
        ) {
            this.setData({
                couplesInvite: true,
                loverInfo,
            });
        }
    },
    onShow: function () {
        if (app.globalData.userInfo) {
            this.initUserInfo(app.globalData.userInfo);
            this.checkCoupleBind(app.globalData.userInfo);
        } else {
            app.userInfoReadyCallback = (v) => {
                this.checkCoupleBind(v);
                this.initUserInfo(v);
            };
        }
        if (!this.data.classTime) {
            let classTime = wx.getStorageSync("classTime");
            this.setData({
                classTime,
            });
        }
    },
    onLoad: function (query) {
        console.log(query, "query");
        let couplesAdd =
            query.couplesAdd && query.couplesAdd !== "null"
                ? query.couplesAdd
                : null;
        let nickname =
            query.nickname && query.nickname !== "null" ? query.nickname : null;
        let avatar =
            query.avatar && query.avatar !== "null" ? query.avatar : null;
        this.setData({
            loverInfo: {
                couplesAdd,
                nickname,
                avatar,
            },
        });
    },
    /**
     * 给ta留言
     */
    newMessage() {
        console.log("newMessage");
        this.setData({
            newMessage: true,
        });
    },
    /**
     * 消息内容更改
     */
    messageChange(e) {
        console.log(e.detail.value, "messageChange");
        this.setData({
            messageValue: e.detail.value,
        });
    },
    /**
     * 消息发送时间格式化
     */
    TimePicker(e) {
        let day = dayjs(e.detail).format("MM月DD日");
        let am = dayjs(e.detail).format("A") == "PM" ? "下午" : "上午"; // 格式化上下午
        let time = dayjs(e.detail).format("HH:mm");
        let sendTime = `${day} ${am} ${time}`;
        console.log(sendTime, "TimePicker");
        this.setData({
            sendTime: sendTime,
            startTime: dayjs(e.detail),
        });
    },
    /**
     * 取消保存消息
     */
    cancelMessage() {
        this.setData({
            newMessage: false,
            editMessage: false,
            messageValue: "",
            sendTime: "现在",
            startTime: null,
        });
    },
    /**
     * 保存消息
     */
    saveMessage() {
        let { messageValue, startTime, editMessageId, haveCouple } = this.data;
        let lid = editMessageId;
        let tid = haveCouple;
        let _startTime = startTime ? dayjs(startTime) : dayjs();
        let params = {
            tid, // 情侣的id
            starttime: _startTime.unix(), // 开始时间
            endtime: 1, // 代表留言只持续1天
            love_sort: 0, // 代表类型为留言
            contents: messageValue, //信息内容
        };
        if (lid) {
            params["lid"] = lid;
        }
        couplesInfoAdd(params).then((v) => {
            console.log(v, "couplesInfoAdd");
            wxShowToast(v.msg);
            this.getMessage(haveCouple);
        });
        this.cancelMessage();
    },
    /**
     * 编辑/新建消息
     */
    editMessage(e) {
        let { type, index, lid } = e.currentTarget.dataset;
        let { messageList } = this.data;
        console.log(type, index, lid);
        if (type) {
            this.setData({
                messageValue: messageList[index].contents,
                sendTime: messageList[index].time,
                editMessageId: lid,
            });
        }
        this.setData({
            editMessage: true,
        });
    },
    /**
     * 删除留言信息
     */
    delMessage(e) {
        let { haveCouple } = this.data;
        let { lid } = e.currentTarget.dataset;
        couplesInfoDel({ lid }).then((v) => {
            console.log(v);
            this.getMessage(haveCouple);
            if (v.code == 0) {
                wx.showToast({
                    title: v.msg,
                    icon: "none",
                    image: "",
                    duration: 2000,
                });
            }
        });
    },
    /**
     * 登陆
     */
    bindGetUserInfo(e) {
        if (e.detail.userInfo) {
            wxShowMaskLoading("登陆中");
            app.getInfo().then((v) => {
                this.initUserInfo(v);
                console.log(v, "getInfo");
                wx.hideLoading();
            });
        }
    },
    /**
     * 给ta设置背景
     */
    couplesBG() {
        let couples = true;
        wx.navigateTo({
            url:
                "/pages/schedule/schedule?" +
                serializePathQuery({
                    couples,
                }),
        });
    },
    /**
     * 滑动开始
     */
    touchstart(e) {
        this.setData({
            touchX: e.changedTouches[0].clientX,
            touchY: e.changedTouches[0].clientY,
        });
    },
    /**
     * 滑动停止
     */
    touchend(e) {
        let { clientX: endX, clientY: endY } = e.changedTouches[0];
        let { touchY, touchX, ScheduleId } = this.data;
        const getTouchData = (endX, endY, startX, startY) => {
            let turn = "";
            if (endX - startX > 50 && Math.abs(endY - startY) < 50) {
                //右滑
                turn = "right";
            } else if (endX - startX < -50 && Math.abs(endY - startY) < 50) {
                //左滑
                turn = "left";
            }
            return turn;
        };
        let turn = getTouchData(endX, endY, touchX, touchY);
        if (turn === "left" && ScheduleId == 0) {
            this.setData({
                ScheduleId: 1,
            });
        } else if (turn === "right" && ScheduleId == 1) {
            this.setData({
                ScheduleId: 0,
            });
        } else {
            return;
        }
    },
    /**
     * 切换课表
     * @return {*}
     */
    switchSchedule(e) {
        let _id = e.currentTarget.dataset.id;
        let ScheduleId = this.data.ScheduleId;
        if (_id == ScheduleId) {
            return;
        } else {
            this.setData({
                ScheduleId: _id,
            });
        }
    },
    /**
     * 前往课程表页面
     */
    entryCoure() {
        if (
            !this.data.userInfo.courseInfo ||
            this.data.userInfo.courseInfo.length == 0
        ) {
            wx.switchTab({
                url: "/pages/timetable/timetable",
            });
        }
    },
    /**
     * 同意情侣绑定
     */
    couplesConfirm(e) {
        let { loverInfo } = this.data;
        console.log(e.currentTarget.dataset.type, "couplesConfirm");
        if (e.currentTarget.dataset.type) {
            couplesAdd({
                lovers_id: loverInfo.couplesAdd,
            }).then((v) => {
                if (v.code) {
                    app.getInfo().then((v) => {
                        this.initUserInfo(v);
                    });
                } else {
                    wxShowToast(v.msg);
                }
            });
        }
        this.setData({
            couplesInvite: false,
        });
    },
});
