from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil


async def get_annual_sunshine_hours(cid):
    sql = "SELECT pv.annual_effective_hours FROM " \
          "`algo_distributed_pv_quick_check_list` pv " \
          "LEFT JOIN company c on c.city =pv.city where c.cid=%s"
    async with MysqlUtil() as conn:
        hours = await conn.fetchone(sql, args=(cid,))
    return hours


async def get_p(cid):
    sql = "SELECT pv.hour, pv.p FROM `algo_distributed_pv` pv " \
          "LEFT JOIN company c on c.city =pv.city where c.cid=%s"
    async with MysqlUtil() as conn:
        datas = await conn.fetchall(sql, args=(cid,))
    return datas


async def get_elec_price_dao(cid):
    sql = "select * from price_policy where cid=%s " \
          "ORDER BY start_month desc limit 1"
    async with MysqlUtil() as conn:
        elec_price = await conn.fetchone(sql, args=(cid,))
    return elec_price


async def get_max_demand_by_inlid(inlids):
    sql = """SELECT '[]' as has_space,b.inlid as related_inlids FROM
    `algo_md_space_analysis_result` a
    LEFT JOIN algo_md_space_analysis_unit b on a.space_analysis_id=b.id
    WHERE b.inlid in %s ORDER BY a.month DESC LIMIT %s"""
    async with MysqlUtil() as conn:
        spaces = await conn.fetchall(sql, args=(inlids, len(inlids)))
    return spaces


async def insert_price_policy_data_dao(cid, inline_id, start_month, quarters,
                                       price_s, price_p, price_f, price_v,
                                       price_md, price_tc, effect_date):
    sql = """INSERT INTO `price_policy` (`cid`, `inline_vc`, `start_month`, 
    `time_range`,`quarters`,`price_p`,`price_s`,price_f, `price_v`, `price_md`, 
    price_tc, `price_ttl_addition`, `price_type`, effect_date) VALUES ( %s, %s, 
            %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s); """
    async with MysqlUtil() as conn:
        await conn.execute(sql, args=(cid, inline_id, start_month, "1-12",
                                      quarters, price_p, price_s, price_f,
                                      price_v, price_md, price_tc, None,
                                      "工商业", effect_date))


async def inset_algorithm_power_factor_dao(inline_id, start_time, std_cos):
    sql = """INSERT INTO `algo_power_factor` (`inlid`, `start_time`,
    `valid`, `std_cos`) VALUES ( %s, %s, %s, %s); """
    async with MysqlUtil() as conn:
        await conn.execute(sql, args=(inline_id, start_time, 1, std_cos))
        log.info(sql % (inline_id, start_time, 1, std_cos))


async def get_algorithm_power_factor_dao(cid):
    sql = "select a.std_cos from algo_power_factor a " \
          "LEFT JOIN inline_zdu line on line.inlid =a.inlid " \
          "WHERE line.cid = %s ORDER BY a.start_time desc limit 1"
    async with MysqlUtil() as conn:
        datas = await conn.fetchone(sql, args=(cid,))
    return datas

