//
//  MainView.m
//  ChatAgentApp
//
//  Created by Sun,Jian(ACU-T102) on 2018/12/31.
//  Copyright © 2018年 Sun,Jian(ACU-T102). All rights reserved.
//


#import "MainView.h"
#import <sys/utsname.h>
#include "BDCloudRTCBaseDefine.pch"
#import "BaiduAgentApi.h"
#import "RTCTextField.h"

@interface MainView () <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, NoticeextFieldSaveDelegate>

@end

@implementation MainView {
    UIButton *_startCallButton;
    UIImage *_image;
    UIImageView *_logoImageView;
    UILabel *_welcomLabel;
    UILabel *_entryRoomLabel;
    UILabel *_serviceProviderLabel;
#ifndef APP_FOR_TAL
    UIPickerView *_pickerView;
#endif
    NSArray *_pickerDataEnv;
    NSArray *_pickerDataModel;
    NSArray *_pickerDataTTS;
    NSArray *_pickerDataASR;
    NSArray *_pickerDataAgentType;
    
    NSInteger _curSelectEnv;
    NSInteger _curSelectModel;
    NSInteger _curSelectTTS;
    NSInteger _curSelectASR;
    NSInteger _curlAgentType;      //数字人类型：Human agent
    
    RTCTextField *_roomText;
    RTCTextField *_aapText;
}

@synthesize delegate = _delegate;

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _logoImageView = [[UIImageView alloc] init];
        [self addSubview:_logoImageView];
        
        _welcomLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _welcomLabel.textAlignment = NSTextAlignmentCenter;
        _welcomLabel.text = @"欢迎来到百度云AI Agent";
        _welcomLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:26];
        _welcomLabel.textColor = [UIColor colorWithRed:68/255.0 green:73/255.0 blue:90/255.0 alpha:1/1.0];
        [self addSubview:_welcomLabel];
        
        
        _entryRoomLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _entryRoomLabel.textAlignment = NSTextAlignmentCenter;
        _entryRoomLabel.text = @"进入房间后开始你的旅程";
        _entryRoomLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
        _entryRoomLabel.textColor = [UIColor colorWithRed:68/255.0 green:73/255.0 blue:90/255.0 alpha:1/1.0];
        [self addSubview:_entryRoomLabel];
        
        _serviceProviderLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _serviceProviderLabel.text = @"百度云提供计算服务";
        _serviceProviderLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        _serviceProviderLabel.textColor = [UIColor colorWithRed:210/255.0 green:211/255.0 blue:219/255.0 alpha:1/1.0];
        [self addSubview:_serviceProviderLabel];
        
       
                
        _startCallButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        NSString *deviceType = [self judgeDevice];
        if ([deviceType isEqualToString:@"iPhone X"]
            || [deviceType isEqualToString:@"iPhone XR"]
            || [deviceType isEqualToString:@"iPhone XS"]
            || [deviceType isEqualToString:@"iPhone XS MAX"]) {
            _startCallButton.layer.cornerRadius = 25.0;
        } else {
            _startCallButton.layer.cornerRadius = 20.0;
        }
        _startCallButton.layer.masksToBounds = YES;
        _startCallButton.titleLabel.adjustsFontSizeToFitWidth = YES;
        [_startCallButton setTitle:@"开始通话"
                          forState:UIControlStateNormal];
        
        //        _startCallButton.titleLabel.font = controlFont;
        [_startCallButton addTarget:self
                             action:@selector(onStartCall:)
                   forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_startCallButton];
        
        
        if (@available(iOS 13.0, *)) {
            self.backgroundColor = [UIColor systemBackgroundColor];
        } else {
            self.backgroundColor = [UIColor whiteColor];
        }
#ifndef APP_FOR_TAL
        // 初始化UIPickerView
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        [self addSubview:_pickerView];
        _pickerView.translatesAutoresizingMaskIntoConstraints = NO;
        
     

            // 使用AutoLayout设置PickerView的约束
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-80-[_pickerView(450)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_pickerView)]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_pickerView(400)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_pickerView)]];
        _pickerDataEnv = @[@"外部", @"测试"];
        _pickerDataModel = @[@"默认", @"LLMRacing", @"LLM4TN", @"LLM4T", @"LLMSpeedPro", @"LLMMathGPT"];
        _pickerDataTTS = @[@"zh", @"en"];
        _pickerDataASR = @[@"DH", @"Ag"];
        _pickerDataAgentType = @[@"DH", @"Agent"];
        _curSelectEnv = 1;
        _curSelectModel = 0;
        _curSelectTTS = 0;
        _curSelectASR = 1;
        _curlAgentType = 1; //默认智能体
#else
        // 初始化数据
        _pickerDataEnv = @[@"外部环境", @"测试环境", @""];
        _pickerDataModel = @[@"默认", @"LLM4T", @"LLMSpeedPro", @"LLMMathGPT"]; //value: ”LLMMathGPT“，“LLMSpeedPro”，”LLMLite“, ”LLM4T“
        _pickerDataTTS = @[@"TTS_1", @"TTS_2", @""];
        _pickerDataASR = @[@"ASR_1", @"ASR_2", @""];
        _curSelectModel = 2;
#endif
        _roomText = [[RTCTextField alloc] initWithFrame:CGRectZero delegate:self back:@"请输入房间号:"];
        [self addSubview:_roomText];
        NSString* roomName = @"";
        if (roomName && [roomName length] > 0) {
            _roomText.roomText = roomName;
        } else {
            _roomText.roomText = @"";
        }
        
        _aapText = [[RTCTextField alloc] initWithFrame:CGRectZero delegate:self back:@"请输入APPID:"];
        [self addSubview:_aapText];
        NSString* appName = @"";
        if (appName && [appName length] > 0) {
            _aapText.roomText = appName;
        } else {
            _aapText.roomText = @"";
        }
    }
    
    return self;
}
#ifndef APP_FOR_TAL

#pragma mark - UIPickerViewDataSource
 
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 4; // 单列
}
 
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSInteger currCount = 0;
    switch (component) {
        case 0:
            currCount = _pickerDataEnv.count;
            break;
        case 1:
            currCount = _pickerDataModel.count;
            break;
        case 2:
            currCount = _pickerDataTTS.count;
            break;
        case 3:
            currCount = _pickerDataASR.count;
            break;
        default:
            break;
    }
    return currCount;
}
 
#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString* cur = @"";

    switch (component) {
        case 0:
            cur = _pickerDataEnv[row];
            break;
        case 1:
            cur = _pickerDataModel[row];
            break;
        case 2:
            cur = _pickerDataTTS[row];
            break;
        case 3:
            cur = _pickerDataASR[row];
            break;
        default:
            break;
    }
    return cur;
}

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSDictionary *attributes = @{
        NSForegroundColorAttributeName : [UIColor blueColor],
        NSFontAttributeName : [UIFont boldSystemFontOfSize:4]
    };
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"Row %ld", (long)row] attributes:attributes];

    switch (component) {
        case 0:
            attributedString = [[NSAttributedString alloc] initWithString:_pickerDataEnv[row] attributes:attributes];
            break;
        case 1:
            attributedString = [[NSAttributedString alloc] initWithString:_pickerDataModel[row] attributes:attributes];
            break;
        case 2:
            attributedString = [[NSAttributedString alloc] initWithString:_pickerDataTTS[row] attributes:attributes];
            break;
        case 3:
            attributedString = [[NSAttributedString alloc] initWithString:_pickerDataASR[row] attributes:attributes];
            break;
        default:
            break;
    }
    return attributedString;
}
 
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    // 用户选择某个选项时的响应
    switch (component) {
        case 0:
            _curSelectEnv = row;
            break;
        case 1:
            _curSelectModel = row;
            break;
        case 2:
            _curSelectTTS = row;
            break;
        case 3:
            _curSelectASR = row;
            break;
        default:
            break;
    }
    
}
#endif
- (void)layoutSubviews {
    CGRect bounds = self.bounds;
    CGSize bdsSize = bounds.size;
    CGFloat logImageViewX = bdsSize.width*523/kLayoutWidth;
    CGFloat logImageViewY = bdsSize.height*91.7/kLayoutHeight;
    CGFloat logImageViewW = bdsSize.width*196/kLayoutWidth;
    CGFloat logImageViewH = logImageViewW*222/196;
    _logoImageView.frame = CGRectMake(logImageViewX, logImageViewY, logImageViewW, logImageViewH);
    _image = [UIImage imageNamed:@"first_page_logo.png"];
    [_logoImageView setImage:_image];
    
    CGFloat welcomLabelX = bdsSize.width*120/kLayoutWidth;
    CGFloat welcomLabelY = bdsSize.height*443/kLayoutHeight;
    CGFloat welcomLabelW = bdsSize.width*960/kLayoutWidth;
    CGFloat welcomLabelH = welcomLabelW*140/912;
    _welcomLabel.frame = CGRectMake(welcomLabelX, welcomLabelY, welcomLabelW, welcomLabelH);
    
    CGFloat entryLabelX = bdsSize.width*343/kLayoutWidth;
    CGFloat entryLabelY = bdsSize.height*598/kLayoutHeight;
    CGFloat entryLabelW = bdsSize.width*556/kLayoutWidth;
    CGFloat entryLabelH = welcomLabelW*70/556;
    _entryRoomLabel.frame = CGRectMake(entryLabelX, entryLabelY, entryLabelW, entryLabelH);
    
    CGFloat appTextX = bdsSize.width * 97 / kLayoutWidth;
    CGFloat appTexMarginH = bdsSize.height * 600 * kLayoutHeightScale;
    CGFloat appTextY = CGRectGetMaxY(_entryRoomLabel.frame) + appTexMarginH;
    CGFloat appTextW = bdsSize.width * 1070/kLayoutWidth;
    CGFloat appTextH = 50;
    _aapText.frame = CGRectMake(appTextX, appTextY, appTextW, appTextH);
    
    CGFloat roomTextX = bdsSize.width*97/kLayoutWidth;
    CGFloat roomTexMarginH = bdsSize.height*10 * kLayoutHeightScale;
    CGFloat roomTextY = CGRectGetMaxY(_aapText.frame) + roomTexMarginH;
    CGFloat roomTextW = bdsSize.width*1070/kLayoutWidth;
    CGFloat roomTextH = 50;
    _roomText.frame = CGRectMake(roomTextX, roomTextY, roomTextW, roomTextH);

//
//    CGFloat _startOnlinePickerX = bdsSize.width*97/kLayoutWidth;
//    CGFloat _startOnlinePickerY = CGRectGetMaxY(_entryRoomLabel.frame) + bdsSize.height*400*kLayoutHeightScale;
//    CGFloat _startOnlinePickerW = bdsSize.width*1070/kLayoutWidth;
//    CGFloat _startOnlinePickerH = SCREEN_HEIGHT*140*kLayoutHeightScale;
//    _pickerView.frame = CGRectMake(_startOnlinePickerX,
//                                   _startOnlinePickerY,
//                                   _startOnlinePickerW,
//                                   _startOnlinePickerH);
//    
    
    CGFloat _startCallBtnX = bdsSize.width*97/kLayoutWidth;
    CGFloat _startCallBtnY = CGRectGetMaxY(_roomText.frame) + bdsSize.height*100 * kLayoutHeightScale;
    CGFloat _startCallBtnW = bdsSize.width*1070/kLayoutWidth;
    CGFloat _startCallBtnH = SCREEN_HEIGHT*140*kLayoutHeightScale;
    
    _startCallButton.frame = CGRectMake(_startCallBtnX,
                                        _startCallBtnY,
                                        _startCallBtnW,
                                        _startCallBtnH);
    [_startCallButton setBackgroundColor:[UIColor colorWithRed:77/255.0 green:102/255.0 blue:254/255.0 alpha:1/1.0]];
    
    CGFloat serviceProviderLabelX = bdsSize.width*383/kLayoutWidth;
    CGFloat serviceProviderLabelY = bdsSize.height*2070/kLayoutHeight;
    CGFloat serviceProviderLabelW = bdsSize.width*477/kLayoutWidth;
    CGFloat serviceProviderLabelH = welcomLabelW*69/477;
    _serviceProviderLabel.frame = CGRectMake(serviceProviderLabelX,
                                             serviceProviderLabelY,
                                             serviceProviderLabelW,
                                             serviceProviderLabelH);
#ifndef APP_FOR_TAL
    if (_pickerView) {
        [_pickerView selectRow:_curSelectEnv inComponent:0 animated:YES];
        [_pickerView selectRow:_curSelectTTS inComponent:1 animated:YES];
        [_pickerView selectRow:_curSelectTTS inComponent:2 animated:YES];
        [_pickerView selectRow:_curSelectASR inComponent:3 animated:YES];
    }
#endif
}


#pragma mark - Private
- (void)onStartCall:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(mainView:didCall:config:app:room:hd:)]) {
        NSString *env = (_curSelectEnv == 1 ? @"test" : @"online");
        BOOL isHD = NO;
        if (_curSelectASR == 0) {
            env = @"dh";
            isHD = YES;
        }
        NSString *model = _pickerDataModel[_curSelectModel];
        if ([model isEqualToString:@"默认"]) model = @"";
#ifndef APP_FOR_TAL
        NSString *tts = _pickerDataTTS[_curSelectTTS];
        NSString *asr = @"default";
        NSString *config =  [BaiduAgentApi configBuild:env model:model tts:tts asr:asr];
        [self.delegate mainView:self didCall:nil config:config  app:_aapText.roomText room:_roomText.roomText hd:isHD];
#else
        NSString *llm_url = @"path_of_model";
        NSString *tts_sayhi = @"welcome-welcome hello hello";
        NSString *config =  [BaiduAgentApi configBuild:env model:model llmurl:llm_url tts:tts_sayhi];
        [self.delegate mainView:self didCall:nil config:config];
#endif
   
    }
}

- (NSString *)judgeDevice {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString*phoneType = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([phoneType  isEqualToString:@"iPhone1,1"])  return @"iPhone 2G";
    
    if ([phoneType  isEqualToString:@"iPhone1,2"])  return @"iPhone 3G";
    
    if ([phoneType  isEqualToString:@"iPhone2,1"])  return @"iPhone 3GS";
    
    if ([phoneType  isEqualToString:@"iPhone3,1"])  return @"iPhone 4";
    
    if ([phoneType  isEqualToString:@"iPhone3,2"])  return @"iPhone 4";
    
    if ([phoneType  isEqualToString:@"iPhone3,3"])  return @"iPhone 4";
    
    if ([phoneType  isEqualToString:@"iPhone4,1"])  return @"iPhone 4S";
    
    if ([phoneType  isEqualToString:@"iPhone5,1"])  return @"iPhone 5";
    
    if ([phoneType  isEqualToString:@"iPhone5,2"])  return @"iPhone 5";
    
    if ([phoneType  isEqualToString:@"iPhone5,3"])  return @"iPhone 5c";
    
    if ([phoneType  isEqualToString:@"iPhone5,4"])  return @"iPhone 5c";
    
    if ([phoneType  isEqualToString:@"iPhone6,1"])  return @"iPhone 5s";
    
    if ([phoneType  isEqualToString:@"iPhone6,2"])  return @"iPhone 5s";
    
    if ([phoneType  isEqualToString:@"iPhone7,1"])  return @"iPhone 6 Plus";
    
    if ([phoneType  isEqualToString:@"iPhone7,2"])  return @"iPhone 6";
    
    if ([phoneType  isEqualToString:@"iPhone8,1"])  return @"iPhone 6s";
    
    if ([phoneType  isEqualToString:@"iPhone8,2"])  return @"iPhone 6s Plus";
    
    if ([phoneType  isEqualToString:@"iPhone8,4"])  return @"iPhone SE";
    
    if ([phoneType  isEqualToString:@"iPhone9,1"])  return @"iPhone 7";
    
    if ([phoneType  isEqualToString:@"iPhone9,2"])  return @"iPhone 7 Plus";
    
    if ([phoneType  isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
    
    if ([phoneType  isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    
    if ([phoneType  isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    
    if ([phoneType  isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    
    if ([phoneType  isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    
    if ([phoneType  isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    
    if ([phoneType  isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    
    if ([phoneType  isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    
    if ([phoneType  isEqualToString:@"iPhone11,4"]) return @"iPhone XS Max";
    
    if ([phoneType  isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    return nil;
}


#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // There is no other control that can take focus, so manually resign focus
    // when return (Join) is pressed to trigger |textFieldDidEndEditing|.
    [textField resignFirstResponder];
    return YES;
}


#pragma mark NoticeextFieldSaveDelegate
- (void) onNoticeSave:(RTCTextField *) textField {
    if ([textField.roomText length] < 0) {
        return;
    }
    
    if (textField == _aapText) {
 //       BDCloudDefaultRTCAppID = textField.roomText;
//        [self.storage setObject:textField.roomText forKey:@"signal_rtc"];
//        [self.storage setObject:_pathText.roomText forKey:@"url_rtc"];
    } else if (textField == _roomText) {
//        [self.storage setObject:_signalText.roomText forKey:@"signal_rtc"];
//        [self.storage setObject:textField.roomText forKey:@"url_rtc"];
    }
}
@end

