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

Page({
    data: {
        competition: "",
        programs: [],
        program: {},
        inputProgram: !1,
        loadmore: "",
        contactServiceView: !1,
        config_rechargeable: !1,
        user_vip: !1
    },
    onLoad: function(t) {
        var i = this;
        wx.showLoading({
            title: "正在加载",
            mask: !0
        }), this.getCompetition(t.id), a.collection("_config").doc("config").field({
            rechargeable: !0
        }).get().then(function(t) {
            i.data.config_rechargeable = t.data.rechargeable;
        }).catch(function(t) {
            console.error(t);
        }), a.collection("users").where({
            _openid: e.globalData.openid,
            vipExpiryTime: o.gt(a.serverDate())
        }).count().then(function(t) {
            1 == t.total && (i.data.user_vip = !0);
        }).catch(function(t) {
            console.log(t);
        });
    },
    getCompetition: function(o) {
        var i = this;
        a.collection("competitions").doc(o).field({
            title: !0,
            workers: !0,
            juries: !0,
            rechargeable: !0,
            status: !0,
            proExpiryTime: !0,
            settings: !0
        }).get().then(function(t) {
            var a = t.data, o = new Date();
            a.proExpiryTime && (a.rechargeable = new Date(a.proExpiryTime) > o), i.data.competition = a;
            var n = "oRnCI5JYWT9dmVycOnBjYaX1Yx7k" == e.globalData.openid || i.data.competition.workers.indexOf(e.globalData.openid) >= 0;
            i.setData({
                competition: a,
                isWorker: n
            }), i.getPrograms();
        }).catch(function(e) {
            t.competitionNoExistShowModal(e.errCode);
        });
    },
    getPrograms: function() {
        var t = this;
        a.collection("programs").aggregate().match({
            competition_id: this.data.competition._id
        }).group({
            _id: null,
            programs: i.addToSet({
                _id: "$_id",
                competition_id: "$competition_id",
                index: "$index",
                note: "$note",
                title: "$title",
                image: "$image",
                skipJuries: "$skipJuries"
            })
        }).end().then(function(e) {
            for (var a = e.list.length >= 1 ? e.list[0].programs : [], o = 0; o < a.length; o++) a[o].skipJuries || (a[o].skipJuries = []);
            a.sort(function(t, e) {
                return t.index - e.index;
            }), wx.hideLoading(), wx.stopPullDownRefresh(), 0 == a.length ? t.setData({
                loadmore: "暂未添加参赛者"
            }) : (t.setData({
                programs: a,
                loadmore: "全部加载"
            }), t.getJuries(a, t.data.competition.juries));
        }).catch(function(t) {
            console.error(t);
        });
    },
    getJuries: function(t, e) {
        var o = this;
        a.collection("users").aggregate().addFields({
            matched: i.in([ "$_openid", e ])
        }).match({
            matched: !0
        }).group({
            _id: null,
            juries: i.addToSet({
                _openid: "$_openid",
                avatarUrl: "$avatarUrl",
                authorized: "$authorized",
                nickName: "$nickName",
                realName: "$realName"
            })
        }).end().then(function(e) {
            for (var a = e.list.length >= 1 ? e.list[0].juries : [], i = [], n = 0; n < a.length; n++) i.push(a[n]._openid), 
            a[n].authorized || a[n].avatarUrl ? a[n].name = a[n].realName ? a[n].realName : a[n].nickName ? a[n].nickName : "无昵称或未授权微信登录" : (a[n].name = "无昵称或未授权微信登录", 
            a[n].avatarUrl = "/images/user-unlogin.png");
            for (var r = 0; r < t.length; r++) for (var s = 0; s < t[r].skipJuries.length; s++) i.indexOf(t[r].skipJuries[s]) >= 0 && (t[r].skipJuries[s] = a[i.indexOf(t[r].skipJuries[s])]);
            o.setData({
                juries: a,
                programs: t
            });
        });
    },
    addSkipJury: function(t) {
        var i = this, n = this.data.juries, r = this.data.programs, s = this.data.competition, c = t.currentTarget.dataset.program, d = t.currentTarget.dataset.idxprogram, l = t.detail.value;
        if (n.length) if ((this.data.competition.rechargeable || this.data.config_rechargeable || this.data.user_vip) && "example" != this.data.competition._id) if (s.workers.indexOf(e.globalData.openid) >= 0) {
            var u = -1;
            c.skipJuries && c.skipJuries.length > 0 && (u = c.skipJuries.findIndex(function(t) {
                return n[l]._openid == t._openid;
            })), u >= 0 ? wx.showToast({
                title: "重复设置评委",
                icon: "none",
                duration: 1500
            }) : (wx.showLoading({
                title: "正在提交",
                mask: !0
            }), a.collection("programs").doc(c._id).update({
                data: {
                    skipJuries: o.push(n[l]._openid)
                }
            }).then(function(t) {
                r[d].skipJuries.push(n[l]), i.setData({
                    programs: r
                }), wx.showToast({
                    title: "设置评委回避",
                    icon: "success",
                    duration: 1500
                });
            }));
        } else wx.showToast({
            title: "仅工作人员有权限",
            icon: "none",
            duration: 1500
        }); else "example" == this.data.competition._id ? wx.showToast({
            title: "比赛示例不能使用该功能",
            icon: "none",
            duration: 1e3
        }) : this.setData({
            contactServiceView: !0
        });
    },
    deleteSkipJury: function(t) {
        if ("example" == this.data.competition._id) wx.showToast({
            title: "比赛示例的参赛者不能使用此操作",
            icon: "none",
            duration: 1e3
        }); else {
            var i = this, n = i.data.competition, r = i.data.programs, s = t.currentTarget.dataset.program, c = t.currentTarget.dataset.idxprogram, d = t.currentTarget.dataset.skipjuryopenid;
            n.workers.indexOf(e.globalData.openid) >= 0 && wx.showActionSheet({
                itemList: [ "删除该回避评委" ],
                itemColor: "#767676",
                success: function(t) {
                    switch (t.tapIndex) {
                      case 0:
                        wx.showLoading({
                            title: "正在提交",
                            mask: !0
                        }), a.collection("programs").doc(s._id).update({
                            data: {
                                skipJuries: o.pull(d)
                            }
                        }).then(function(t) {
                            var e = s.skipJuries.findIndex(function(t) {
                                return d == t._openid;
                            });
                            e > -1 && r[c].skipJuries.splice(e, 1), i.setData({
                                programs: r
                            }), wx.showToast({
                                title: "删除该评委",
                                icon: "success",
                                duration: 1500
                            });
                        }).catch(console.error);
                    }
                }
            });
        }
    },
    formSubmit: function(t) {
        var e = this;
        if (wx.showLoading({
            title: "正在提交",
            mask: !0
        }), "example" == this.data.competition._id) wx.hideLoading(), wx.showToast({
            title: "比赛示例不支持添加参赛者",
            icon: "none",
            duration: 3e3
        }); else {
            var a = {
                index: parseInt(t.detail.value.index),
                title: t.detail.value.title,
                note: t.detail.value.note
            };
            this.data.program._id ? (a._id = this.data.program._id, a.competition_id = this.data.competition._id, 
            a.image = this.data.program.image ? this.data.program.image : "") : (a.competition_id = this.data.competition._id, 
            a.votesTotal = 0, a.averageScore = 0, a.scores = [], a.awards = []), a.title && a.index >= 0 && a.index <= 1e3 ? wx.cloud.callFunction({
                name: "textSecCheck",
                data: {
                    text: JSON.stringify(a)
                }
            }).then(function(t) {
                87014 == t.result.errCode ? (wx.hideLoading(), wx.showModal({
                    content: "系统检测所提交的文本含有违规用词，请修改后再提交",
                    showCancel: !1,
                    confirmColor: "#FF5A5F",
                    confirmText: "我知道了",
                    success: function(t) {},
                    fail: function(t) {
                        console.log(t);
                    }
                })) : a._id ? wx.cloud.callFunction({
                    name: "program",
                    data: {
                        program: a,
                        operation: "update"
                    }
                }).then(function(t) {
                    wx.hideLoading(), wx.showToast({
                        title: "编辑参赛者",
                        icon: "success",
                        duration: 2e3
                    });
                    var o = e.data.programs.findIndex(function(t) {
                        return a._id == t._id;
                    });
                    e.data.programs[o] = a, e.setData({
                        programs: e.data.programs,
                        program: {},
                        inputProgram: !1
                    });
                }) : wx.cloud.callFunction({
                    name: "program",
                    data: {
                        program: a,
                        operation: "add"
                    }
                }).then(function(t) {
                    wx.hideLoading(), wx.showToast({
                        title: "已添加",
                        icon: "success",
                        duration: 2e3
                    }), a._id = t.result._id, e.data.programs.push(a), e.setData({
                        programs: e.data.programs,
                        program: {},
                        inputProgram: e.data.competition.rechargeable || e.data.programs.length < 10 || e.data.config_rechargeable || e.data.user_vip
                    }), "暂未添加参赛者参赛者" == e.data.loadmore && e.setData({
                        loadmore: "全部加载"
                    }), "已结束" == e.data.competition.status && wx.cloud.callFunction({
                        name: "competition",
                        data: {
                            competition: {
                                _id: e.data.competition._id,
                                status: "正常"
                            },
                            operation: "update"
                        }
                    }).then(function(t) {});
                });
            }) : (wx.hideLoading(), !a.index || a.index < 0 ? wx.showToast({
                title: "序号为大于等于0的整数",
                icon: "none",
                duration: 2e3
            }) : a.index > 1e3 ? wx.showToast({
                title: "序号为小于1000的整数",
                icon: "none",
                duration: 2e3
            }) : a.title || wx.showToast({
                title: "请添加参赛者名称",
                icon: "none",
                duration: 2e3
            }));
        }
    },
    inputProgram: function() {
        (this.data.competition.rechargeable || this.data.programs.length < 10 || this.data.config_rechargeable || this.data.user_vip) && "example" != this.data.competition._id ? this.setData({
            inputProgram: !this.data.inputProgram,
            program: {}
        }) : "example" == this.data.competition._id ? wx.showToast({
            title: "比赛示例不能添加参赛者",
            icon: "none",
            duration: 2e3
        }) : this.setData({
            contactServiceView: !0
        });
    },
    clearProgram: function() {
        this.setData({
            program: {}
        });
    },
    editProgram: function(t) {
        if (this.data.competition.workers.indexOf(e.globalData.openid) >= 0) if ("example" == this.data.competition._id) wx.showToast({
            title: "比赛示例的参赛者不能编辑",
            icon: "none",
            duration: 2e3
        }); else {
            var a = t.currentTarget.dataset.program;
            this.setData({
                inputProgram: !0,
                program: a
            });
        } else wx.showToast({
            title: "仅工作人员有权限编辑参赛者",
            icon: "none",
            duration: 1500
        });
    },
    chooseImage: function(t) {
        if ("example" != this.data.competition._id) {
            var e = t.currentTarget.dataset.program, a = t.currentTarget.dataset.index, o = this;
            wx.chooseImage({
                count: 1,
                sizeType: [ "original", "compressed" ],
                sourceType: [ "album" ],
                success: function(t) {
                    var i = String(t.tempFilePaths[0]);
                    wx.getFileInfo({
                        filePath: i,
                        success: function(t) {
                            console.log("getFileInfo:", t);
                            var n = t;
                            if (wx.showLoading({
                                title: "上传图片",
                                mask: !0
                            }), n.size > 512e3) {
                                var r = parseInt(512e5 / n.size + 1);
                                wx.compressImage({
                                    src: i,
                                    quality: r,
                                    success: function(t) {
                                        var i = t.tempFilePath;
                                        wx.getFileInfo({
                                            filePath: i,
                                            success: function(t) {
                                                console.log("getFileInfo:", t), o.uploadImage(e, a, i, n.digest);
                                            }
                                        });
                                    }
                                });
                            } else o.uploadImage(e, a, i, n.digest);
                        }
                    });
                }
            });
        } else "example" == this.data.competition._id ? wx.showToast({
            title: "比赛示例的参赛者不能上传图片",
            icon: "none",
            duration: 2e3
        }) : this.setData({
            contactServiceView: !0
        });
    },
    uploadImage: function(t, e, a, o) {
        var i = this;
        wx.cloud.uploadFile({
            cloudPath: "programImages/" + t.competition_id + "/" + o + ".jpg",
            filePath: a
        }).then(function(n) {
            t.image = "cloud://release-bu5dc.7265-release-bu5dc-1301069672/programImages/" + t.competition_id + "/" + o + ".jpg", 
            wx.cloud.callFunction({
                name: "program",
                data: {
                    program: t,
                    operation: "update"
                }
            }).then(function(n) {
                wx.hideLoading(), wx.showToast({
                    title: "上传成功",
                    icon: "success",
                    duration: 1500
                }), i.data.programs[e].image = "cloud://release-bu5dc.7265-release-bu5dc-1301069672/programImages/" + t.competition_id + "/" + o + ".jpg", 
                i.setData({
                    programs: i.data.programs
                }), i.imgSecCheck(t, e, a);
            });
        });
    },
    imgSecCheck: function(t, e, a) {
        var o = this, i = wx.getFileSystemManager().readFileSync(a);
        wx.cloud.callFunction({
            name: "imgSecCheck",
            data: {
                buffer: i
            }
        }).then(function(a) {
            var i = a.result.errCode;
            87014 == i && (wx.showToast({
                title: "图片检测到违规内容，请重新选择图片",
                icon: "none",
                duration: 300
            }), wx.cloud.deleteFile({
                fileList: [ t.image ]
            }).then(function(a) {
                t.image = "", wx.cloud.callFunction({
                    name: "program",
                    data: {
                        program: t,
                        operation: "update"
                    }
                }).then(function(t) {
                    o.data.programs[e].image = "", o.setData({
                        programs: o.data.programs
                    });
                });
            })), 0 == i && console.log("海报检测通过");
        }).catch(function(t) {
            console.log(t);
        });
    },
    deleteImage: function(t) {
        var a = t.currentTarget.dataset.program, o = t.currentTarget.dataset.index;
        if (this.data.competition.workers.indexOf(e.globalData.openid) >= 0) {
            var i = this;
            wx.showModal({
                content: "确认删除图片吗？",
                cancelColor: "#484848",
                cancelText: "取消",
                confirmColor: "#FF5A5F",
                confirmText: "确定",
                success: function(t) {
                    t.confirm && (wx.showLoading({
                        title: "删除图片",
                        mask: !0
                    }), wx.cloud.deleteFile({
                        fileList: [ a.image ]
                    }).then(function(t) {
                        a.image = "", wx.cloud.callFunction({
                            name: "program",
                            data: {
                                program: a,
                                operation: "update"
                            }
                        }).then(function(t) {
                            wx.hideLoading(), wx.showToast({
                                title: "已删除",
                                icon: "success",
                                duration: 1500
                            }), i.data.programs[o].image = "", i.setData({
                                programs: i.data.programs
                            });
                        });
                    }));
                },
                fail: function(t) {
                    console.log(t);
                }
            });
        } else wx.showToast({
            title: "仅工作人员有权限删除照片",
            icon: "none",
            duration: 2500
        });
    },
    deleteProgram: function(t) {
        if (this.data.competition.workers.indexOf(e.globalData.openid) >= 0) if ("example" == this.data.competition._id) wx.showToast({
            title: "比赛示例的参赛者不能删除",
            icon: "none",
            duration: 2e3
        }); else {
            var a = t.currentTarget.dataset.program, o = t.currentTarget.dataset.index, i = this;
            wx.showModal({
                content: "确认删除该参赛者吗？如果评委已提交过分数，将同步删除。",
                cancelColor: "#484848",
                cancelText: "取消",
                confirmColor: "#FF5A5F",
                confirmText: "确定",
                success: function(t) {
                    t.confirm && (wx.showLoading({
                        title: "正在删除",
                        mask: !0
                    }), wx.cloud.callFunction({
                        name: "program",
                        data: {
                            program: a,
                            operation: "delete"
                        }
                    }).then(function(t) {
                        wx.hideLoading(), wx.showToast({
                            title: "已删除",
                            icon: "success",
                            duration: 2e3
                        }), i.data.programs.splice(o, 1), i.setData({
                            programs: i.data.programs
                        });
                    }));
                },
                fail: function(t) {
                    console.log(t);
                }
            });
        } else wx.showToast({
            title: "仅工作人员有权限删除参赛者",
            icon: "none",
            duration: 2500
        });
    },
    shuffle: function() {
        var t = this.data.programs, e = this;
        0 == t.length ? wx.showToast({
            title: "请先添加参赛者",
            icon: "none",
            duration: 1500
        }) : wx.showModal({
            content: "建议在参赛者的共同见证下抽签，抽签后参赛者的序号将随机打乱",
            cancelColor: "#484848",
            cancelText: "取消",
            confirmColor: "#FF5A5F",
            confirmText: "开始抽签",
            success: function(o) {
                if (o.confirm) {
                    for (var i = 0; i < t.length; i++) t[i].index = 0;
                    e.setData({
                        programs: t
                    }), wx.showLoading({
                        title: "随机抽签中",
                        mask: !0
                    }), function(t) {
                        for (var e, a, o = t.length; o > 0; ) e = Math.floor(Math.random() * o), a = t[o - 1], 
                        t[o - 1] = t[e], t[e] = a, o--;
                    }(t);
                    for (var n = 0; n < t.length; n++) t[n].index = n + 1;
                    t.sort(function(t, e) {
                        return t.index - e.index;
                    }), wx.cloud.callFunction({
                        name: "program",
                        data: {
                            programs: t,
                            operation: "updateAllPrograms"
                        }
                    }).then(function(o) {
                        wx.hideLoading(), wx.showToast({
                            title: "抽签完毕",
                            icon: "success",
                            duration: 1500
                        }), e.setData({
                            programs: t
                        }), a.collection("behaviors").add({
                            data: {
                                createTime: a.serverDate(),
                                type: "shuffle",
                                page: "programs"
                            }
                        }).then(function(t) {}).catch(console.error);
                    });
                }
            },
            fail: function(t) {
                console.log(t);
            }
        });
    },
    onPullDownRefresh: function() {
        this.data.programs = [], this.getCompetition(this.data.competition._id);
    },
    hideContactService: function(t) {
        this.setData({
            contactServiceView: !1
        });
    },
    contactService: function(t) {
        a.collection("behaviors").add({
            data: {
                createTime: a.serverDate(),
                competition_id: this.data.competition._id,
                competition_title: this.data.competition.title,
                type: "contactService",
                page: "programs"
            }
        }).then(function(t) {}).catch(console.error), this.setData({
            contactServiceView: !1
        });
    },
    importPrograms: function(t) {
        var e = this;
        wx.showModal({
            title: "选择Excel表文件导入添加",
            content: "Excel表无需标题行，第1列为整数序号，第2列为参赛者名称，第3列为备注可不填。先把Excel表发送到手机微信的“文件传输助手”方可选择导入，电脑端不能使用导入功能。导入数量较多时需要几秒后下拉刷新一下才显示全部。",
            cancelColor: "#484848",
            cancelText: "取消",
            confirmColor: "#FF5A5F",
            confirmText: "选择文件",
            success: function(t) {
                t.confirm && ((e.data.competition.rechargeable || e.data.config_rechargeable || e.data.user_vip) && "example" != e.data.competition._id ? wx.chooseMessageFile({
                    count: 1,
                    type: "file",
                    success: function(t) {
                        var a = t.tempFiles[0].name.split(".");
                        if ("xlsx" == a[1] || "xls" == a[1]) {
                            var o = t.tempFiles[0].path;
                            wx.showLoading({
                                title: "上传Excel表",
                                mask: !0
                            }), wx.cloud.uploadFile({
                                cloudPath: "programExcels/" + e.data.competition._id + ".xlsx",
                                filePath: o
                            }).then(function(t) {
                                wx.showLoading({
                                    title: "导入添加",
                                    mask: !0
                                });
                                var a = t.fileID;
                                wx.cloud.callFunction({
                                    name: "importPrograms",
                                    data: {
                                        fileID: a,
                                        competition_id: e.data.competition._id
                                    }
                                }).then(function(t) {
                                    87014 == t.result.errCode ? (wx.hideLoading(), wx.showModal({
                                        content: "系统检测所提交的文本含有违规用词，请修改后再提交",
                                        showCancel: !1,
                                        confirmColor: "#FF5A5F",
                                        confirmText: "我知道了",
                                        success: function(t) {},
                                        fail: function(t) {
                                            console.log(t);
                                        }
                                    })) : (wx.showToast({
                                        title: "完成添加",
                                        icon: "success",
                                        duration: 1500
                                    }), wx.showModal({
                                        showCancel: !1,
                                        title: "导入完成",
                                        content: "如暂未显示所有参赛者请稍后下拉刷新",
                                        confirmColor: "#FF5A5F",
                                        confirmText: "好的",
                                        success: function(t) {
                                            e.data.programs = [], e.getPrograms();
                                        },
                                        fail: function(t) {
                                            console.log(t);
                                        }
                                    })), wx.cloud.deleteFile({
                                        fileList: [ a ]
                                    }).then(function(t) {});
                                });
                            }).catch(function(t) {});
                        } else wx.showToast({
                            title: "不是Excel文件",
                            icon: "none",
                            duration: 1500
                        });
                    }
                }) : "example" == e.data.competition._id ? wx.showToast({
                    title: "比赛示例不能添加参赛者",
                    icon: "none",
                    duration: 2e3
                }) : e.setData({
                    contactServiceView: !0
                }));
            },
            fail: function(t) {
                console.log(t);
            }
        });
    },
    onShareAppMessage: function() {
        return {
            title: "邀请你填写参赛信息@" + this.data.competition.title,
            path: "/pages/competition/programs/programs?add=true&id=" + this.data.competition._id,
            imageUrl: "/images/sharePic.png"
        };
    }
});