def get(self, round_id):

        match_round = MatchRound.get_or_404(id=round_id)
        match = Match.get_or_404(id=match_round.match_id)

        query = MatchMember.select().where(
            MatchMember.match_id == match.id,
            MatchMember.state == MatchMember.MatchMemberState.normal)

        members = []
        for member in query:
            members.append({"id": member.id, "name": member.name})

        query = MatchAgainst.select().where(
            MatchAgainst.round_id == match_round.id).order_by(
                MatchAgainst.id.asc())

        againsts = []
        for against in query:
            againsts.append(against.info)

        match_options = MatchOption.select().where(
            MatchOption.match_id == match.id)

        self.render("match/round_againsts.html",
                    match=match,
                    match_round=match_round,
                    members=members,
                    againsts=againsts,
                    match_options=match_options)
    def get(self, match_id):
        match = Match.get_or_404(id=match_id)

        # 获取赛事分组信息
        groups = MatchGroup.select().where(
            MatchGroup.match_id == match.id).order_by(
                MatchGroup.sort_num.desc())

        # 获取报名表自定义选项
        custom_options = MatchOption.select().where(
            MatchOption.match_id == match.id).order_by(
                MatchOption.sort_num.desc())

        rounds = MatchRound.select(MatchRound, ).where(
            MatchRound.match_id == match.id).order_by(MatchRound.created.asc(),
                                                      MatchRound.id.asc())

        covers = MatchCover.select().where(
            MatchCover.match_id == match.id).order_by(MatchCover.id.desc())

        # 获取对阵图
        RightMember = MatchMember.alias()

        against_query = MatchAgainst.select(
            MatchAgainst, MatchMember, RightMember).join(
                MatchMember,
                on=(MatchAgainst.left_member_id == MatchMember.id
                    ).alias("left_member")).switch(MatchAgainst).join(
                        RightMember,
                        join_type=JOIN_LEFT_OUTER,
                        on=(MatchAgainst.right_member_id == RightMember.id
                            ).alias("right_member")).where(
                                MatchAgainst.match_id == match_id).order_by(
                                    MatchAgainst.start_time.asc())

        againsts = {}
        for against in against_query:
            if against.round_id not in againsts:
                againsts[against.round_id] = []

            againsts[against.round_id].append(against)

        # 如果已经结束 获取是否已经提交了结算申请
        is_application_exist =\
            SettlementApplication.is_application_exist(match_id)

        self.render("match/detail.html",
                    match=match,
                    rounds=rounds,
                    groups=groups,
                    custom_options=custom_options,
                    covers=covers,
                    againsts=againsts,
                    is_application_exist=is_application_exist)
    def parse_options(self, match_id):

        # 获取自定义选项
        query = MatchOption.select().where(
            MatchOption.match_id == match_id).order_by(
                MatchOption.sort_num.desc())

        option_values = []
        for option in query:
            is_photo = False

            if option.field_type in ("photo", "file"):
                is_photo = True
                to_bucket = self.settings['qiniu_avatar_bucket']
                to_key = "match:%s%s" % (match_id, time.time())
                to_key = hashlib.md5(to_key.encode()).hexdigest()

                try:
                    value = self.upload_file("option_{0}".format(option.id),
                                             to_bucket=to_bucket,
                                             to_key=to_key,
                                             required=option.required)
                except ArgumentError as e:
                    raise ApiException(
                        400, "{0}{1}".format(option.title, e.message))

            else:
                value = self.get_argument("option_{0}".format(option.id), None)
                if option.required and not value:
                    raise ApiException(400, "{0}必填".format(option.title))

                elif option.field_type in ("choice",) and \
                        value not in option.choices.replace("|", "|").split("|"):

                    raise ApiException(400, "{0}选择错误".format(option.title))

                elif option.field_type in ("choice", ):
                    choices = set(option.choices.replace("|", "|").split("|"))
                    value = set(value.split("|"))

                    if len(choices & value) == 0:
                        raise ApiException(400, "{0}选择错误".format(option.title))

                    value = "|".join(value)

            option_values.append({
                "option_id": option.id,
                "option_title": option.title,
                "value": value,
                "is_photo": is_photo
            })

        return option_values
    def get(self, match_id):
        """获取赛事信息

        :match_id: 赛事ID
        :returns: 赛事信息

        """

        match = Match.get_or_404(id=match_id)

        # 获取自定义选项
        query = MatchOption.select().where(
            MatchOption.match_id == match.id).order_by(
                MatchOption.sort_num.desc())

        options = []
        for option in query:
            options.append(option.info)

        self.write({"options": match.fields, "custom_options": options})
    def get(self, match_id):

        match = Match.get_or_404(id=match_id)
        match.sport_id = Sport.get_or_none(id=match.sport_id)

        match.group_type = str(match.group_type)
        team = Team.get_or_404(id=match.team_id)
        form = EditMatchFrom(obj=match, team=team)

        # 获取赛事分组信息
        query = MatchGroup.select().where(
            MatchGroup.match_id == match.id).order_by(
                MatchGroup.sort_num.desc())

        groups = []
        for group in query:
            group = group.info
            group['max'] = group['max_members']
            groups.append(group)

        # 获取报名表自定义选项
        query = MatchOption.select().where(
            MatchOption.match_id == match.id).order_by(
                MatchOption.sort_num.desc())

        custom_options = []
        for option in query:
            option = option.info
            if 'choices' in option:
                option['choices'] = "|".join(option['choices'])
            custom_options.append(option)

        self.render("match/edit.html",
                    form=form,
                    match=match,
                    cities=ChinaCity.get_cities(),
                    group_type=match.group_type,
                    groups=groups,
                    custom_options=custom_options,
                    options=match.fields)
    def post(self, match_id):
        match = Match.get_or_404(id=match_id)
        team = Team.get_or_404(id=match.team_id)
        form = EditMatchFrom(self.arguments, team=team)

        groups = self.parse_groups()
        options = self.parse_options()
        custom_options = self.parse_custom_options()

        # 验证分组设置
        groups_validated = self.validate_groups(form, groups)

        if form.validate() and groups_validated:
            with (self.db.transaction()):
                form.populate_obj(match)

                # 计算赛事总人数限制
                if intval(match.group_type) == 1:
                    match.price = min(map(lambda x: float(x['price']),
                                          groups)) if groups else 0
                    match.max_members = reduce(lambda x, y: x + y,
                                               map(lambda x: x['max'],
                                                   groups)) if groups else 0

                if "coverfile" in self.request.files:
                    to_bucket = self.settings['qiniu_avatar_bucket']
                    to_key = "match:%s%s" % (self.current_user.id, time.time())
                    to_key = hashlib.md5(to_key.encode()).hexdigest()

                    cover_key = self.upload_file(
                        "coverfile",
                        to_bucket=to_bucket,
                        to_key=to_key,
                    )

                    match.cover_key = cover_key

                match.user_id = self.current_user.id
                match.fields = options

                if not match.join_end:
                    match.join_end = match.start_time

                match.save()

                if intval(match_id) > 0:
                    group_ids = [
                        group['id'] for group in groups if group['id'] > 0
                    ]

                    if len(group_ids) > 0:
                        MatchGroup.delete().where(
                            MatchGroup.match_id == intval(match_id),
                            MatchGroup.id.not_in(group_ids)).execute()

                    else:
                        MatchGroup.delete().where(
                            MatchGroup.match_id == intval(match_id)).execute()

                # 保存分组
                for group in groups:
                    if group['id'] > 0:
                        MatchGroup.update(
                            name=group['name'],
                            price=group['price'],
                            max_members=group['max']).where(
                                MatchGroup.id == group['id']).execute()

                    else:
                        MatchGroup.create(match_id=match.id,
                                          name=group['name'],
                                          price=group['price'],
                                          max_members=group['max'])

                if intval(match_id) > 0:
                    custom_option_ids = [
                        custom_option['id'] for custom_option in custom_options
                        if custom_option['id'] > 0
                    ]

                    if len(custom_option_ids) > 0:
                        MatchOption.delete().where(
                            MatchOption.match_id == intval(match_id),
                            MatchOption.id.not_in(
                                custom_option_ids)).execute()

                    else:
                        MatchOption.delete().where(MatchOption.match_id ==
                                                   intval(match_id)).execute()

                # 保存自定义选项
                for custom_option in custom_options:
                    if custom_option['id'] > 0:
                        MatchOption.update(
                            title=custom_option['title'],
                            field_type=custom_option['field_type'],
                            required=custom_option['required'],
                            choices=custom_option['choices'],
                        ).where(
                            MatchOption.id == custom_option['id']).execute()
                    else:
                        MatchOption.create(
                            match_id=match.id,
                            title=custom_option['title'],
                            field_type=custom_option['field_type'],
                            required=custom_option['required'],
                            choices=custom_option['choices'],
                        )

            # MatchService.add_match_start_notify(match)
            self.redirect(self.reverse_url("admin_match_detail", match.id))
            return

        province = self.get_argument("province", None)
        if province:
            form.city.choices = ChinaCity.get_cities(province)

        self.validate_groups(form, groups)

        self.render("match/edit.html",
                    form=form,
                    match=match,
                    cities=ChinaCity.get_cities(),
                    groups=groups,
                    group_type=self.get_argument("group_type", "0"),
                    options=options,
                    custom_options=custom_options)