#!/usr/bin/env python
# -*- coding: utf-8 -*-
##################################################################
#
# Copyright (c) 2023 CICV, Inc. All Rights Reserved
#
##################################################################
"""
@Authors:           zhanghaiwen, yangzihao
@Data:              2024/02/21
@Last Modified:     2024/02/21
@Summary:           The template of custom indicator.
"""

"""
设计思路：

"""

import math
import pandas as pd
import numpy as np
from common import zip_time_pairs, continuous_group, get_status_active_data
from log import logger

"""import functions"""


# custom metric codes
class CustomMetric(object):
    def __init__(self, all_data, case_name):
        self.data = all_data
        self.optimal_dict = self.data.config
        self.status_trigger_dict = self.data.status_trigger_dict
        self.case_name = case_name
        self.markline_df = pd.DataFrame(columns=['start_time', 'end_time', 'start_frame', 'end_frame', 'type'])
        self.graph_list = []

        self.df = pd.DataFrame()
        self.ego_df = pd.DataFrame()
        self.df_ica = pd.DataFrame()

        self.percentage_lon_acc_roc = 0

        self.result = {
            "name": "合理加减速度变化率占比",
            "value": [],
            # "weight": [],
            "tableData": {
                "avg": "",  # 平均值，或指标值
                "max": "",
                "min": ""
            },
            "reportData": {
                "name": "合理加减速度变化率占比（%）",
                # "legend": [], # 如果有多个data，则需要增加data对应的说明，如：["横向加速度", "纵向加速度"]
                "data": [],
                "markLine": [],
                "range": [],
            },
            "statusFlag": {}
        }
        self.run()
        print(f"ICA: 合理加减速度变化率占比: {self.result['value']}")

    def data_extract(self):
        self.df = self.data.object_df
        self.ego_df = self.data.ego_data

        active_time_ranges = self.status_trigger_dict['ICA']['ICA_active_time']
        self.df_ica = get_status_active_data(active_time_ranges, self.ego_df)

        # active_status_list = ["LLC_Follow_Line", "LLC_Follow_Vehicle", "Only_Longitudinal_Control"]
        # self.df_ica = self.ego_df[self.ego_df['ICA_status'].isin(active_status_list)].copy()  # 数字3对应ICA的Active
        # self.df_ica = self.df[self.df['ACC_status'] == "Shut_off"].copy()  # 数字3对应ICA的Active
        # self.df_ica = self.df[self.df['ACC_status'] == "Active"].copy()  # 数字3对应ICA的Active

        if self.df_ica.empty:
            self.result['statusFlag']['function_ICA'] = False
        else:
            self.result['statusFlag']['function_ICA'] = True

    def data_analyze(self):
        count_in_range = 0
        if self.df_ica.empty:
            percentage_in_range = 100  
    
            # 存储结果并打印  
            self.result['value'] = [100]  
            print(f"Percentage of frames with acceleration/deceleration in range: {percentage_in_range}%")
        else:
            # 指定要分析的列  
            col_list = ['simTime', 'simFrame', 'playerId', 'v', 'accel', 'lon_acc_roc']  
            # 从原始 DataFrame 中选择列并复制  
            df = self.df_ica[col_list].copy()  
        
            # 将速度从km/h转换为m/s  
            df['v_ms'] = df['v'] / 3.6  
        
            # 初始化计数器  
            
            total_frames = len(df)  
        
            # 遍历DataFrame的每一行  
            for index, row in df.iterrows():  
                v_ms = row['v_ms']  
                lon_acc_roc = row['lon_acc_roc']  
        
                # 根据车速范围设置减速度和加速度的阈值（这里假设减速度就是加速度的相反数，用于判断）  
                if v_ms > 20:  # 车速大于20m/s  
                    decel_threshold = -2.5  # 减速度不小于-2.5 m/s^2（注意是减速度，所以是负数）  
                    accel_threshold_max = 2.5  # 这里我们也需要一个加速度的最大值阈值，但原题没有给出，这里假设和减速度绝对值相同  
                elif v_ms < 5:  # 车速低于5m/s（这里已经是m/s，无需转换）  
                    decel_threshold = -5  # 减速度不小于5 m/s^2（注意是减速度，所以是负数）  
                    accel_threshold_max = 5  # 加速度不大于5 m/s^2（注意这里是正值，因为加速度是正值）  
                else:  # 车速在5到20m/s之间  
                    # 对减速度和加速度的阈值进行线性插值  
                    # 假设在5m/s时decel_threshold=-5 m/s^2, accel_threshold_max=5 m/s^2  
                    # 在20m/s时decel_threshold=-2.5 m/s^2, accel_threshold_max=2.5 m/s^2（这里假设加速度和减速度绝对值相等）  
                    decel_threshold = -5 + (5 - 2.5) * ((v_ms - 5) / (20 - 5))  # 注意这里计算出来的是减速度，所以是负数  
                    accel_threshold_max = 5 - (5 - 2.5) * ((v_ms - 5) / (20 - 5))  # 加速度的最大值  
        
                # 检查加速度是否在允许的范围内（注意这里我们假设加速度是正值，减速度是负值）  
                # 由于我们只有一个加速度值（accel），并且没有直接的减速度值，  
                # 我们只能根据加速度的值和符号来判断它是否满足减速度的要求。  
                # 如果accel是负数，并且其绝对值小于等于decel_threshold的绝对值，则满足减速度要求。  
                # 如果accel是正数，并且小于等于accel_threshold_max，则满足加速度要求。  
                if (lon_acc_roc < 0 and abs(lon_acc_roc) <= abs(decel_threshold)) or (lon_acc_roc >= 0 and lon_acc_roc <= accel_threshold_max):  
                    count_in_range += 1  
        
            # 计算百分比  
            percentage_in_range = (count_in_range / total_frames) * 100  
        
            # 存储结果并打印  
            self.result['value'] = [round(percentage_in_range, 3)]  
            print(f"Percentage of frames with acceleration/deceleration in range: {percentage_in_range}%")

    def markline_statistic(self):
        pass

    def report_data_statistic(self):
        time_list = self.ego_df['simTime'].values.tolist()
        graph_list = [x for x in self.graph_list if not np.isnan(x)]
        self.result['tableData']['avg'] = self.result['value'][0] if not self.df_ica.empty else '-'
        self.result['tableData']['max'] = '-'
        self.result['tableData']['min'] = '-'

        zip_vs_time = zip_time_pairs(time_list, self.graph_list)
        self.result['reportData']['data'] = zip_vs_time

        # self.markline_statistic()
        # markline_slices = self.markline_df.to_dict('records')
        self.result['reportData']['markLine'] = []

        self.result['reportData']['range'] = [0, 100]

    def run(self):
        # logger.info(f"Custom metric run:[{self.result['name']}].")
        logger.info(f"[case:{self.case_name}] Custom metric:[percentage_lon_acc_roc:{self.result['name']}] evaluate.")

        try:
            self.data_extract()
        except Exception as e:
            logger.error(f"[case:{self.case_name}] Custom metric:{self.result['name']} data extract ERROR!", e)

        try:
            self.data_analyze()
        except Exception as e:
            logger.error(f"[case:{self.case_name}] Custom metric:{self.result['name']} data analyze ERROR!", e)

        try:
            self.report_data_statistic()
        except Exception as e:
            logger.error(f"[case:{self.case_name}] Custom metric:{self.result['name']} report data statistic ERROR!", e)

# if __name__ == "__main__":
#     pass
