import logging
import math
import datetime
from unify_api.utils import time_format
from unify_api.modules.tsp_water.dao.tsp_map_dao import get_index_data_dao, \
    get_position_dao, get_tsp_id_list_dao, get_month_rank_dao
from unify_api.modules.tsp_water.dao.tsp_dao import meterdata_tsp_current
from unify_api.modules.tsp_water.components.tsp_map_cps import \
    IndexDataResp, IndexTopDataResp
from unify_api.modules.common.procedures.cids import get_cids
from unify_api.constants import Product
from unify_api.modules.tsp_water.script.stateweath import downscal
from pot_libs.common.components.responses import success_res
from unify_api.utils.response_code import RET


async def tsp_map_service(user_id):
    datas = await get_index_data_dao()
    companys = {data["cid"]: data for data in datas}
    all_cids = await get_cids(user_id, Product.YangChen.value)
    myself_company = list(set(companys.keys()) & set(all_cids))
    if not myself_company:
        return success_res(code=RET.permissions_no_enough, msg="权限不足")
    # 地图数据
    try:
        res = downscal()
        # res[(res["lon"]==113.944396) & (res["lat"]==22.512695)] linux获取不到数据
        # windows可以获取  所以采取直接用行数获取数据
        # downscal如果换了文件 这个数值需要换
        corsp_val = res.iloc[2223].values
        corsp_val_2 = round(corsp_val[2])
        corsp_val_3 = round(corsp_val[3])
    except Exception as e:
        corsp_val, corsp_val_2, corsp_val_3 = 0, "", ""
    # 经纬度
    positions = await get_position_dao(myself_company)
    company_data = []
    tsp_ids = await get_tsp_id_list_dao(myself_company)
    tsp_id_dict = {data["cid"]: data["tsp_ids"] for data in tsp_ids}
    for position in positions:
        if tsp_id_dict.get(position["cid"]).find(",") != -1:
            tsp_id_list = tsp_id_dict.get(position["cid"]).split(",")
        else:
            tsp_id_list = [tsp_id_dict.get(position["cid"])]
        tsp_data = []
        for tsp_id in tsp_id_list:
            tsp_id_data = await meterdata_tsp_current(tsp_id)
            tsp_data.append(tsp_id_data)
        max_pm25 = max([tsp["pm25"] for tsp in tsp_data])
        max_pm10 = max([tsp["pm10"] for tsp in tsp_data])
        # max_tsp = max([tsp["tsp"] for tsp in tsp_data])
        logging.info(f"cid:{position['cid']}, tsp_data:{tsp_data}")
        if not isinstance(corsp_val, int):
            pm25_deviation = round(math.fabs((corsp_val_2-max_pm25)/max_pm25), 2)
            pm10_deviation = round(math.fabs((corsp_val_3-max_pm10)/max_pm10), 2)
        else:
            pm25_deviation, pm10_deviation = "", ""
        company_dict = {
            "company_info": {
                "cid": position["cid"],
                "ext_modules": [],
                "shortname": companys.get(position["cid"]).get("shortname"),
                "fullname": companys.get(position["cid"]).get("fullname"),
                "industry": companys.get(position["cid"]).get("industry"),
                "province": companys.get(position["cid"]).get("province"),
            },
            "position": position["value"],
            "pm25": {"actual": max_pm25, "theory": corsp_val_2,
                      "deviation": pm25_deviation},
            "pm10": {"actual": max_pm10, "theory": corsp_val_3,
                     "deviation": pm10_deviation},
            # "tsp": {"actual": max_tsp, "theory": "", "deviation": ""}
        }
        company_data.append(company_dict)
    return IndexDataResp(company_data=company_data)


async def index_top_data_service(user_id):
    datas = await get_index_data_dao()
    companys = {data["cid"]: data["shortname"] for data in datas}
    all_cids = await get_cids(user_id, Product.YangChen.value)
    myself_company = list(set(companys.keys()) & set(all_cids))
    if not myself_company:
        return success_res(code=RET.permissions_no_enough, msg="权限不足")
    # 经纬度
    positions = await get_position_dao(myself_company)
    tsp_ids = await get_tsp_id_list_dao(myself_company)
    tsp_id_dict = {data["cid"]: data["tsp_ids"] for data in tsp_ids}
    pm25_unusual, pm10_unusual, tsp_unusual, project_unusual = 0, 0, 0, 0
    for position in positions:
        if tsp_id_dict.get(position["cid"]).find(",") != -1:
            tsp_id_list = tsp_id_dict.get(position["cid"]).split(",")
        else:
            tsp_id_list = [tsp_id_dict.get(position["cid"])]
        tsp_data = []
        for tsp_id in tsp_id_list:
            tsp_id_data = await meterdata_tsp_current(tsp_id)
            tsp_data.append(tsp_id_data)
        max_pm25 = max([tsp["pm25"] for tsp in tsp_data])
        max_pm10 = max([tsp["pm10"] for tsp in tsp_data])
        max_tsp = max([tsp["tsp"] for tsp in tsp_data])
        # PM2.5异常：PM2.5超过75、PM10异常（PM10超过150）、TSP异常（TSP超过300）
        old_unusual = [pm25_unusual, pm10_unusual, tsp_unusual]
        logging.info(f"index-map old_unusual:{old_unusual}")
        pm25_unusual = pm25_unusual + 1 if max_pm25 > 75 else pm25_unusual
        pm10_unusual = pm10_unusual + 1 if max_pm10 > 150 else pm10_unusual
        tsp_unusual = tsp_unusual + 1 if max_tsp > 300 else tsp_unusual
        logging.info(f"index-map max_pm25:{max_pm25}, "
                     f"max_pm10:{max_pm10}, max_tsp:{max_tsp}")
        new_unusual = [pm25_unusual, pm10_unusual, tsp_unusual]
        logging.info(f"index-map new_unusual:{new_unusual}")
        # 空气达标率（项目总数减去存在异常的项目)
        project_unusual = project_unusual + 1 if \
            set(new_unusual) - set(old_unusual) else project_unusual
    count_project = len(myself_company)
    air_standard = round((count_project - project_unusual)/count_project) * 100
    # 月度统计排名
    rank_data = await get_month_rank(myself_company)
    rank_list = []
    for rank in rank_data:
        if not rank['measures']:
            ef_rate = 0
        else:
            ef_rate = f"{int(round(rank['effect']/rank['measures'], 2)*100)}%"
        rank_list.append({
            "cid": rank["cid"],
            "company": companys.get(rank["cid"]),
            "measures": rank["measures"] or 0,
            "effective_rate": ef_rate
        })
    return IndexTopDataResp(
        rank=rank_list, count_project=count_project, pm25_unusual=pm25_unusual,
        pm10_unusual=pm10_unusual, tsp_unusual=tsp_unusual,
        air_standard=f"{air_standard}%"
    )


# 首页获取月度排名
async def get_month_rank(cids):
    this_month = datetime.date.today()
    start, end = time_format.get_month_start_end(this_month)
    rank_data = await get_month_rank_dao(cids, start, end)
    return rank_data

