from common.utils.models import BaseConnection, PowerOAConnection

from console.electricity_bill.models import TariffType


def create_ele_price():
    oa_conn = PowerOAConnection()
    sql = """
    select * from io_price
    """
    data = oa_conn.query(sql)
    for item in data:
        TariffType.objects.create(
            name=item.get("name"),
            base_prise=item.get("basic_price"),
            tip_prise=item.get("tip_price"),
            peak_prise=item.get("peak_price"),
            flat_prise=item.get("usual_price"),
            valley_prise=item.get("valley_price"),
            is_summer=item.get("is_summer"),
            voltage_level=item.get("voltage_level"),
            enterprise_id=item.get("oa_org_id")
            if item.get("oa_org_id") else None,
        )


def get_ele_bill(year_month=None):
    conn = BaseConnection()
    sql = """
    SELECT
     a.*,b.power_number,b.magnification,
     b.transformer_capacity,b.real_capacity,d.name
    from electricity_bill a LEFT JOIN electrical_info b on a.electrical_id=b.id
    LEFT JOIN electricity_user c on b.electricity_user_id=c.id
    LEFT JOIN customer d on c.customer_id=d.id
    """
    if year_month:
        sql += " where year_month={}".format(year_month)
    data = conn.query(sql)
    return data
