//
//  SetCategoryPriceController.m
//  iSales-NPD
//
//  Created by Jack on 2016/10/11.
//  Copyright © 2016年 United Software Applications, Inc. All rights reserved.
//

#import "SetCategoryPriceController.h"
#import "const.h"
#import "EnumSelectViewController.h"
#import "iSalesNetwork.h"

#define Percent  100
#define Float    101
#define NoChange 102

#define NUMBERS @"0123456789.\n"
#define NEGATIVE_NUMBERS @"0123456789.-\n"


@interface SetCategoryPriceController ()<UITextFieldDelegate>

@property (strong, nonatomic) IBOutlet UIButton *basePriceButton;
@property (strong, nonatomic) IBOutlet UIButton *floatCheckButton;
@property (strong, nonatomic) IBOutlet UIButton *percentageCheckButton;
@property (strong, nonatomic) IBOutlet UITextField *floatTextField;
@property (strong, nonatomic) IBOutlet UITextField *percentageTextField;

@property (nonatomic,assign) NSInteger changePrice;
@property (nonatomic,assign) NSInteger priceType;

@end

@implementation SetCategoryPriceController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.changePrice = NoChange;
    self.basePriceButton.enabled = NO;
    [self configAppearance];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configAppearance {
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                   style:UIBarButtonItemStylePlain
                                                                  target:self
                                                                  action:@selector( returnBackClick:)];
    
    self.navigationItem.leftBarButtonItem = backButton;
    
    // base price
//    NSString *basePrice = [self.categoryPrice objectForKey:@"base_price"];
//    [self changePriceType:basePrice.integerValue];
    [self changePriceType:1];
    
    // discount
    NSString *discount = [self.categoryPrice objectForKey:@"price_discount"];
    if ([discount hasSuffix:@"%"]) {
        self.percentageTextField.text = [discount substringToIndex:discount.length - 1];
    } else {
        self.floatTextField.text = discount;
    }

}

- (void)returnBackClick:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)changePriceType:(NSInteger)type {
    
    NSString *title = [Singleton sharedInstance].deliveryString;
    switch (type) {
        case 0: {
            title = [Singleton sharedInstance].deliveryString;
        }
            break;
        case 1: {
            title = flat_price;
        }
            break;
            
        default:
            break;
    }
    
    self.priceType = type;
    [self.basePriceButton setTitle:title forState:UIControlStateNormal];
    
}


- (NSString *)checkPriceType:(NSInteger)priceType {
    return  self.priceType == priceType ? @"1" : @"0";
}

- (NSInteger)checkedCadedate:(NSDictionary *)cadedate {
    
    int priceType = 0;
    int count = [[cadedate objectForKey:@"count"] intValue];
    for (int i = 0; i < count; i++) {
        NSDictionary *dic = [cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
        int check = [[dic objectForKey:@"check"] intValue];
        if (check) {
            
            priceType = [[dic objectForKey:@"value_code"] integerValue];
            
            break;
        }
    }
    
    return priceType;
}


- (IBAction)basePriceButtonClick:(UIButton *)sender {
    
    EnumSelectViewController* enumvc =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"EnumSelectorViewController"];
    
    enumvc.max_select = 1;
    
    
    enumvc.cadedate = @{
                        @"count" : @"2",
                        @"val_0" : @{@"value" : [Singleton sharedInstance].deliveryString,@"value_code" : @"0",@"check" : [self checkPriceType:0]},
                        @"val_1" : @{@"value" : flat_price,@"value_code" : @"1",@"check" : [self checkPriceType:1]}
                        }.mutableCopy;
    enumvc.title = @"";
    
    
    enumvc.single_select =true;
    
    __weak typeof(self) weakSelf = self;
    
    enumvc.returnValue = ^(NSMutableDictionary* value){
        
        if (weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf changePriceType:[strongSelf checkedCadedate:value]];
        }
        
    };
    
    [self.navigationController pushViewController:enumvc animated:true];
}

- (IBAction)percentageCheckButtonClick:(UIButton *)sender {
    
    
    if (self.changePrice == NoChange || self.changePrice == Percent) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            self.changePrice = Percent;
        } else {
            self.changePrice = NoChange;
        }
    } else if (self.changePrice == Float) {
        sender.selected = YES;
        self.changePrice = Percent;
        self.floatCheckButton.selected = NO;
        self.floatTextField.enabled = NO;
    }
    
    self.percentageTextField.enabled = sender.selected;
    
}

- (IBAction)floatCheckButtonClick:(UIButton *)sender {
    
    if (self.changePrice == NoChange || self.changePrice == Float) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            self.changePrice = Float;
        } else {
            self.changePrice = NoChange;
        }
        
    } else if (self.changePrice == Percent) {
        sender.selected = YES;
        self.changePrice = Float;
        self.percentageCheckButton.selected = NO;
        self.percentageTextField.enabled = NO;
    }
    self.floatTextField.enabled = sender.selected;
}
- (IBAction)saveButtonClick:(UIButton *)sender {
    
    // 向服务器提交数据
    // http://192.168.0.126:8080/site/isales/setSeeGivenPrice.htm
    
    NSString *discount = @"";
    BOOL rightDiscount = YES;
    switch (self.changePrice) {
        case Float:{
            discount = self.floatTextField.text;
            if (!discount || !discount.length) {
                rightDiscount = NO;
            }
        }
            break;
        case Percent:{
            discount = [self.percentageTextField.text stringByAppendingString:@"%"];
            if (!discount || discount.length <= 1) {
                rightDiscount = NO;
            }
        }
            break;
    
        default:
            break;
    }
    
    
    if (rightDiscount) {
        
        UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Set Price"];
        
        NSDictionary *dic = [iSalesNetwork set_npd_shop_givenPrice:@{@"base_price" : [NSString stringWithFormat:@"%d",self.priceType],@"discount" : discount,@"category_id" : @(self.categoryID)}.mutableCopy];
        
        [waitalert dismissWithClickedButtonIndex:0 animated:YES];
        
        if ([[dic objectForKey:@"result"] integerValue] == 2) {
            
            [self.categoryPrice setObject:[NSString stringWithFormat:@"%d",self.priceType] forKey:@"base_price"];
            [self.categoryPrice setObject:discount forKey:@"price_discount"];
            
            // 将数据返回
            if (self.returnBlock)
                self.returnBlock(self.categoryPrice);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } else {
        
        [RAUtils message_alert:@"Please write a correct value" title:@"Warning" controller:self];
        
    }
    
}

#pragma mark - text field delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (newText.length == 0)
        return YES;

//    // 第一个字符不能为小数点
//    if ([newText isEqualToString:@"."])
//        return NO;
//    if ([newText componentsSeparatedByString:@"."].count > 2) {
//        return NO;
//    } // 不能有多个小数点
//    
//    // 只能第一个字符为减号
//    if (newText.length > 1 && [string isEqualToString:@"-"]) {
//        return NO;
//    }
//    // 不能为 0123
//    if (newText.length > 1 && [newText hasPrefix:@"0"] && [newText characterAtIndex:1] != '.') {
//        return NO;
//    }
//    // 不能为 -0123
//    if (newText.length > 2 && [newText hasPrefix:@"-0"] && [newText characterAtIndex:2] != '.') {
//        return NO;
//    }
//
//    // 校验正数
//    NSCharacterSet *cs;
//    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
//    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
//    BOOL canChange = [string isEqualToString:filtered];
//    
//    if ([textField isEqual:self.floatTextField]) {
//
//        // 校验负数
//        NSCharacterSet *negative_cs;
//        
//        negative_cs = [[NSCharacterSet characterSetWithCharactersInString:NEGATIVE_NUMBERS]invertedSet];
//        NSString *negative_filtered = [[string componentsSeparatedByCharactersInSet:negative_cs]componentsJoinedByString:@""];
//        
//        BOOL negative_canChange = [string isEqualToString:negative_filtered];
//        
//        // 只能第一个字符为减号
//        if ([string isEqualToString:@"-"]) {
//            
//            if (newText.length == 1 && [string isEqualToString:@"-"]) {
//                negative_canChange = YES && negative_canChange;
//            } else {
//                negative_canChange = NO;
//            }
//        }
//
//        
//        return canChange || negative_canChange;
//    } else {
//        return canChange;
//    }
    

    // 正则表达式
    NSString *match = @"-[1-9]{1,1}[0-9]*(\\.[0-9]*)?|-0\\.[0-9]+|[1-9]{1,1}[0-9]*(\\.[0-9]*)?|0\\.[0-9]{0,}|0{1,1}|-{1,1}|-0{1,1}|-0\\.{1,1}";
    
    if ([textField isEqual:self.percentageTextField])
        match = @"[1-9]{1,1}[0-9]*(\\.[0-9]*)?|0(\\.[0-9]*)?";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",match];
    
        return [predicate evaluateWithObject:newText];
}

@end
