from common.utils.exceptions import ValidationError
from common.utils.models import (BaseConnection)

from .models import PowerStation, Outline, Circuit

base_db = BaseConnection()


class PowerStationQuerySet(object):
    @property
    def get_all_power_station(self):
        return PowerStation.objects.filter(deleted=False).prefetch_related(
            "electricity_user", "customer", "electricity_user__customer"
        ).order_by("-id")


class PowerStationRepo(object):
    def get_powerstation(self, pk):
        return PowerStation.objects.filter(deleted=False, id=pk).first()

    def get_power_station_circuit(self, power_station_id, circuit_id=None):
        circuit = Circuit.objects.filter(power_station_id=power_station_id,
                                         deleted=False)
        if circuit_id:
            circuit = circuit.filter(id=circuit_id)
        return circuit

    def get_monitor_points(self, station_id):
        _sql = """
        SELECT
            a.id,
            a.name,
            b.imei
        FROM monitor_points a
        LEFT JOIN monitor_device b
        on a.id=b.monitor_point_id
        WHERE a.station_id=%s
        """ % station_id
        return base_db.query(_sql)

class OutlineQuerySet(object):
    @property
    def get_outline(self):
        return Outline.objects.filter(deleted=False).order_by("-id")


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

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


powerstation_queryset = PowerStationQuerySet()
powerstation_repo = PowerStationRepo()
outline_queryset = OutlineQuerySet()
outline_repo = OutlineRepo()
