//
//  TestViewController.m
//  HYTTSDemo
//
//  Created by apple on 2023/11/20.
//

#import "TestViewController.h"
#import <TTSSDK/TTSSDK.h>
#import "HCToast.h"
#import <AVFoundation/AVFoundation.h>
//#import "OnlinePcmToMp3.h"
#import "AFNetworking.h"
#import "YYModel.h"
#import "LanguageModel.h"
//#import "EmotionModel.h"


@interface TestViewController ()<TTSProtocl,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) TTSManger *manger;
@property(nonatomic, strong) TTSParams *params;
@property (strong, nonatomic) IBOutlet UIButton *langTypeBtn;

@property (strong, nonatomic) IBOutlet UIButton *voiceBtn;

@property (strong, nonatomic) IBOutlet UIButton *emotionBtn;


@property (strong, nonatomic) IBOutlet UITextView *contentTextView;
@property (strong, nonatomic) IBOutlet UIButton *beginBtn;
@property (strong, nonatomic) IBOutlet UIButton *endBtn;

@property (strong, nonatomic) IBOutlet UIButton *onlineBtn;
@property (strong, nonatomic) IBOutlet UIButton *offlineBtn;

@property (strong, nonatomic) IBOutlet UILabel *machineCode;
@property (strong, nonatomic) IBOutlet UIButton *networkActivationBtn;
@property (strong, nonatomic) IBOutlet UILabel *unNetworkLable;

@property (strong, nonatomic) IBOutlet UILabel *netWorkLable;
@property (strong, nonatomic) IBOutlet UIButton *unNetworkActivationBtn;
@property (strong, nonatomic) IBOutlet UITextField *activationTextField;

@property (strong, nonatomic) IBOutlet UITextField *appidTextFexfield;
@property (strong, nonatomic) IBOutlet UITextField *appsecetTextField;
@property (strong, nonatomic) IBOutlet UIButton *initsdkBtn;

@property (strong, nonatomic) IBOutlet UIButton *downLoadBtn;

@property (nonatomic,strong)UITableView *listView;

//@property(nonatomic,strong)NSArray *titleCellArray;
//@property(nonatomic,strong)NSArray *langTypeArray;
//
//@property(nonatomic,strong)NSArray *voicetitleCellArray;
//@property(nonatomic,strong)NSArray *voiceTypeArray;

@property(nonatomic,strong)NSDictionary *voiceDic;


@property (nonatomic,assign) BOOL islangType;

@property (nonatomic,copy) NSArray *textArray;

@property (nonatomic,strong) NSDictionary *langtextArray;

@property (nonatomic, strong) NSMutableData *mp3da;

@property (strong, nonatomic) IBOutlet UIButton *releaseBtn;
@property (strong, nonatomic) IBOutlet UIButton *debugBtn;

@property (strong, nonatomic) IBOutlet UILabel *releaseLabel;
@property (strong, nonatomic) IBOutlet UILabel *debugLable;

@property(nonatomic,copy)NSArray *onlineReleaseTypeList;
@property(nonatomic,copy)NSArray *onlineDebugTypeList;
@property(nonatomic,assign)NSInteger onlineIndex;
@property(nonatomic,assign)NSInteger onlineVoiceIndex;

@property(nonatomic,strong)NSMutableArray *emotionArray;

@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    NSLog(@"currentLanguage: %@", currentLanguage);
    
    self.releaseBtn.selected = YES;
    [self gerLanguage];
    
    self.islangType = YES;

    self.manger = [TTSManger getTTSManger];
    self.params = [[TTSManger getTTSManger] getSdkParams];
    [self.manger setTTSDelegate:self];
    self.onlineIndex = 0;
    self.onlineVoiceIndex = 0;

    [self layoutSubViewUI];

    self.appidTextFexfield.text = @"";
    self.appsecetTextField.text = @"";
    
 
    
    [self layoutBtn];

}

-(void)gerLanguage{

    NSDictionary *dic = @{@"ability_code":@"tts"};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    [manager GET:@"https://test.voice.dolphin-ai.jp/common/v1/setting/langs" parameters:dic headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"release-list--%@",responseObject);
        
        NSArray *data = [responseObject objectForKey:@"data"];
        NSString *status = [responseObject objectForKey:@"status"];
        if([status isEqualToString:@"000000"]){
            
            self.onlineReleaseTypeList = [NSArray yy_modelArrayWithClass:[LanguageModel class] json:data];
         
            LanguageModel *model = self.onlineReleaseTypeList[0];
            self.params.langType = model.code;
            [self.langTypeBtn setTitle: model.name forState:UIControlStateNormal];
            if ([self.params.langType isEqualToString:@"en-US"]) {
              self.contentTextView.text =  @"Life was like a box of chocolates. You never know what you're gonna get.";
            }else if([self.params.langType isEqualToString:@"zh-cmn-Hans-CN"]){
                self.contentTextView.text =  @"今天天气晴朗，风和日丽，可以出门走走。";
            }else if([self.params.langType isEqualToString:@"ja-JP"]){
                self.contentTextView.text =  @"お会いできて嬉しいです！最近何をしていますか？";
            }
            [self changeVoice];
        }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

    
    
}

-(void)changeVoice{
    
    NSDictionary *dic = @{@"ability_code":@"tts",@"lang_code":self.params.langType};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    [manager GET:@"https://test.voice.dolphin-ai.jp/common/v1/setting/fields" parameters:dic headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"voice-list--%@",responseObject);
        
        NSDictionary *data = [responseObject objectForKey:@"data"];
        NSString *status = [responseObject objectForKey:@"status"];
        if([status isEqualToString:@"000000"]){
            
            int currentIdex = 0;
            for (int i=0; i<self.onlineReleaseTypeList.count-1 ;i++ ) {
                LanguageModel *model = self.onlineReleaseTypeList[i];

                if ([self.params.langType isEqualToString:model.code]) {
                    currentIdex = i;
                }
            }
            
            LanguageModel *voiceList = self.onlineReleaseTypeList[currentIdex];
            voiceList.voice_list = [NSArray yy_modelArrayWithClass:[VoiceList class] json:data];
            
            //默认第一个
            VoiceList *voiceModel = voiceList.voice_list[0];
            self.params.voice = voiceModel.code;
            [self.voiceBtn setTitle: voiceModel.name forState:UIControlStateNormal];
            
            [self layoutBtn];
            [self getEmotion];
        }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
    
}

-(void)getEmotion{


    NSDictionary *dic = @{@"ability_code":@"tts",@"voice":self.params.voice};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.params.emotion = @"";
    [self.emotionBtn setTitle: @"emotion" forState:UIControlStateNormal];
    [manager GET:@"https://test.voice.dolphin-ai.jp/common/v1/setting/emotion" parameters:dic headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"voice-list--%@",responseObject);
        
        NSDictionary *data = [responseObject objectForKey:@"data"];
        NSString *status = [responseObject objectForKey:@"status"];
        if([status isEqualToString:@"000000"]){
            
           
            if (  [[data objectForKey:@"emotion"] isKindOfClass:[NSArray class]]) {
                NSArray *emotionArray = [data objectForKey:@"emotion"];

                self.emotionArray = [NSMutableArray arrayWithArray:emotionArray];
                
                [self layoutBtn];
                
            }else{
                self.emotionArray = [[NSMutableArray alloc] init];
                self.params.emotion = @"";
                return;
            }
           
        }else{
            self.emotionArray = [[NSMutableArray alloc] init];
            self.params.emotion = @"";

        }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
 
    
    
}


-(void)getTextArray{
    NSBundle *modelBundle = [NSBundle bundleForClass:[self class]];
    NSString *filePath = [modelBundle pathForResource:@"ttsText" ofType:@"txt"];
    NSError *error;
    NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

    if (error) {
        NSLog(@"Error reading file: %@", error.localizedDescription);
    } else {
        
        NSArray *lines = [fileContent componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

    }

}

- (IBAction)releaseAction:(UIButton *)sender {
    
    self.releaseBtn.selected = YES;
    self.debugBtn.selected = NO;
    
    [[TTSManger shareInstance] setSdkParams:self.params];
    [[TTSManger shareInstance] initWithWithAppid:@"" WithAppSecret:@"" WithinitBlock:^(NSString * _Nonnull ErrorMessage) {
        if (ErrorMessage == nil) {
            NSLog(@"init success");
            [[HCToast shareInstance] showToast:@"init success"];
        }else{
            [[HCToast shareInstance] showToast:ErrorMessage];
        }
    }];
    
}
- (IBAction)debugAction:(UIButton *)sender {
    self.releaseBtn.selected = NO;
    self.debugBtn.selected = YES;
    
    
    self.onlineIndex = 0;
    self.onlineVoiceIndex = 0;
    [self changeVoice];
    

    self.params.isProductionEnvironment = @"NO";
    [[TTSManger shareInstance] setSdkParams:self.params];
    [[TTSManger shareInstance] initWithWithAppid:@"14b36fe6-5924-42d1-bc15-8c4780eda28c" WithAppSecret:@"Zxq86PtWdZ" WithinitBlock:^(NSString * _Nonnull ErrorMessage) {
        if (ErrorMessage == nil) {
            NSLog(@"init success");
            [[HCToast shareInstance] showToast:@"init success"];
        }else{
            [[HCToast shareInstance] showToast:ErrorMessage];
        }
    }];
    
}

- (IBAction)langTypeAction:(UIButton *)sender {
    
    [self.listView removeFromSuperview];
    self.listView = nil;
    
    self.voiceBtn.selected = NO;
    self.emotionBtn.selected = NO;
    if (self.langTypeBtn.selected == YES) {
        self.langTypeBtn.selected = NO;
        return;
    }
    self.langTypeBtn.selected = YES;
    
    self.islangType = YES;
    
    UIWindow *widow = [[[UIApplication sharedApplication] delegate] window];
    
    CGRect rect = [sender convertRect:self.langTypeBtn.bounds toView:widow];
    
    self.listView.frame = CGRectMake(rect.origin.x, rect.origin.y + 50, 150, 350);
    
    [self.view addSubview:self.listView];
}


- (IBAction)changeVoiceAction:(UIButton *)sender {
    
    [self.listView removeFromSuperview];
    self.listView = nil;
    self.langTypeBtn.selected = NO;
    self.emotionBtn.selected = NO;
    self.islangType = NO;
    if (self.voiceBtn.selected == YES) {
        self.voiceBtn.selected = NO;
        return;
    }
    
    self.voiceBtn.selected = YES;
    
    UIWindow *widow = [[[UIApplication sharedApplication] delegate] window];
    
    CGRect rect = [sender convertRect:self.voiceBtn.bounds toView:widow];
    
    self.listView.frame = CGRectMake(rect.origin.x, rect.origin.y + 50, 200, 350);
    
    [self.view addSubview:self.listView];
    
}

- (IBAction)emotionAction:(UIButton *)sender {
    
    [self.listView removeFromSuperview];
    self.listView = nil;
    self.langTypeBtn.selected = NO;
    self.voiceBtn.selected = NO;
    self.islangType = NO;
    if (self.emotionBtn.selected == YES) {
        self.emotionBtn.selected = NO;
        return;
    }
    
    self.emotionBtn.selected = YES;
    
    UIWindow *widow = [[[UIApplication sharedApplication] delegate] window];
    
    CGRect rect = [sender convertRect:self.emotionBtn.bounds toView:widow];
    
    self.listView.frame = CGRectMake(rect.origin.x, rect.origin.y + 50, 200, 350);
    
    [self.view addSubview:self.listView];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    
}


- (IBAction)initOfflineModel:(UIButton *)sender {
    
    TTSParams *params = [[TTSParams alloc] init];
    params.text = @"";
    params.langType = @"zh-cmn-Hans-CN";
    params.format = @"mp3";
    params.voice = @"Yaqing";
    params.volume = 1;
    params.speech_rate = 1.0;// [0.2,3]
    params.pitch_rate = 1.0;// [0.1, 3]
    params.sample_rate = 16000;
    params.online = YES;
    params.isProductionEnvironment = @"NO";

    [[TTSManger shareInstance] setSdkParams:params];

//
    [[TTSManger shareInstance] initWithWithAppid:@"288eb6d0-e86f-4cd4-a632-e012c0f07439" WithAppSecret:@"UXlKAwa48t" WithinitBlock:^(NSString * _Nonnull ErrorMessage) {
        if (ErrorMessage == nil) {
            NSLog(@"init success");
            [[HCToast shareInstance] showToast:@"init success"];
        }else{
            [[HCToast shareInstance] showToast:ErrorMessage];
        }
    }];
}

- (IBAction)beginAction:(UIButton *)sender {
    self.mp3da = [[NSMutableData alloc] init];
    [self.view endEditing:YES];
    self.params = [[TTSManger getTTSManger] getSdkParams];
    self.params.text = self.contentTextView.text;
    
    [[TTSManger shareInstance] setSdkParams:self.params];
    [[TTSManger getTTSManger] onStart];
}


- (IBAction)endAction:(UIButton *)sender {
    [[TTSManger getTTSManger] onStop];
    
}


#pragma mark - TTSProtocl
- (void)onSuccess{
    [[HCToast shareInstance] showToast:@"init success"];
}



/*
 *Warning
 */
-(void)onWarningWithCode:(NSString *)cede WithMessage:(NSString *)message WithTaskId:(NSString *)taskid{
    
    [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"Warning code:%@--Warning message：%@",cede,message]];

}


/*
 *Error
 */
-(void)onErrorWithCode:(NSString *)code WithMessage:(NSString *)message WithTaskId:(NSString *)taskid{
    
    [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"Error code:%@--error：%@",code,message]];


}



/*
 *audioData
 */
-(void)onAudio:(NSData *)audioData{
    
    
    [self.mp3da appendData:audioData];
    NSLog(@"audio-%lu-----%lu",(unsigned long)audioData.length,(unsigned long)self.mp3da.length);
}
-(void) onPlayerEnd{
//    OnlinePcmToMp3*mp3Manger = [[OnlinePcmToMp3 alloc] init];
//    [mp3Manger initLame];
//    NSData *mp3Data = [mp3Manger transMP3WithPCMData:self.mp3da isLast:YES];
//
//    [self writeFileName:@"pcmData" Type:@"wav" Data:mp3Data];
}

-(void)writeFileName:(NSString *)fileName Type:(NSString *)type Data:(NSData *)data{
    
    
    
//Get sandbox path 
    NSString *filePathStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// Write the file you want to write to
    NSString *fullPathStr = [filePathStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",fileName,type]];
 
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fullPathStr]) {
//create directory
        [fileManager createDirectoryAtPath:filePathStr withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        //Delete the original file
        [[NSFileManager defaultManager] removeItemAtPath:filePathStr error:nil];
        [fileManager createDirectoryAtPath:filePathStr withIntermediateDirectories:YES attributes:nil error:nil];//recreate

    }
    
    
    if ([fileManager fileExistsAtPath:fullPathStr]) {//在已存在的文件后面追加内容
        
        
        
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:fullPathStr];
        [fileHandle seekToEndOfFile];
        [fileHandle writeData:data];
        [fileHandle closeFile];
    }
    else {//Create and write content when no file exists
        
        [data writeToFile:fullPathStr atomically:YES];
    }
}
-(void)layoutSubViewUI{
    
    UIImage *image = [UIImage imageNamed:@"Arrow"];
    [self.langTypeBtn setImage:image forState:UIControlStateNormal];


    CGSize imageSize = CGSizeMake(15, 10); // resize
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.langTypeBtn setImage:resizedImage forState:UIControlStateNormal];

    self.langTypeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -self.langTypeBtn.imageView.image.size.width, 0, self.langTypeBtn.imageView.image.size.width);
    self.langTypeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.langTypeBtn.titleLabel.bounds.size.width, 0, -self.langTypeBtn.titleLabel.bounds.size.width-30);
    

    [self.voiceBtn setImage:resizedImage forState:UIControlStateNormal];

    self.voiceBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -self.voiceBtn.imageView.image.size.width, 0, self.voiceBtn.imageView.image.size.width);
    self.voiceBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.voiceBtn.titleLabel.bounds.size.width, 0, -self.voiceBtn.titleLabel.bounds.size.width -30);
    
    
    [self.onlineBtn setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
    [self.onlineBtn setImage:[UIImage imageNamed:@"nuselect"] forState:UIControlStateNormal];
    self.onlineBtn.selected = YES;
    
    [self.offlineBtn setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
    [self.offlineBtn setImage:[UIImage imageNamed:@"nuselect"] forState:UIControlStateNormal];
    self.offlineBtn.selected = NO;
    
    
    [self.networkActivationBtn setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
    [self.networkActivationBtn setImage:[UIImage imageNamed:@"nuselect"] forState:UIControlStateNormal];
    self.networkActivationBtn.selected = YES;
    
    [self.unNetworkActivationBtn setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
    [self.unNetworkActivationBtn setImage:[UIImage imageNamed:@"nuselect"] forState:UIControlStateNormal];
    self.unNetworkActivationBtn.selected = NO;
    
    
    [self.releaseBtn setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
    [self.releaseBtn setImage:[UIImage imageNamed:@"nuselect"] forState:UIControlStateNormal];
    self.releaseBtn.selected = YES;
    
    [self.debugBtn setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
    [self.debugBtn setImage:[UIImage imageNamed:@"nuselect"] forState:UIControlStateNormal];
    self.debugBtn.selected = NO;
    
    
    self.beginBtn.layer.masksToBounds = YES;
    self.beginBtn.layer.borderWidth = 1;
    self.beginBtn.layer.borderColor = [UIColor cyanColor].CGColor;
    self.beginBtn.layer.cornerRadius =5;
    
    self.endBtn.layer.masksToBounds = YES;
    self.endBtn.layer.borderWidth = 1;
    self.endBtn.layer.borderColor = [UIColor cyanColor].CGColor;
    self.endBtn.layer.cornerRadius =5;
    
    self.initsdkBtn.layer.masksToBounds = YES;
    self.initsdkBtn.layer.borderWidth = 1;
    self.initsdkBtn.layer.borderColor = [UIColor cyanColor].CGColor;
    self.initsdkBtn.layer.cornerRadius =5;
    
    self.downLoadBtn.layer.masksToBounds = YES;
    self.downLoadBtn.layer.borderWidth = 1;
    self.downLoadBtn.layer.borderColor = [UIColor cyanColor].CGColor;
    self.downLoadBtn.layer.cornerRadius =5;
    
    
    self.releaseLabel.layer.masksToBounds = YES;
    self.releaseLabel.layer.borderWidth = 1;
    self.releaseLabel.layer.borderColor = [UIColor cyanColor].CGColor;
    self.releaseLabel.layer.cornerRadius =5;
    
    self.debugLable.layer.masksToBounds = YES;
    self.debugLable.layer.borderWidth = 1;
    self.debugLable.layer.borderColor = [UIColor cyanColor].CGColor;
    self.debugLable.layer.cornerRadius =5;
    
    self.contentTextView.layer.masksToBounds = YES;
    self.contentTextView.layer.borderWidth = 1;
    self.contentTextView.layer.borderColor = [UIColor grayColor].CGColor;
    self.contentTextView.layer.cornerRadius =5;
    
}
#pragma UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

    if (self.islangType) {
        return self.onlineReleaseTypeList.count;

    }else{
        if (self.voiceBtn.selected) {
            int index = [self getLangTypeIndex];
            LanguageModel *model = self.onlineReleaseTypeList[index];
            return model.voice_list.count;
        }else{
            
            return self.emotionArray.count;
        }
       
    }
}

-(int )getLangTypeIndex{
    int currentIdex = 0;
    for (int i=0; i<self.onlineReleaseTypeList.count-1 ;i++ ) {
        LanguageModel *model = self.onlineReleaseTypeList[i];

        if ([self.params.langType isEqualToString:model.code]) {
            currentIdex = i;
        }
    }
    return currentIdex;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
    }
    NSString *titleText;

    if (self.islangType) {
        LanguageModel *mode = self.onlineReleaseTypeList[indexPath.row];
        titleText = mode.name;
    }else{
        if (self.voiceBtn.selected) {
            int  index = [self getLangTypeIndex];
            LanguageModel *currentModel = self.onlineReleaseTypeList[index];
            VoiceList *voiceModel = currentModel.voice_list[indexPath.row];
            titleText = voiceModel.name;
        }else{
            
//            EmotionModel *emotionModel = self.emotionArray[indexPath.row];
            titleText = self.emotionArray[indexPath.row];

        }
        
    }
  
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = titleText;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.params = [self.manger getSdkParams];
    
    if (self.islangType) {
        LanguageModel *languageModel = self.onlineReleaseTypeList[indexPath.row];
        self.params.langType = languageModel.code;
        [self.langTypeBtn setTitle: languageModel.name forState:UIControlStateNormal];
        [self changeVoice];
        
        if ([self.params.langType isEqualToString:@"en-US"]) {
          self.contentTextView.text =  @"Life was like a box of chocolates. You never know what you're gonna get.";
        }else if([self.params.langType isEqualToString:@"zh-cmn-Hans-CN"]){
            self.contentTextView.text =  @"今天天气晴朗，风和日丽，可以出门走走。";
        }else if([self.params.langType isEqualToString:@"ja-JP"]){
            self.contentTextView.text =  @"お会いできて嬉しいです！最近何をしていますか？";
        }
        
    }else{
        
        if (self.voiceBtn.selected) {
            int  index = [self getLangTypeIndex];
            LanguageModel *currentModel = self.onlineReleaseTypeList[index];
            VoiceList *voiceModel = currentModel.voice_list[indexPath.row];
            self.params.voice = voiceModel.code;
            [self.voiceBtn setTitle: voiceModel.name forState:UIControlStateNormal];
            [self getEmotion];
        }else{
            [self.emotionBtn setTitle: self.emotionArray[indexPath.row] forState:UIControlStateNormal];
            self.params.emotion = self.emotionArray[indexPath.row];

        }
        

    }

    [self layoutBtn];
    
    [self.listView removeFromSuperview];
    self.listView = nil;
}

-(UITableView *)listView{
    if (_listView == nil) {
        _listView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 150, 350) style:UITableViewStylePlain];
        _listView.estimatedRowHeight = 0;
        _listView.estimatedSectionHeaderHeight = 0;
        _listView.estimatedSectionFooterHeight = 0;
        _listView.delegate = self;
        _listView.dataSource = self;
        _listView.tableFooterView = [[UIView alloc]init];
        
        
    }
    return _listView;
}


-(void)layoutBtn{
    UIImage *image = [UIImage imageNamed:@"Arrow"];
    [self.langTypeBtn setImage:image forState:UIControlStateNormal];
    // resize
    CGSize imageSize = CGSizeMake(15, 10);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.langTypeBtn setImage:resizedImage forState:UIControlStateNormal];

    self.langTypeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -self.langTypeBtn.imageView.image.size.width, 0, self.langTypeBtn.imageView.image.size.width);
    self.langTypeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.langTypeBtn.titleLabel.bounds.size.width, 0, -self.langTypeBtn.titleLabel.bounds.size.width-30);
    

    [self.voiceBtn setImage:resizedImage forState:UIControlStateNormal];

    self.voiceBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -self.voiceBtn.imageView.image.size.width, 0, self.voiceBtn.imageView.image.size.width);
    self.voiceBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.voiceBtn.titleLabel.bounds.size.width, 0, -self.voiceBtn.titleLabel.bounds.size.width -30);
    
    [self.emotionBtn setImage:resizedImage forState:UIControlStateNormal];

    self.emotionBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -self.emotionBtn.imageView.image.size.width, 0, self.emotionBtn.imageView.image.size.width);
    self.emotionBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.emotionBtn.titleLabel.bounds.size.width, 0, -self.emotionBtn.titleLabel.bounds.size.width -30);
}

-(void)hiddenOfflineBtn{
    
    self.networkActivationBtn.hidden = YES;
    self.unNetworkLable.hidden = YES;
    self.netWorkLable.hidden = YES;
    self.unNetworkActivationBtn.hidden = YES;
    self.activationTextField.hidden = YES;
    [self.listView reloadData];
}

-(void)showOfflineBtn{
    
    self.networkActivationBtn.hidden = NO;
    self.unNetworkLable.hidden = NO;
    self.netWorkLable.hidden = NO;
    self.unNetworkActivationBtn.hidden = NO;
    self.activationTextField.hidden = NO;
    if (self.unNetworkActivationBtn.selected) {
        self.activationTextField.hidden = NO;
    }else{
        self.activationTextField.hidden = YES;
    }
    [self.listView reloadData];
}


@end
