from common.utils.exceptions import ValidationError
from common.utils.models import BaseConnection
from .models import ElectricalInfromation

base_db = BaseConnection()


class ElectricalInfromationQuerySet(object):
    @property
    def get_all_electrical_info(self):
        return ElectricalInfromation.objects.filter(
            deleted=False).order_by("id")


class ElectricalInfromationRepo(object):
    def get_electrical_info(self, pk):
        queryset = ElectricalInfromation.objects.filter(deleted=False, id=pk)
        if not queryset.exists():
            raise ValidationError("没有找到该id")
        return queryset.first()

    def get_electrical_infos(self, pks):
        queryset = ElectricalInfromation.objects.filter(deleted=False,
                                                        id__in=pks)
        if len(pks) != len(queryset):
            raise ValidationError('id数量有误')
        return queryset.all()

    def get_electrical_info_sql(self, enterprise_ids, **kwargs):
        page = kwargs.get("page")
        page_size = kwargs.get("page_size")
        id = kwargs.get("id")
        transformer = kwargs.get("transformer", 0)
        if isinstance(transformer, list):
            transformer = transformer[0]
        where = ["b.service_enterprise_id in (%s)" % ",".join(enterprise_ids)]
        where.extend(base_db.filter(kwargs.get("station_id"), value='a.powerstation_id={}'))
        where.extend(base_db.filter(id, value='a.id={}'))
        where.extend(base_db.filter(kwargs.get("ele_user"),
                                    value='a.electricity_user_id={}'))
        limit = base_db.paginator(page, page_size)
        _sql = """
            select
                %s
            from electrical_info a
            left join power_station c on a.powerstation_id=c.id
            left join customer b
            on c.customer_id=b.id
        """
        count_select = ' COUNT(a.id) as `count` '
        count_sql, _ = base_db.sql_splice(_sql,
                                          count_select,
                                          where=where)
        select = """
            a.id,
            a.power_number,
            a.meter_number,
            a.powerstation_id powerstation,
            a.incoming_line_name,
            a.comment,
            a.magnification,
            a.transformer_capacity,
            a.real_capacity,
            a.voltage_level,
            a.ep_factor
        """
        sql, count = base_db.sql_splice(_sql,
                                        select,
                                        where=where,
                                        count_sql=count_sql,
                                        limit=limit,
                                        limit_idx="a.id")
        df = base_db.query_df(sql)
        rst = df.to_dict(orient="records")
        if transformer and id:
            if isinstance(id, list):
                id = id[0]
            trans_sql = """
            select
            a.id,
            a.name,
            b.capacity,
            b.real_capacity,
            b.comments
            from equipments a
            left join equipment_data b
            on a.equipment_data_id=b.id
            where b.modular=1 and a.electrical_info_id=%s
            """ % id
            trans_rst = base_db.query(trans_sql)
            rst[0]["transformer"] = trans_rst
            return rst, count
        return rst, count


electrical_info_queryset = ElectricalInfromationQuerySet()
electrical_info_repo = ElectricalInfromationRepo()
