import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px  
from behavior.analyst import Analyst
from utils.directoryUtil import DirectoryUtil as dir
from algorithmContract.confBusiness import *
from algorithmContract.contract import Contract
from windrose import WindroseAxes
import matplotlib as mpl

class CabinVibrateAnalyst(Analyst):
    '''
    风电机组机舱振动分析
    '''
    def typeAnalyst(self):
        return "cabin_vibrate"
    
    def turbinesAnalysis(self, dataFrameMerge, outputAnalysisDir, conf: Contract):
        self.CabinVibrateAnalysis(dataFrameMerge, outputAnalysisDir, conf)
    
    def CabinVibrateAnalysis(self, dataFrameMerge: pd.DataFrame, outputAnalysisDir, conf: Contract):
        # 检查所需列是否存在
        required_columns = {Field_WindDirection, Field_WindSpeed, Field_NacLrVib, Field_NacFbVib}
        # Cabin_Vibrate_X为左右振动 Cabin_Vibrate_Y为前后振动

        if not required_columns.issubset(dataFrameMerge.columns):
            raise ValueError(f"DataFrame缺少必要的列。需要的列有: {required_columns}")
        
        dataFrameMerge = dataFrameMerge.dropna(axis=0, how='any')
        
        # 按设备名分组数据
        grouped = dataFrameMerge.groupby(Field_NameOfTurbine)

        for name, group in grouped:
            # 风向- 左右振动 - 风速
            fig = plt.figure(figsize=(6,6))
            pointsize = 6 # 散点的大小
            ax = WindroseAxes.from_ax()
            ax.set_theta_zero_location("N")
            ax.set_theta_direction('clockwise')
            ax.set_xticks([(i/8)*np.pi for i in range(16)])
            ax.set_xticklabels(['N', 'NNE', 'NE', 'ENE', 'E','ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'])
            #ax.set_rlim(0, 0.6, 0.1, auto=False)
            # 设定极轴的范围，即设定图片显示振动大小的范围
            ax.set_rlabel_position(34)
            # 将显示极轴刻度的位置设在34°方向上，即位于NNE与NE的中间
            plt.scatter(np.radians(group[Field_WindDirection]), group[Field_NacFbVib],
                        c=group[Field_WindSpeed], cmap='viridis_r', alpha=1, s=pointsize)
            plt.title('WindDirecton-Cabin_VibrationX-Windspeed')
            locator = mpl.ticker.MultipleLocator(1)
            # 设置颜色条上的风速间隔为1
            cb = plt.colorbar(ticks=locator, pad=0.05, shrink=0.65) 
            # 颜色条与图像保持一定距离，防止重叠现象
            cb.ax.tick_params()
            cb.ax.set_title('Wind Speedd(m/s)')
            # 保存图像
            plt.savefig(os.path.join(outputAnalysisDir, "{}Cabin_Vibrate_X.png".format(name)), bbox_inches='tight', dpi=120)
            
            # 风向- 前后振动 - 风速
            fig = plt.figure(figsize=(6,6))
            pointsize = 6 # 散点的大小
            ax = WindroseAxes.from_ax()
            ax.set_theta_zero_location("N")
            ax.set_theta_direction('clockwise')
            ax.set_xticks([(i/8)*np.pi for i in range(16)])
            ax.set_xticklabels(['N', 'NNE', 'NE', 'ENE', 'E','ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'])
            #ax.set_rlim(0, 0.6, 0.1, auto=False)
            # 设定极轴的范围，即设定图片显示振动大小的范围
            ax.set_rlabel_position(34)
            # 将显示极轴刻度的位置设在34°方向上，即位于NNE与NE的中间
            plt.scatter(np.radians(group[Field_WindDirection]), group[Field_NacFbVib],
                        c=group[Field_WindSpeed], cmap='viridis_r', alpha=1, s=pointsize)
            plt.title('WindDirecton-Cabin_VibrationX-Windspeed')
            locator = mpl.ticker.MultipleLocator(1)
            # 设置颜色条上的风速间隔为1
            cb = plt.colorbar(ticks=locator, pad=0.05, shrink=0.65) 
            # 颜色条与图像保持一定距离，防止重叠现象
            cb.ax.tick_params()
            cb.ax.set_title('Wind Speedd(m/s)')
            # 保存图像
            plt.savefig(os.path.join(outputAnalysisDir, "{}Cabin_Vibrate_Y.png".format(name)), bbox_inches='tight', dpi=120) 


