# encoding: UTF-8
from ..model.createDataNumber import CreateDataNumber

from logger import logger


class CreateNumberDao(object):
    @staticmethod
    def get_number_no_filters(session):
        rets = session.query(CreateDataNumber) \
            .filter(CreateDataNumber.del_flag == 0) \
            .all()
        return rets

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

    @staticmethod
    def get_number_info_by_id(session, create_data_detail_id):
        try:
            ret = session.query(CreateDataNumber).filter(
                CreateDataNumber.create_data_detail_id == create_data_detail_id).first()
        except Exception as e:
            logger.warning(f'获取造数使用次数失败: id{create_data_detail_id}, {e}')
            return f'获取造数使用次数失败: id{create_data_detail_id}', False
        return ret, True

    @staticmethod
    def save_number_info(session, create_info):
        if not isinstance(create_info, dict):
            logger.error('只支持dict类型。build_info type: {}'.format(type(create_info)))
        create_detail_info = CreateDataNumber(**create_info)
        session.add(create_detail_info)
        # session.flush()
        err = session.done(close=False)
        create_info_id = create_detail_info.id
        if err:
            logger.error(f'新增失败！{err}')
            return 0
        if not create_info_id:
            logger.error(f'{create_detail_info}获取关键字id失败！')
            return 0
        # session.commit()
        return create_info_id

    @staticmethod
    def update_number_info(session, update_info, create_data_detail_id):
        update_res = session.query(CreateDataNumber).filter(
            CreateDataNumber.create_data_detail_id == create_data_detail_id).update(
            update_info)
        print(update_res, "update_res")
        err_msg = session.commit()
        # session.done()
        if err_msg:
            return '基础信息修改失败！'
        return update_res
