//
//  SMCreateClientViewController.m
//  SkinMagnifier
//
//  Created by nana on 2020/11/6.
//

#import "SMCreateClientViewController.h"
#import "SMTakeImageViewController.h"
#import <AFNetworking.h>
#import "MTRAreaPickView.h"
#import <MOFSPickerManager/MOFSPickerManager.h>
#import <TZImagePickerController.h>
#import <SDWebImage/SDImageCache.h>
#import "SMLinkDeviceView.h"


@interface SMCreateClientViewController ()
@property(nonatomic, strong)NSMutableArray *labelArray;
@property(nonatomic, strong)UIButton *iconBtn;
@property(nonatomic, strong)UITextField *nameTF;
@property(nonatomic, strong)UIButton *grilBtn;
@property(nonatomic, strong)UIButton *boyBtn;
@property(nonatomic, strong)UITextField *phoneTF;
@property(nonatomic, strong)UIButton *birthdayBtn;
@property(nonatomic, strong)UIButton *areaBtn;
@property(nonatomic, strong)UITextField *addressTF;
@property(nonatomic, strong)UIButton *saveBtn;
@property(nonatomic, strong)MTRAreaPickView *rpView;

@property(nonatomic, strong)NSString *sex;
@property(nonatomic, strong)NSString *areaprovince;
@property(nonatomic, strong)NSString *areacity;
@property(nonatomic, strong)NSString *arearegion;
@property(nonatomic, strong)NSString *areatxt;

@end

@implementation SMCreateClientViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.rpView = [[MTRAreaPickView alloc] init];
    
    
    self.labelArray = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    if (self.clientModel.ID) {
        self.wb_titleLabel.text = @"编辑档案";
    }else {
        self.wb_titleLabel.text = @"新建档案";
    }

    NSArray *firstArray = [@"头像,顾客姓名,性别" componentsSeparatedByString:@","];
    [self createViewWithNameArray:firstArray firstTop:92.5];

    UILabel *lastLabel =  self.labelArray.lastObject;
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = rgba(243, 243, 243, 1);
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lastLabel.mas_bottom).offset(17.5);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(10);
    }];
    
    NSArray *secondArray = [@"联系方式,生日,地区,地址" componentsSeparatedByString:@","];
    [self createViewWithNameArray:secondArray firstTop:270];
    
    
    for (int i = 0; i < self.labelArray.count; i++) {
        UILabel *label = self.labelArray[i];
        
        if (i == 0) {
            UIButton *iconBtn = [[UIButton alloc] init];
            iconBtn.layer.masksToBounds = YES;
            iconBtn.layer.cornerRadius = 15;
            [iconBtn addTarget:self action:@selector(iconBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [iconBtn wb_setImageName:@"customer_logo"];
//            [iconBtn setBackgroundImage:[[UIImage wb_imageWithColor:rgba(242, 238, 233, 1) size:CGSizeMake(30, 30)] sd_roundedCornerImageWithRadius:15 corners:0xff borderWidth:0 borderColor:[UIColor clearColor]] forState:UIControlStateNormal];
            [self.view addSubview:iconBtn];
            _iconBtn = iconBtn;
            [iconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.right.mas_equalTo(-40.5);
                make.size.mas_equalTo(CGSizeMake(30, 30));
            }];
            UIImageView *showImageView = [[UIImageView alloc] init];
            showImageView.image = [UIImage imageNamed:@"customer_icon_xyb"];
            [self.view addSubview:showImageView];
            [showImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.right.mas_equalTo(-22);
            }];
            
        }else if (i == 1){
            
            UILabel *xinLabl = [[UILabel alloc] init];
            xinLabl.attributedText = createAttString(@"*", 15, rgba(255, 0, 0, 1));
            [self.view addSubview:xinLabl];
            [xinLabl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label).offset(2);
                make.left.equalTo(label.mas_right).offset(10);

            }];
            
            
            UITextField *nameTF = [[UITextField alloc] init];
            nameTF.textColor = rgba(76, 74, 66, 1);
            nameTF.font = [UIFont systemFontOfSize:14];
            nameTF.textAlignment = NSTextAlignmentRight;
            _nameTF = nameTF;
            [nameTF addTarget:self action:@selector(nameTFTextChange:) forControlEvents:UIControlEventEditingChanged];
            nameTF.attributedPlaceholder = createAttString(@"未填写", 14, rgba(185, 185, 185, 1));
            [self.view addSubview:nameTF];
            [nameTF mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.left.mas_equalTo(100);
                make.right.mas_equalTo(-22);
            }];
        }else if (i == 2){
            
            UIImage *norImage = [[UIImage wb_imageWithColor:[UIColor whiteColor] size:CGSizeMake(75.5, 26)] sd_roundedCornerImageWithRadius:13 corners:0xff borderWidth:0.5 borderColor:rgba(255, 124, 78, 1)];
            UIImage *selImage = [[UIImage wb_imageWithColor:rgba(255, 124, 78, 1) size:CGSizeMake(75.5, 26)] sd_roundedCornerImageWithRadius:13 corners:0xff borderWidth:0.5 borderColor:rgba(255, 124, 78, 1)];
            
            UIButton *boyBtn = [[UIButton alloc] init];
            [boyBtn addTarget:self action:@selector(xbBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            _boyBtn = boyBtn;
            [boyBtn setAttributedTitle:createAttString(@"男", 14, rgba(255, 124, 78, 1)) forState:UIControlStateNormal];
            [boyBtn setAttributedTitle:createAttString(@"男", 14, [UIColor whiteColor]) forState:UIControlStateSelected];
            [boyBtn setBackgroundImage:norImage forState:UIControlStateNormal];
            [boyBtn setBackgroundImage:selImage forState:UIControlStateSelected];
            [self.view addSubview:boyBtn];
            [boyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
        
                make.right.mas_equalTo(-22);
            }];
            
            UIButton *girlBtn = [[UIButton alloc] init];
            [girlBtn addTarget:self action:@selector(xbBtnClick:) forControlEvents:UIControlEventTouchUpInside];

            _grilBtn = girlBtn;
            girlBtn.selected = YES;
            self.sex = @"0";
            [girlBtn setAttributedTitle:createAttString(@"女", 14, rgba(255, 124, 78, 1)) forState:UIControlStateNormal];
            [girlBtn setAttributedTitle:createAttString(@"女", 14, [UIColor whiteColor]) forState:UIControlStateSelected];
            [girlBtn setBackgroundImage:norImage forState:UIControlStateNormal];
            [girlBtn setBackgroundImage:selImage forState:UIControlStateSelected];
            [self.view addSubview:girlBtn];
            [girlBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.right.equalTo(boyBtn.mas_left).offset(-13.5);
            }];
            
        }else if (i == 3){
            UITextField *phoneTF = [[UITextField alloc] init];
            phoneTF.textColor = rgba(76, 74, 66, 1);
            phoneTF.font = [UIFont systemFontOfSize:14];
            phoneTF.keyboardType =UIKeyboardTypePhonePad;
            phoneTF.textAlignment = NSTextAlignmentRight;
            _phoneTF = phoneTF;
            phoneTF.attributedPlaceholder = createAttString(@"未填写", 14, rgba(185, 185, 185, 1));
            [self.view addSubview:phoneTF];
            [phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.left.mas_equalTo(100);
                make.right.mas_equalTo(-22);
            }];
        }else if (i == 4){

            UIButton *birthdayBtn = [[UIButton alloc] init];
            [birthdayBtn addTarget:self action:@selector(birthdayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            _birthdayBtn = birthdayBtn;
            [birthdayBtn setAttributedTitle:createAttString(@"未填写", 14, rgba(185, 185, 185, 1)) forState:UIControlStateNormal];
            [birthdayBtn wb_setImageName:@"customer_icon_xyb"];
            birthdayBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -4.5, 0, 4.5);
            [birthdayBtn wb_setRightImage];
            [self.view addSubview:birthdayBtn];
            [birthdayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.right.mas_equalTo(-22);
            }];

        }else if (i == 5) {
            
            UIButton *areaBtn = [[UIButton alloc] init];
            _areaBtn = areaBtn;
            [areaBtn addTarget:self action:@selector(areaBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [areaBtn setAttributedTitle:createAttString(@"未填写", 14, rgba(185, 185, 185, 1)) forState:UIControlStateNormal];
            [areaBtn wb_setImageName:@"customer_icon_xyb"];
            areaBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -4.5, 0, 4.5);
            [areaBtn wb_setRightImage];
            [self.view addSubview:areaBtn];
            [areaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.right.mas_equalTo(-22);
            }];

            @weakify(self);
            self.rpView.selectCityBlock = ^(NSInteger province, NSInteger city, NSInteger district, NSString * _Nonnull resultStr) {
                @strongify(self);
                self.areacity = [NSString stringWithFormat:@"%ld",city];
                self.areaprovince = [NSString stringWithFormat:@"%ld",province];
                self.arearegion = [NSString stringWithFormat:@"%ld",district];
                self.areatxt = resultStr;
                [self.areaBtn setAttributedTitle:createAttString(resultStr, 14,rgba(76, 74, 66, 1)) forState:UIControlStateNormal];

            };
        }else if (i == 6) {
            
            UITextField *addressTF = [[UITextField alloc] init];
            addressTF.textColor = rgba(76, 74, 66, 1);
            addressTF.font = [UIFont systemFontOfSize:14];
            addressTF.textAlignment = NSTextAlignmentRight;
            _addressTF = addressTF;
            addressTF.attributedPlaceholder = createAttString(@"未填写", 14, rgba(185, 185, 185, 1));
            [self.view addSubview:addressTF];
            [addressTF mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(label);
                make.left.mas_equalTo(100);
                make.right.mas_equalTo(-22);
            }];
        } 
    }

    
    UIButton *saveBtn = [[UIButton alloc] init];
    _saveBtn = saveBtn;
    saveBtn.userInteractionEnabled = NO;
    saveBtn.selected = YES;
    [saveBtn addTarget:self action:@selector(saveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setAttributedTitle:createAttString(@"保存", 15, rgba(255, 255, 255, 1)) forState:UIControlStateNormal];

    [saveBtn setBackgroundImage:[[UIImage wb_imageWithColor:rgba(255, 124, 78, 1) size:CGSizeMake(225.5, 45)] sd_roundedCornerImageWithRadius:45/2.0 corners:0xff borderWidth:0 borderColor:rgba(0, 0, 0, 0)]  forState:UIControlStateNormal];
    [saveBtn setBackgroundImage:[[UIImage wb_imageWithColor:rgba(255, 200, 180, 1) size:CGSizeMake(225.5, 45)] sd_roundedCornerImageWithRadius:45/2.0 corners:0xff borderWidth:0 borderColor:rgba(0, 0, 0, 0)]  forState:UIControlStateSelected];
    [self.view addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(safaBottom(-50));
        make.centerX.mas_equalTo(0);
    }];

    if (self.clientModel.ID) {

        [self.iconBtn sd_setImageWithURL:[NSURL URLWithString:self.clientModel.clientimg] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"customer_logo"]];

        self.nameTF.text = self.clientModel.cname;
        [self nameTFTextChange:self.nameTF];
        if ([self.clientModel.sex isEqualToString:@"0"]) {
            [self xbBtnClick:self.grilBtn];
        }else {
            [self xbBtnClick:self.boyBtn];
        }
        
        self.phoneTF.text = self.clientModel.telphone;
        
        if (self.clientModel.birthday.length) {
            [self.birthdayBtn setAttributedTitle:createAttString(timestampString(self.clientModel.birthday.longLongValue/1000, @"yyyy-MM-dd") ,  14,rgba(76, 74, 66, 1)) forState:UIControlStateNormal];
        }

        
        if (self.clientModel.areatxt.length) {
            [self.areaBtn setAttributedTitle:createAttString(self.clientModel.areatxt,14,rgba(76, 74, 66, 1)) forState:UIControlStateNormal];
        }


        
        self.addressTF.text = self.clientModel.address;
    
        self.sex = self.clientModel.sex;
        
        self.areaprovince = self.clientModel.areaprovince;
        self.areacity = self.clientModel.areacity;
        self.arearegion = self.clientModel.arearegion;
        self.areatxt = self.clientModel.areatxt;
        
    }

}
- (void)iconBtnClick:(UIButton *)btn {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    imagePickerVc.allowPickingVideo = NO;
//    presentViewController
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    @weakify(self);
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        @strongify(self);
        UIImage *img =  photos.firstObject;
        [self.iconBtn setImage:img forState:UIControlStateSelected];
        self.iconBtn.selected = YES;
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)areaBtnClick:(UIButton *)btn {
    [self.rpView show];
}
- (void)nameTFTextChange:(UITextField *)tf {
    bool user = tf.text.length;
    self.saveBtn.selected = !user;
    self.saveBtn.userInteractionEnabled = user;
}
- (void)xbBtnClick:(UIButton *)btn {
    if ([self.boyBtn isEqual:btn]) {
        self.sex = @"1";
        self.boyBtn.selected = YES;
        self.boyBtn.userInteractionEnabled = NO;
        
        self.grilBtn.selected = NO;
        self.grilBtn.userInteractionEnabled = YES;
    }else {
        self.sex = @"0";
        self.boyBtn.selected = NO;
        self.boyBtn.userInteractionEnabled = YES;
        
        self.grilBtn.selected = YES;
        self.grilBtn.userInteractionEnabled = NO;
    }
}

- (void)birthdayBtnClick:(UIButton *)btn {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    @weakify(self);
//    [[MOFSPickerManager shareManger] showDatePickerWithTag:1 commitBlock:^(NSDate *date) {
//        @strongify(self);
//        NSString *dateString = [formatter stringFromDate:date];
//        [self.birthdayBtn setAttributedTitle:createAttString(dateString, 14,rgba(76, 74, 66, 1)) forState:UIControlStateNormal];
//    } cancelBlock:^{
//
//    }];
    
    NSString *selectDateString = [btn attributedTitleForState:UIControlStateNormal].string;
//
//    [[MOFSPickerManager shareManger] showDatePickerWithTag:1 firstDate:[formatter dateFromString:selectDateString] minDate:[NSDate dateWithTimeIntervalSince1970:0] maxDate:[NSDate date] datePickerMode:UIDatePickerModeDate commitBlock:^(NSDate * _Nonnull date) {
//            @strongify(self);
//            NSString *dateString = [formatter stringFromDate:date];
//            [self.birthdayBtn setAttributedTitle:createAttString(dateString, 14,rgba(76, 74, 66, 1)) forState:UIControlStateNormal];
//        } cancelBlock:^{
//
//
//        }];
    
    [[MOFSPickerManager shareManger].datePicker showWithTitle:nil commitTitle:@"确定" cancelTitle:@"取消" selectedDate:[formatter dateFromString:selectDateString] minDate:[NSDate dateWithTimeIntervalSince1970:0] maxDate:[NSDate date] datePickerMode:UIDatePickerModeDate commitBlock:^(NSDate * _Nullable date) {
            
        
        @strongify(self);
        NSString *dateString = [formatter stringFromDate:date];
        [self.birthdayBtn setAttributedTitle:createAttString(dateString, 14,rgba(76, 74, 66, 1)) forState:UIControlStateNormal];
        } cancelBlock:^{
            
        }];
//
}
- (void)saveBtnClick:(UIButton *)btn {
    if (self.nameTF.text.length > 40) {
        [SVProgressHUD showErrorWithStatus:@"姓名不能超过40个字"];
        return;
    }
    if ([self.nameTF.text containsEmoji]) {
        [SVProgressHUD showErrorWithStatus:@"姓名不能输入表情"];
        return;
    }
    if (self.phoneTF.text.length > 30) {
        [SVProgressHUD showErrorWithStatus:@"联系方式不能超过30个字"];
        return;
    }
    
    if (self.addressTF.text.length > 40) {
        [SVProgressHUD showErrorWithStatus:@"地址不能超过40个字"];
        return;
    }
    if ([self.addressTF.text containsEmoji]) {
        [SVProgressHUD showErrorWithStatus:@"地址不能输入表情"];
        return;
    }
    

    NSMutableDictionary *pDict = [[NSMutableDictionary alloc] init];
    if (self.iconBtn.selected) {
        UIImage *iconImg = [self.iconBtn imageForState:UIControlStateSelected];
        if (iconImg) {
            iconImg = [iconImg sd_resizedImageWithSize:CGSizeMake(100, 100/iconImg.size.width *iconImg.size.height) scaleMode:SDImageScaleModeAspectFill];
            NSString *keyString = [NSString stringWithFormat:@"Pictures/header/%@.jpg",nowTimeTimestamp()];
            [[MMLocalDataBManager sharedManager] addWithObjectKey:keyString updateData:UIImageJPEGRepresentation(iconImg, 1)];
            NSString *iconUrl = [NSString stringWithFormat:@"%@/%@",[[MMAutoUploadTool sharedManager] domain],keyString];
            [[SDImageCache sharedImageCache] storeImage:iconImg forKey: iconUrl completion:^{
                
            }];
            pDict[@"clientimg"] = iconUrl;
        }
    }


    

    pDict[@"mid"] = [SMGlobalModel share].mid;
    pDict[@"cname"] = self.nameTF.text;
    pDict[@"sex"] = self.sex;
    

    NSString *bstring = [self.birthdayBtn attributedTitleForState:UIControlStateNormal].string;
    if (![bstring isEqualToString:@"未填写"]) {
        pDict[@"birthday"] = bstring;
    }
    pDict[@"telphone"] = self.phoneTF.text;
    pDict[@"address"] = self.addressTF.text;

        pDict[@"areatxt"] = self.areatxt;
        pDict[@"areaprovince"] = self.areaprovince;
        pDict[@"areacity"] = self.areacity;
        pDict[@"arearegion"] = self.arearegion;


    if (self.clientModel.ID) {
        pDict[@"id"] = self.clientModel.ID;
    }

    @weakify(self);
    [self.view postFormDataWithUrl:@"/magnifier/client/saveOrUpdateClient" params:pDict success:^(NSDictionary * _Nonnull responseObject, JFResponseModel * _Nonnull JsonData) {
        @strongify(self);
        if ([JsonData.code isEqualToString:@"200"]) {
            if (self.clientModel.ID) {
                self.clientModel.cname = pDict[@"cname"];
                self.clientModel.sex = pDict[@"sex"];
                if ( pDict[@"clientimg"]) {
                    self.clientModel.clientimg = pDict[@"clientimg"];
                }
                
                if (![bstring isEqualToString:@"未填写"]) {
                    self.clientModel.birthday =
                    [NSString stringWithFormat:@"%@", ((NSDictionary *)JsonData.data)[@"birthday"] ];

                }
                self.clientModel.telphone =  pDict[@"telphone"];
                self.clientModel.address =  pDict[@"address"] ;
                self.clientModel.areatxt =   pDict[@"areatxt"] ;
                self.clientModel.areaprovince = pDict[@"areaprovince"] ;
                self.clientModel.areacity =   pDict[@"areacity"];
                self.clientModel.arearegion =  pDict[@"arearegion"];
                [self.navigationController popViewControllerAnimated:YES];
            }else {

                if (islinkDeviceWifi()) {
                    SMTakeImageViewController *vc = [[SMTakeImageViewController alloc] init];
                    vc.clinetModel = [SMClientListModel mj_objectWithKeyValues:JsonData.data];
                    [self.navigationController pushViewController:vc animated:YES];
                }else {
                    SMLinkDeviceView *linkView = [[SMLinkDeviceView alloc] init];
                    linkView.flishBlock = ^{
                        @strongify(self);
                        SMTakeImageViewController *vc = [[SMTakeImageViewController alloc] init];
                        vc.clinetModel = [SMClientListModel mj_objectWithKeyValues:JsonData.data];
                        [self.navigationController pushViewController:vc animated:YES];
                    };
                    [linkView wb_showFromSuperView: self.view];
                }
                
            }
        }
    }];

}

- (void)createViewWithNameArray:(NSArray *)nameArray firstTop:(CGFloat)firstTop{
  
    UIView *lastView = nil;
    for (int i = 0; i < nameArray.count; i++) {
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.attributedText = createAttString(nameArray[i], 15, rgba(76, 74, 66, 1));
        [self.view addSubview:nameLabel];
        [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            if (i == 0) {
                make.top.mas_equalTo(firstTop);
            }else {
                make.top.equalTo(lastView.mas_bottom).offset(18);
            };
            make.left.mas_equalTo(20);
        }];
        [self.labelArray addObject:nameLabel];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = rgba(229, 229, 229, 1);
        [self.view addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(20.5);
            make.right.mas_equalTo(-22);
            make.top.equalTo(nameLabel.mas_bottom).offset(17.5);
            make.height.mas_equalTo(0.5);
        }];
        lastView =lineView;
    }
}
@end
