var e = require("../../../49539051658710DF2F35F8564970FAA0.js"), t = getApp(), o = wx.cloud.database(), a = o.command, i = o.command.aggregate;

Page({
    data: {
        competition: "",
        programs: [],
        averageScores: [],
        loadmore: "",
        votes: [],
        isWorker: !1,
        orderBy: "index",
        programSearchIds: [],
        filtrating: !1,
        inputShowed: !1,
        inputVal: "",
        keyword: ""
    },
    onLoad: function(e) {
        var a = this;
        this.data.id = e.id || e.scene, "oRnCI5JYWT9dmVycOnBjYaX1Yx7k" != t.globalData.openid && o.collection("behaviors").add({
            data: {
                createTime: o.serverDate(),
                competition_id: e.id,
                type: "visit",
                role: "audience",
                page: "vote"
            }
        }), o.collection("_config").where({
            _id: "config"
        }).field({
            v: !0,
            adVote: !0
        }).get().then(function(e) {
            a.setData({
                c: t.globalData.c,
                v: e.data[0].v
            }), a.getCompetition();
        }).catch(function(e) {
            console.error(e);
        }), wx.showLoading({
            title: "正在加载"
        });
    },
    getCompetition: function() {
        var a = this, i = this;
        o.collection("competitions").doc(i.data.id).field({
            focus: !1
        }).get().then(function(r) {
            var s = r.data;
            i.data.competition = s, s.startTime = e.formatTime("short", s.startTime);
            var n = s.workers.indexOf(t.globalData.openid) >= 0, d = s.audiences.indexOf(t.globalData.openid) >= 0;
            n || "已删除" != s.status && "已关闭" != s.status ? o.collection("votes").where({
                competition_id: i.data.id,
                _openid: t.globalData.openid
            }).get().then(function(e) {
                var t = e.data ? e.data : [];
                i.data.votes = t, i.setData({
                    v: s.settings && !s.settings.showVote ? "0.0.0" : a.data.v,
                    competition: s,
                    votes: t,
                    focused: d,
                    isWorker: n
                }), i.getPrograms();
            }) : (wx.hideLoading(), wx.stopPullDownRefresh(), wx.hideShareMenu(), wx.showModal({
                showCancel: !1,
                content: "主办方" + s.status + "比赛",
                confirmColor: "#FF5A5F",
                confirmText: "我知道了",
                success: function(e) {
                    wx.reLaunch({
                        url: "/pages/index/index"
                    });
                },
                fail: function(e) {
                    console.log(e);
                }
            }));
        }).catch(function(t) {
            console.error("errCode", t), e.competitionNoExistShowModal(t.errCode);
        });
    },
    getPrograms: function() {
        var t = this, a = this.data.competition, r = this;
        o.collection("programs").aggregate().match({
            competition_id: r.data.id
        }).group({
            _id: null,
            programs: i.addToSet({
                _id: "$_id",
                averageScore: "$averageScore",
                awards: "$awards",
                competition_id: "$competition_id",
                index: "$index",
                note: "$note",
                scores: "$scores",
                title: "$title",
                votesTotal: "$votesTotal",
                judging: "$judging",
                extraPoints: "$extraPoints",
                image: "$image"
            })
        }).end().then(function(o) {
            for (var i = o.list.length >= 1 ? o.list[0].programs : [], s = [], n = 0; n < i.length; n++) {
                if (a.juriesGroups && a.juriesGroups.length >= 1 && a.juriesGroups[0].juriesDetails.length >= 1) for (var d = 0; d < a.juriesGroups.length; d++) a.juriesGroups[d].scores = [];
                for (var c = 0; c < i[n].scores.length; c++) if (-1 == a.juries.indexOf(i[n].scores[c]._openid)) i[n].scores.splice(c, 1), 
                c--; else for (var l = c + 1; l < i[n].scores.length; l++) i[n].scores[c]._openid == i[n].scores[l]._openid && (i[n].scores.splice(l, 1), 
                l--);
                if (i[n].averageScore = 0, i[n].scores.length >= a.juries.length || !i[n].judging || "example" == i[n].competition_id && i[n].scores.length >= 1) {
                    var u = 0, g = {
                        averageScore: 0,
                        totalScore: 0
                    };
                    if (i[n].scores.length > 0) {
                        for (var h = [], p = 0; p < i[n].scores.length; p++) if (h.push(i[n].scores[p].score), 
                        a.juriesGroups && a.juriesGroups.length >= 1 && a.juriesGroups[0].juriesDetails.length >= 1) for (var m = 0; m < a.juriesGroups.length; m++) JSON.stringify(a.juriesGroups[m].juriesDetails).indexOf(i[n].scores[p]._openid) >= 0 && a.juriesGroups[m].scores.push(i[n].scores[p].score);
                        if (a.juriesGroups && a.juriesGroups.length >= 1 && a.juriesGroups[0].juriesDetails.length >= 1) for (var v = 0; v < a.juriesGroups.length; v++) g = e.calculateScores(a.juriesGroups[v].scores, a.rule.decimalPlaces, a.juriesGroups[v].lowestScoresExcludedTotal, a.juriesGroups[v].topScoresExcludedTotal), 
                        u += parseFloat(g.averageScore) * a.juriesGroups[v].weight; else g = e.calculateScores(h, a.rule.decimalPlaces, a.rule.lowestScoresExcludedTotal, a.rule.topScoresExcludedTotal), 
                        u = parseFloat(g.averageScore);
                    } else i[n].arrScores = [];
                    u += i[n].extraPoints, u = parseFloat(u.toFixed(a.rule.decimalPlaces)), s.push(u), 
                    i[n].averageScore = u;
                }
                r.data.votes.length >= 1 && JSON.stringify(r.data.votes).indexOf(i[n]._id) >= 0 ? i[n].voted = !0 : i[n].voted = !1;
            }
            s.sort(function(e, t) {
                return t - e;
            });
            for (var f = 0; f < i.length; f++) i[f].averageScore > 0 ? i[f].order = s.indexOf(i[f].averageScore) + 1 : i[f].order = 1e3, 
            0 == t.data.programSearchIds.length || t.data.programSearchIds.indexOf(i[f]._id) >= 0 ? i[f].searched = !0 : i[f].searched = !1;
            i.sort(function(e, t) {
                return e.index - t.index;
            }), "order" != r.data.orderBy && "votes" != r.data.orderBy || i.sort(function(e, t) {
                return e.order - t.order;
            }), "votes" == r.data.orderBy && i.sort(function(e, t) {
                return t.votesTotal - e.votesTotal;
            }), wx.hideLoading(), wx.stopPullDownRefresh(), 0 == i.length ? r.setData({
                loadmore: "主办方暂未添加参赛者"
            }) : r.setData({
                programs: i,
                loadmore: "全部加载",
                averageScores: s,
                orderBy: r.data.orderBy
            });
        });
    },
    focuseCompetition: function() {
        this.data.focused ? (wx.showToast({
            title: "取消关注",
            icon: "success",
            duration: 500
        }), this.setData({
            focused: !1
        }), wx.cloud.callFunction({
            name: "role",
            data: {
                competition: {
                    _id: this.data.competition._id
                },
                operation: "deleteRole",
                role: "audience",
                openidDeleted: t.globalData.openid
            }
        }).then(function(e) {})) : (this.setData({
            focused: !0
        }), wx.showToast({
            title: "可在“首页-比赛精选”中再次查看",
            icon: "none",
            duration: 1500
        }), wx.cloud.callFunction({
            name: "role",
            data: {
                competition: {
                    _id: this.data.competition._id
                },
                operation: "addRole",
                role: "audience"
            }
        }).then(function(e) {}));
    },
    vote: function(e) {
        var t = this;
        if (this.data.v != this.data.c && this.data.votes.length >= 1) ; else if (this.data.votes.length >= this.data.competition.settings.votesTotal) this.data.v == this.data.c && wx.showToast({
            title: "邀请好友一起来送花吧~",
            icon: "none",
            duration: 1500
        }); else {
            wx.showLoading({
                title: "正在提交",
                mask: !0
            });
            var i = e.currentTarget.dataset.id;
            o.collection("votes").add({
                data: {
                    program_id: i,
                    competition_id: this.data.competition._id,
                    createTime: o.serverDate()
                }
            }).then(function(e) {
                t.data.votes.push({
                    program_id: i,
                    competition_id: t.data.competition._id
                }), wx.hideLoading(), t.data.votes.length == t.data.competition.settings.votesTotal || t.data.v != t.data.c ? wx.showToast({
                    title: "谢谢参与",
                    icon: "success",
                    duration: 1500
                }) : wx.showToast({
                    title: "还剩" + (t.data.competition.settings.votesTotal - t.data.votes.length) + "朵可送",
                    icon: "success",
                    duration: 1500
                }), t.setData({
                    votes: t.data.votes
                }), o.collection("programs").doc(i).update({
                    data: {
                        votesTotal: a.inc(1)
                    }
                }).then(function(e) {
                    var o = t.data.programs.findIndex(function(e) {
                        return e._id == i;
                    });
                    t.data.programs[o].votesTotal++, t.data.programs[o].voted = !0, t.setData({
                        programs: t.data.programs
                    });
                }).catch(console.error);
            });
        }
    },
    onPullDownRefresh: function() {
        this.data.programs = [], this.getCompetition();
    },
    refresh: function() {
        wx.showLoading({
            title: "正在刷新",
            mask: !0
        }), this.data.programs = [], this.getCompetition();
    },
    changeOrderBy: function(e) {
        switch (wx.showLoading({
            title: "切换排序",
            mask: !0
        }), this.data.orderBy) {
          case "index":
            this.data.orderBy = "order", this.data.programs = [], this.getCompetition();
            break;

          case "order":
            this.data.c == this.data.v ? this.data.orderBy = "votes" : this.data.orderBy = "index", 
            this.data.programs = [], this.getPrograms();
            break;

          case "votes":
            this.data.orderBy = "index", this.data.programs = [], this.getPrograms();
        }
    },
    showInput: function() {
        this.setData({
            inputShowed: !0
        });
    },
    hideInput: function() {
        this.setData({
            programs: [],
            loadmore: "",
            keyword: "",
            inputVal: "",
            inputShowed: !1
        }), this.data.programSearchIds = [], this.getPrograms();
    },
    clearInput: function() {
        this.setData({
            inputVal: ""
        }), this.data.programSearchIds = [];
    },
    inputTyping: function(e) {
        this.setData({
            inputVal: e.detail.value
        }), e.detail.value || (this.data.programSearchIds = []);
    },
    inputFinish: function(e) {
        if ("" == e.detail.value.replace(/\s*/g, "").length) wx.showToast({
            title: "请输入关键词",
            icon: "none",
            duration: 1e3
        }); else {
            var t = e.detail.value.replace(/\s*/g, "");
            wx.showLoading({
                title: "正在加载",
                mask: !0
            }), this.programSearchIds(t, this.data.competition._id);
        }
    },
    programSearchIds: function(e, t) {
        var i = this, r = this.data.programSearchIds.length;
        o.collection("programs").where({
            competition_id: t
        }).where(a.or([ {
            title: o.RegExp({
                regexp: e,
                options: "i"
            })
        }, {
            note: o.RegExp({
                regexp: e,
                options: "i"
            })
        }, {
            index: o.RegExp({
                regexp: e,
                options: "i"
            })
        } ])).field({
            _id: !0
        }).skip(r).get().then(function(o) {
            if (wx.hideLoading(), 20 == o.data.length) {
                for (var a = 0; a < o.data.length; a++) i.data.programSearchIds.push(o.data[a]._id);
                i.programSearchIds(e, t);
            } else {
                for (var r = 0; r < o.data.length; r++) i.data.programSearchIds.push(o.data[r]._id);
                0 == i.data.programSearchIds.length ? i.setData({
                    programs: [],
                    loadmore: "搜索结果为空"
                }) : i.getPrograms();
            }
        }).catch(console.error);
    },
    drawPoster: function() {
        var e = this.data.competition;
        wx.navigateTo({
            url: "/pages/competition/drawPoster/drawPoster",
            success: function(t) {
                t.eventChannel.emit("acceptDataFromOpenerPage", {
                    competition: e,
                    role: "vote"
                });
            }
        });
    },
    previewImage: function(e) {
        console.log(e);
        var t = e.currentTarget.dataset.image;
        wx.previewImage({
            current: t,
            urls: [ t ]
        });
    },
    onShareAppMessage: function(e) {
        return {
            title: "查看成绩一起加油打Call@" + this.data.competition.title,
            path: "/pages/competition/vote/vote?id=" + this.data.competition._id
        };
    }
});