//
//  PerfectInformationViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2017/2/9.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "PerfectInformationViewController.h"
#import "PerfectInformationTableViewCell.h"
#import "DateSelectedViewController.h"

@interface PerfectInformationViewController ()<UITableViewDelegate,UITableViewDataSource,ReturnTableviewcellIndexpathdelegate,UITextFieldDelegate>

@property (nonatomic,strong) NSArray *itemNameArray;
@property (nonatomic,strong) NSMutableArray *informationArray;

@end

@implementation PerfectInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PerfectInformationTableViewCell *informationCell = [tableView dequeueReusableCellWithIdentifier:@"PerfectInformationTableViewCell" forIndexPath:indexPath];
    informationCell.itemInputTextField.text = [BaseViewController isBlankString:self.informationArray[indexPath.section][indexPath.row]]?nil:self.informationArray[indexPath.section][indexPath.row];
    informationCell.itemNameLabel.text = self.itemNameArray[indexPath.section][indexPath.row];
    informationCell.itemInputTextField.placeholder = informationCell.itemNameLabel.text;
    [self textFieldIsEditing:indexPath withCell:informationCell];
    return informationCell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.informationArray[section];
    return array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.informationArray.count;
}

#pragma mark -是否可编辑
- (void)textFieldIsEditing:(NSIndexPath *)indexPath withCell:(PerfectInformationTableViewCell *)cell
{
    if (indexPath.section) {
        cell.itemInputTextField.userInteractionEnabled = YES;
        cell.itemNameLabel.textColor = [UIColor blackColor];
        cell.itemInputTextField.textColor = [UIColor blackColor];
        cell.itemInputTextField.tag = indexPath.row;
        cell.itemInputTextField.delegate = self;
        [self setUpSelectBox:cell];

    }else {
        cell.itemInputTextField.userInteractionEnabled = NO;
        cell.itemNameLabel.textColor = [UIColor grayColor];
        cell.itemInputTextField.textColor = [UIColor grayColor];
    }
}

#pragma mark -UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.informationArray[1][textField.tag] = textField.text;
    [self inputIsCompleted];
}

#pragma mark -设置选择框
- (void)setUpSelectBox:(PerfectInformationTableViewCell *)cell
{
    UITapGestureRecognizer *dataSelectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dateSelection)];
    UITapGestureRecognizer *genderSelectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(genderSelection:)];
    if ([cell.itemInputTextField.placeholder isEqualToString:@"生日"]) {
        [cell.itemInputTextField addGestureRecognizer:dataSelectTap];
    }else if ([cell.itemInputTextField.placeholder isEqualToString:@"性别"]) {
        [cell.itemInputTextField addGestureRecognizer:genderSelectTap];
    }else {
        [cell.itemInputTextField removeGestureRecognizer:dataSelectTap];
        [cell.itemInputTextField removeGestureRecognizer:genderSelectTap];
    }
}

#pragma mark -日期选择框
- (void)dateSelection
{
    WS(weakSelf);
    PerfectInformationTableViewCell *cell = [self.perfectInformationTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
    DateSelectedViewController *datevc = [[DateSelectedViewController alloc]init];
    [datevc setSelectedDateBlock:^(NSDate *selectedDate) {
        cell.itemInputTextField.text = [weakSelf dateAsString:selectedDate];
        weakSelf.informationArray[1][2] = cell.itemInputTextField.text;
        [weakSelf inputIsCompleted];
    }];
    datevc.preferredContentSize = CGSizeMake(300, 250);
    datevc.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = datevc.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = datevc.view;
    [self presentViewController:datevc animated:YES completion:nil];
}

#pragma mark -性别选择
- (void)genderSelection:(UITapGestureRecognizer *)tap
{
    PopoverViewController *popover = [[PopoverViewController alloc]init];
    popover.datasArray = @[@"男",@"女"];
    popover.delegate = self;
    popover.isString = YES;
    popover.contentSize = CGSizeMake(100, 100);
    popover.preferredContentSize = CGSizeMake(100, 100);
    popover.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *pop = popover.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionUp;
    pop.sourceView = popover.view;
    pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:tap.view];
    [self presentViewController:popover animated:YES completion:nil];
}

#pragma mark -ReturnTableviewcellIndexpathdelegate
- (void)returnCellindexpathwithrow:(NSString *)type withCellTitle:(NSString *)title withSelected:(NSInteger)selected
{
    PerfectInformationTableViewCell *cell = [self.perfectInformationTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
    cell.itemInputTextField.text = title;
    self.informationArray[1][1] = title;
    [self inputIsCompleted];
}

#pragma mark -时间转换NSDate转NSString
- (NSString*)dateAsString:(NSDate*)date {
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * timeString = [formatter stringFromDate:date];
    return timeString;
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.perfectInformationTableView.tableFooterView = [UIView new];
    self.title = @"个人资料";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(modifyshoppersInformation)];
    self.navigationItem.rightBarButtonItem.enabled = [Shoppersmanager manager].shoppers.employee.isComplete;
}

#pragma mark -判断输入是否完成
- (void)inputIsCompleted
{
    for (id object in self.informationArray[1]) {
        if ([BaseViewController isBlankString:object]) {
            return;
        }
    }
    [Shoppersmanager manager].shoppers.employee.isComplete = NO;
    self.navigationItem.rightBarButtonItem.enabled = YES;
}

#pragma mark -完成修改导购个人信息
- (void)modifyshoppersInformation
{
    if ([Shoppersmanager manager].shoppers.employee.isComplete) {
        [self dismissViewControllerAnimated:YES completion:nil];return;
    }
    if (![HENLENSONG isValidateMobile:self.informationArray[1][3]]) {
        [XBLoadingView showHUDViewWithText:@"手机号码格式不正确"];return;
    }
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    RsEmployeeRequest *employ = [[RsEmployeeRequest alloc]init];
    employ.employee = [Shoppersmanager manager].shoppers.employee;
    employ.employee.realName = self.informationArray[1][0];
    employ.employee.gender = self.informationArray[1][1];
    employ.employee.birthday = [NSString stringWithFormat:@"%@ 00:00:00",self.informationArray[1][2]];
    employ.employee.mobilePhone = self.informationArray[1][3];
    employ.employee.isComplete = YES;
    [HTTP networkRequestWithURL:SERVERREQUESTURL(MODITYshoppersINFORMATION)  withRequestType:ZERO withParameter:employ withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [XBLoadingView showHUDViewWithSuccessText:@"修改成功" completeBlock:^{
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
    }];
}

#pragma mark -lazy
- (NSMutableArray *)informationArray
{
    if (!_informationArray) {
        LoginResult *guide = [Shoppersmanager manager].shoppers;
        NSMutableArray *mutableArray1 = [NSMutableArray arrayWithObjects:[self disposeNil:guide.employee.userName],[self disposeNil:guide.employee.region],[self disposeNil:guide.employee.office],[self disposeNil:guide.employee.reseller],[self disposeNil:guide.employee.store], nil];
        NSMutableArray *mutableArray2 = [NSMutableArray arrayWithObjects:[self disposeNil:guide.employee.realName],[self disposeNil:guide.employee.gender],[self disposeNil:guide.employee.birthday],[self disposeNil:guide.employee.mobilePhone], nil];
        _informationArray = [NSMutableArray arrayWithObjects:mutableArray1,mutableArray2, nil];
    }
    return _informationArray;
}

- (NSArray *)itemNameArray
{
    if (!_itemNameArray) {
        _itemNameArray = @[
                           @[@"账户名",@"所属大区",@"所属办事处",@"所属经销商",@"所属店名",@"value"],
                           @[@"姓名",@"性别",@"生日",@"手机号"]];
    }
    return _itemNameArray;
}

#pragma mark -处理属性为空避免字典崩溃
- (id)disposeNil:(NSString *)string
{
    if ([BaseViewController isBlankString:string]) {
        return [NSNull null];
    }
    return [[string componentsSeparatedByString:@" "] firstObject];
}

@end
