# encoding: UTF-8
from sqlalchemy import func

from ..model.createResultInfo import CreateResult

from sqlalchemy.exc import NoResultFound
from logger import logger


class CreateResultDao(object):
    @staticmethod
    def get_result_list_by_filters(session, filter_list, page=1, limit=20):
        rets = session.query(CreateResult) \
            .filter(*filter_list).filter(CreateResult.del_flag == 0, CreateResult.status == 1) \
            .offset((int(page) - 1) * int(limit)) \
            .limit(limit) \
            .all()
        total = session.query(CreateResult).filter(*filter_list).filter(CreateResult.del_flag == 0,
                                                                        CreateResult.status == 1).count()
        return rets, total

    @staticmethod
    def get_result_list_by_team_filters(session, filter_list, list_team_name, page=1, limit=20):
        # rets = session.query(CreateResult) \
        #     .filter(*filter_list).filter(CreateResult.del_flag == 0, CreateResult.status == 1) \
        #     .filter(CreateResult.team_name.in_(list_team_name)) \
        #     .offset((int(page) - 1) * int(limit)) \
        #     .limit(limit) \
        #     .all()
        # total = session.query(CreateResult).filter(*filter_list).filter(CreateResult.del_flag == 0,
        #                                                                 CreateResult.status == 1).filter(
        #     CreateResult.team_name.in_(list_team_name)).count()
        rets = session.query(CreateResult) \
            .filter(*filter_list).filter(CreateResult.del_flag == 0, CreateResult.status == 1) \
            .offset((int(page) - 1) * int(limit)) \
            .limit(limit) \
            .all()
        total = session.query(CreateResult).filter(*filter_list).filter(CreateResult.del_flag == 0,
                                                                        CreateResult.status == 1).count()
        return rets, total

    @staticmethod
    def get_result_list_no_filters(session, page=1, limit=20):
        rets = session.query(CreateResult) \
            .filter(CreateResult.del_flag == 0, CreateResult.status == 1) \
            .order_by(CreateResult.modified_time.desc()) \
            .offset((int(page) - 1) * int(limit)) \
            .limit(limit) \
            .all()
        total = session.query(CreateResult).filter(CreateResult.del_flag == 0, CreateResult.status == 1).count()
        return rets, total

    @staticmethod
    def get_result_list_no_team_filters(session, list_team_name, page=1, limit=20):
        # rets = session.query(CreateResult) \
        #     .filter(CreateResult.del_flag == 0, CreateResult.status == 1) \
        #     .filter(CreateResult.team_name.in_(list_team_name)) \
        #     .order_by(CreateResult.modified_time.desc()) \
        #     .offset((int(page) - 1) * int(limit)) \
        #     .limit(limit) \
        #     .all()
        # total = session.query(CreateResult).filter(CreateResult.del_flag == 0, CreateResult.status == 1).filter(
        #     CreateResult.team_name.in_(list_team_name)).count()
        rets = session.query(CreateResult) \
            .filter(CreateResult.del_flag == 0, CreateResult.status == 1) \
            .order_by(CreateResult.modified_time.desc()) \
            .offset((int(page) - 1) * int(limit)) \
            .limit(limit) \
            .all()
        total = session.query(CreateResult).filter(CreateResult.del_flag == 0, CreateResult.status == 1).count()
        return rets, total

    @staticmethod
    def get_result_simple_by_filters(session, filter_list):
        rets = session.query(CreateResult) \
            .filter(*filter_list).filter(CreateResult.del_flag == 0) \
            .first()
        return rets

    @staticmethod
    def get_result_detail_info_by_id(session, sid):
        try:
            ret = session.query(CreateResult).filter(CreateResult.create_data_result_id == sid).one()
        except Exception as e:
            logger.warning(f'获取造数基础信息失败: id{sid}, {e}')
            return None, f'获取造数基础信息失败: id{sid}'
        return ret

    @staticmethod
    def save_result_info_record(session, create_info):
        if not isinstance(create_info, dict):
            logger.error('只支持dict类型。build_info type: {}'.format(type(create_info)))
        create_result_info = CreateResult(**create_info)
        session.add(create_result_info)
        # session.flush()
        err = session.done(close=False)
        create_info_id = create_result_info.create_data_result_id
        if err:
            logger.error(f'新增失败！{err}')
            return 0
        if not create_info_id:
            logger.error(f'{create_result_info}获取造数结果id失败！')
            return 0
        # session.commit()
        return create_info_id

    @staticmethod
    def update_result_record(session, update_info, sid):
        create_info = session.query(CreateResult).filter(
            CreateResult.create_data_result_id == sid).one()
        create_info.status = update_info["status"]
        create_info.result_info = update_info["result_info"]
        err_msg = session.done()
        if err_msg:
            return '修改结果失败！'
        return ''

    @staticmethod
    def get_result_numbers_by_month(session, create_data_detail_id, one_month_ago_str):
        ret = session.query(func.count(CreateResult.create_data_detail_id).label('count')).filter(
            CreateResult.created_time >= one_month_ago_str,
            CreateResult.create_data_detail_id == create_data_detail_id, CreateResult.status == 1).group_by(
            CreateResult.method_function_detail
        ).first()
        return ret
