

#import "CalculatorViewController.h"
#import <Masonry.h>
#import "connectDeviceManager.h"
#import "RSATool.h"

@interface CalculatorViewController ()
{
    UIView *bgView;/*引导视图*/
}
@end

@implementation CalculatorViewController
@synthesize pwd;

#define BUTTON
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor=[UIColor blackColor];
    CGFloat mWidth=self.view.frame.size.width;
    CGFloat mHieght=self.view.frame.size.height;
    //加载button
    [self loadButtons:mWidth Hight:mHieght];
    //加载textField
    [self loadTextField:mWidth Hight:mHieght];
    
    //初始化Calculator
    _cl=[[Calculator alloc]init];
    
    /*加载引导视图*/
    BOOL haveOpenMask = [HWDataManager getBoolWithKey:Const_Mask_View_Open_Calcuator_Tips];
    if (haveOpenMask == NO){
        [self addGuideView];
    }
}

- (void)addGuideView{
    bgView = [[UIView alloc] init];
    [bgView setBackgroundColor:HW000000Color60];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
    
    /*箭头视图*/
    UIImageView *flagImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"guide_open_calcu_flag1"]];
    [bgView addSubview:flagImageView];
    [flagImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-118.f);
        make.height.mas_equalTo(67);
        make.width.mas_equalTo(22);
        make.top.equalTo(_TF.mas_centerY).offset(40);
    }];
    
    /*不可点击btn*/
    UIButton *unableBtn = [[UIButton alloc] init];
    unableBtn.frame = CGRectMake(0, 0, 295, 64);

    NSString * curStr = NSLocalizedString(@"guide_set_open_calcula_guide_tips",nil);
    CGFloat curHeight = [curStr boundingRectWithSize:CGSizeMake(295 - 20 , 1000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14.f]} context:nil].size.height;
    
    if(curHeight < 50){
        curHeight = 50;
    }
    else{
        curHeight += 20;
    }
    
    
    // gradient
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,295,curHeight);
    gl.startPoint = CGPointMake(0, 0.5);
    gl.endPoint = CGPointMake(1, 0.5);
    gl.colors = @[(__bridge id)HW0CDEFDColor.CGColor, (__bridge id)HW058DFBColor.CGColor];
    gl.locations = @[@(0), @(1.0f)];
    
    [unableBtn.layer addSublayer:gl];
    [unableBtn setUserInteractionEnabled:NO];
    [unableBtn setTitle:curStr forState:(UIControlStateNormal)];
    [unableBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [unableBtn.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
    [unableBtn.titleLabel setNumberOfLines:0];
    [unableBtn.layer setCornerRadius:curHeight/2.0];
    unableBtn.clipsToBounds = YES;
    [bgView addSubview:unableBtn];
    [unableBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20*AUTOSCALE);
        make.width.mas_equalTo(295);
        make.top.equalTo(flagImageView.mas_bottom).offset(-8);
        make.height.mas_equalTo(curHeight);
    }];
    unableBtn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 10);
    
    UIButton *knowBtn = [[UIButton alloc] init];
    [knowBtn setBackgroundColor:[UIColor clearColor]];
    [knowBtn.layer setCornerRadius:18.f];
    [knowBtn.layer setBorderColor:HWFFFFFFColor.CGColor];
    [knowBtn.layer setBorderWidth:1];
    [knowBtn setTitle:NSLocalizedString(@"guide_set_pwd_guide_know",nil) forState:(UIControlStateNormal)];
    [knowBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [knowBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [bgView addSubview:knowBtn];
    [knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-29*AUTOSCALE);
        make.width.mas_equalTo(120);
        make.top.equalTo(unableBtn.mas_bottom).offset(15);
        make.height.mas_equalTo(36.f);
    }];
    [knowBtn addTarget:self
                action:@selector(knowBtnPressed)
      forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)knowBtnPressed{
    [bgView removeFromSuperview];
    [HWDataManager setBoolWithKey:Const_Mask_View_Open_Calcuator_Tips value:YES];
}

#pragma mark ----样式设置----
-(void)loadButtons:(CGFloat)mWidth Hight:(CGFloat)mHieght{
    CGFloat x=1;
    CGFloat y=mHieght-(((mWidth-5)/4)*5)-1 - 60;
    NSArray *buttonArray=@[@"C",@"+/-",@"%",@"÷",@"7",@"8",@"9",@"×",@"4",@"5",@"6",@"—",@"1",@"2",@"3",@"+",@"0",@".",@"="];
    NSInteger buttonArrayID=0;
    for (int i=0; i<5; i++) {
        for (int j=0; j<(i==4?3:4); j++) {
            UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
            
            button.frame=CGRectMake(x, y, (buttonArrayID==16?(mWidth-5)/4*2+1 - 13:(mWidth-5)/4 - 13), (mWidth-5)/4 - 13);
            button.layer.cornerRadius = ((mWidth-5)/4 - 13)/2;
            
            [button setTitle:[buttonArray objectAtIndex:buttonArrayID] forState:UIControlStateNormal];

            button.titleLabel.font=[UIFont systemFontOfSize:40];
            
            button.tag=100+buttonArrayID;
            
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            if (buttonArrayID%4==3||buttonArrayID==[buttonArray count]-1) {
                button.backgroundColor=HWEFA23BColor;
            }else if(buttonArrayID==16){
                //设置 0 Button 文字向右对齐
                [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, (mWidth-5)/4)];
                x+=((mWidth-5)/4)+1;
                button.backgroundColor=HW333333Color9;
            }else if(buttonArrayID<3){
                button.backgroundColor=HWA5A5A5Color;
                [button setTitleColor:  [UIColor blackColor] forState:UIControlStateNormal] ;
            }else{
                button.backgroundColor=HW333333Color9;
            }
            
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.view addSubview:button];
            
            x+=((mWidth-5)/4)+1;
            buttonArrayID++;
        }
        x=1;
        y+=((mWidth-5)/4)+1;
    }

}
-(void)loadTextField:(CGFloat)mWidth Hight:(CGFloat)mHieght{
    _TF=[[UITextField alloc]initWithFrame:CGRectMake(10, 50, mWidth-20, mHieght-(((mWidth-5)/4)*5)-50)];
    _TF.tag=1000;
    _TF.textColor=[UIColor whiteColor];
    [_TF setEnabled:NO];
    _TF.textAlignment=NSTextAlignmentRight;
    _TF.adjustsFontSizeToFitWidth=YES;//自适应宽度
    _TF.text=@"0";
    _TF.font=[UIFont fontWithName:@"HelveticaNeue-Thin" size:80];
    [self.view addSubview:_TF];
}


#pragma mark ----button响应----

//button响应方法
-(void)buttonAction:(UIButton *)sender{
    
    [self removeTextFieldFormat];
    switch (sender.tag) {
        case 100:
            //清除
            if ([sender.titleLabel.text isEqualToString:@"AC"]) {
                [self buttonSymbolStyleReduction:sender];
            }
            self.TF.text=@"0";
            [sender setTitle:@"AC" forState:UIControlStateNormal];
            [self.cl calculatorEmpty];
            break;
        case 101:
            //正负转换
            [self getPlusMinus:self.TF.text];
            break;
        case 102:
            //百分比
            [self getPercentage:self.TF.text];
            break;
        case 103:
            //除
            
            [self execute];
            self.cl.exType=1;
            [self buttonSymbolStyleReduction:sender];
            [self buttonSymbolStyle:sender];
            break;
        case 107:
            //乘
            
            [self execute];
            self.cl.exType=2;
            [self buttonSymbolStyleReduction:sender];
            [self buttonSymbolStyle:sender];
            break;
        case 111:
            //减
            
            [self execute];
            self.cl.exType=3;
            [self buttonSymbolStyleReduction:sender];
            [self buttonSymbolStyle:sender];
            break;
        case 115:
            //加
            
            [self execute];
            self.cl.exType=4;
            [self buttonSymbolStyleReduction:sender];
            [self buttonSymbolStyle:sender];
            break;
        case 117:
            //小数点
            [self decimalPoint:self.TF Button:sender];
            break;
        case 118:
            //等
            [self execute];
            self.cl.exType=0;
            [self buttonSymbolStyleReduction:sender];
//            self.TF.text=@"0";
            break;
        default:
            //判断清空计数
            if (self.emptyCount!=0) {
                self.TF.text=@"";
                self.emptyCount=0;
            }
            [self buttonSymbolStyleReduction:sender];
            [(UIButton *)[self.view viewWithTag:100] setTitle:@"C" forState:UIControlStateNormal];
            [self textFieldValueChange:self.TF Button:sender];
            break;
    }
    
    [self addTextFieldFormat];
}

#pragma mark ----样式处理----
//添加点击运算符号button样式方法
-(void)buttonSymbolStyle:(UIButton *)sender{
    [sender.layer setBorderWidth:2];
}
//还原运算符号button样式方法
-(void)buttonSymbolStyleReduction:(UIButton *)sender{
    [((UIButton *)[self.view viewWithTag:103]).layer setBorderWidth:0] ;
    [((UIButton *)[self.view viewWithTag:107]).layer setBorderWidth:0] ;
    [((UIButton *)[self.view viewWithTag:111]).layer setBorderWidth:0] ;
    [((UIButton *)[self.view viewWithTag:115]).layer setBorderWidth:0] ;
    [sender.layer setBorderWidth:0];
}

//添加textfield格式
-(void)addTextFieldFormat{
    NSMutableString *mutableStr=[NSMutableString stringWithString:self.TF.text];
    NSInteger mutableStrLength=mutableStr.length;
    //判断是否包含小数点 如果包含获取小数点左边的数字个数mutableStrLength
    if ([mutableStr containsString:@"."]) {
        mutableStrLength=[self getPointLeft:mutableStr];
    }else{
        mutableStrLength=[self getNumberCount:mutableStr];
    }
    
    for(int i=3 ; i<mutableStrLength ; i++ ){
        //每三个数字添加一次分隔符
        if (i%3==0) {
            //添加分隔逗号
            if (mutableStrLength>i) {
                NSInteger index=mutableStr.length-i-(mutableStr.length-mutableStrLength);
                NSRange range=NSMakeRange(index-1, 1);
                //如果上一个不是负号则添加分隔逗号
                if (![[mutableStr substringWithRange:range]isEqualToString:@"-"]) {
                    //如果第一个是负号 分隔符位置+1
                    if ([[mutableStr substringWithRange:NSMakeRange(0, 1)]isEqualToString:@"-"]) {
                        [mutableStr insertString:@"," atIndex:index+1];
                    }else{
                        [mutableStr insertString:@"," atIndex:index];
                    }
                }else{
                    [mutableStr insertString:@"," atIndex:index+1];
                }
            }
        }
    }
    //如果textfield为空时 自动补0
    if ([mutableStr isEqualToString:@""]) {
        mutableStr=[NSMutableString stringWithString:@"0"];
    }
    self.TF.text=mutableStr;
}
//去除textfield格式
-(void)removeTextFieldFormat{
    if ([self.TF.text isEqualToString:@"0"]) {
        self.TF.text=@"";
    }
    self.TF.text=[self.TF.text stringByReplacingOccurrencesOfString:@"," withString:@""];
}

//textField内容处理方法 限制输入长度 添加分隔符
-(void)textFieldValueChange:(UITextField *)tf Button:(UIButton *)sender{
    NSString *buttonTitleStr=sender.titleLabel.text;
    if ([self getNumberCount:tf.text]<9) {
        tf.text=[tf.text stringByAppendingString:buttonTitleStr];
    }
    
    NSLog(@"tf.text = %@",tf.text);
    
    if(tf.text.length == 4){
        [self verifyPwdFun:tf.text];
    }
    
//    if ([tf.text isEqualToString:pwd]){
//        [connectDeviceManager shareInstance].isFirstInputPwdDone = YES;
//
//        [[NSNotificationCenter defaultCenter] postNotificationName:ShowImgAndVoiceNotification object:nil];
//
//        [self.view removeFromSuperview];
//    }
}

#pragma mark 验证密码是否正确
-(void)verifyPwdFun:(NSString*)text{
    /*先判断本地有无设备 无设备时需要先扫码添加设备*/
    NSDictionary *deviceDict = [HWDataManager getObjectWithKey:Const_Have_Add_Device];
    if (deviceDict && [[deviceDict allKeys] containsObject:Const_Have_Add_Device_SN]){
        //有设备了先去做链接准备  // 80bec9c5
        NSString *SNStr = deviceDict[@"Const_Have_Add_Device_SN"];
        
        if(SNStr){
            [[connectDeviceManager shareInstance] getThridMsgBySN:SNStr needReconnect:NO didNetEnd:^(bool didSuc) {
                
                if(didSuc){
                    NSString *curPwd = [connectDeviceManager shareInstance].DeviceThirdIdMod.data.password;
                    NSString*desPwdStr  = [RSATool AES128Decrypt:curPwd key:AESCODEKEEYY];
                    
                    if ([desPwdStr isEqualToString:text]){
                        [connectDeviceManager shareInstance].isFirstInputPwdDone = YES;
                        
                        [self.view removeFromSuperview];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [[NSNotificationCenter defaultCenter] postNotificationName:ShowImgAndVoiceNotification object:nil];
                        });
                    }
                }
                else{
                    
                }
                
            }];
        }
    }
    
}

//小数点限制方法
-(void)decimalPoint:(UITextField *)tf Button:(UIButton *)sender{
    //判断是否已经输入小数点
    if (![tf.text containsString:@"."]) {
        tf.text=[tf.text stringByAppendingString:sender.titleLabel.text];
    }
    //判断是否直接输入小数点
    if([self.TF.text isEqualToString:@"."]){
        self.TF.text=@"0.";
    }
}

//获取小数点左边数字个数
-(NSInteger)getPointLeft:(NSString *)str{
    NSInteger pointLeft=str.length;
    //判断是否包含小数点 如果包含获取小数点左边的数字个数
    if ([str containsString:@"."]) {
        NSRange range = [str rangeOfString:@"."];
        NSLog(@"getPointLeft=%ld",range.location);
        pointLeft=range.location;
    }
    //判断是否包含负号
    if ([str containsString:@"-"]) {
        pointLeft-=1;
    }
    return pointLeft;
}
//获取小数点右边数字个数
-(NSInteger)getPointRight:(NSString *)str{
    NSInteger pointRight=0;
    //判断是否包含小数点 如果包含获取小数点右边的数字个数
    if ([str containsString:@"."]) {
    NSRange range = [str rangeOfString:@"."];
    NSLog(@"getPointRight=%ld",str.length- range.location);
        pointRight=str.length- range.location;
    }
    return pointRight;
}
//获取纯数字个数
-(NSInteger)getNumberCount:(NSString *)str{
    NSInteger numberCount=str.length;
    //判断是否包含小数点
    if ([str containsString:@"."]) {
        numberCount-=1;
    }
    //判断是否包含负号
    if ([str containsString:@"-"]) {
        numberCount-=1;
    }
    //判断是否包含分隔逗号
    if ([str containsString:@","]) {
        if ([self getPointLeft:str]<5) {
            numberCount-=1;
        }else{
            numberCount-=2;
        }
    }
    return numberCount;
}

//UIColor 转UIImage
- (UIImage*) createImageWithColor: (UIColor*) color{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark ----运算----
//正负数转换
-(void)getPlusMinus:(NSString *)number{
    self.TF.text=[self.cl getPlusMinus:self.TF.text];
    [self textFieldLastValue];
}
//ios计算器bug
//2 * 9 ÷ 目前等于18 转换正负数会变为-0
//计算百分比
-(void)getPercentage:(NSString *)number{
    
    number=[NSString stringWithFormat:@"%f",[number doubleValue]/100];
    //去除floa转换后后面多余的0
    self.TF.text = [NSString stringFloatHandle:number];
    [self textFieldLastValue];
}
//ios计算器bug
//5 * 点击% 变成0.05  再点6  等于30 而不是0.3

//判断textfield上的内容是否为上一次的运算结果 并进行赋值操作 以保证连续运算时执行以上两种操作后的结果能够正确参与运算
-(void)textFieldLastValue{
    //如果number1和result都不为空 number2为空 并且清空计数为1(说明刚刚点击过运算符号button) 说明当前textfield上的内容为上一次的运算结果
    if (self.cl.number1 != nil) {
        if (self.cl.result != nil) {
            if (self.cl.number2==nil) {
                if (self.emptyCount==1) {
                    self.cl.number1=self.TF.text;//将转换后的值赋给number1,以便下次运算使用
                }
            }
        }
    }
}

//四则运算
-(void)execute{
    if(self.emptyCount==0){
        if(self.cl.number1 ==nil){
            self.cl.number1=self.TF.text;
        }else{
            self.cl.number2=self.TF.text;
        }
        //如果number1和number2都不为空 进行计算
        if (self.cl.number2 != nil && self.cl.number1 != nil) {
            //判断除数是否为0
            if([self.cl.number2 isEqualToString:@""]&&self.cl.exType==1){
                self.TF.text=@"错误";
            }else{
                self.TF.text=[self.cl Execute];
            }
        }
        //清空计数
        self.emptyCount=1;
    }
}

@end
