//
//  NewSurveyViewController.m
//  XFFurit
//
//  Created by 陈俊俊 on 15/8/1.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//  新建行情调研



#import "NewSurveyViewController.h"
#import "SurveyCell.h"
#import "SurveyViewController.h"
#import "HPGrowingTextView.h"
#import "StartTimeView.h"
#import "ChosePersonViewController.h"
#import "ChooseProductViewController.h"
#import "SurveyUser.h"
#import "Survey.h"
#import "Product.h"
#define LeftMargin 15
#define BtnHeight 44
#define TableRowHeight 46
#define CornerRadius 5
#define BtnSize 19
#define TotalHeight 432
#define KeyboardHeight 258
#define DateViewHeight 300
typedef enum : NSUInteger {
    SaveTag = 2000,
    CommitTag,
} BtnTag;

@interface NewSurveyViewController ()<UITableViewDataSource,UITableViewDelegate,HPGrowingTextViewDelegate,UITextFieldDelegate,StartTimeViewDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArr;
    UITextField *_titleField;
    UILabel *_productLabel;
    UILabel *_startDateLabel;
    UILabel *_endDateLabel;
    UILabel *_personLabel;
    HPGrowingTextView *_noteTextView;
    UIDatePicker *_timePicker;
    BOOL _isClickStart;
    StartTimeView *_startTimeView;
    id uuidObject;
    id billNumberObject;
    NSNumber *versionObject;
    NSString *_clickState;
}
@property (nonatomic,strong)NSString *titleStr;
@property (nonatomic,strong)NSString *productCodeStr;
@property (nonatomic,strong)NSString *productNameStr;
@property (nonatomic,strong)NSString *productUuidStr;
@property (nonatomic,strong)NSString *beginDateStr;
@property (nonatomic,strong)NSString *endDateStr;
@property (nonatomic,strong)NSString *remarkStr;
@property (nonatomic,strong)NSMutableArray *users;

@end

@implementation NewSurveyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.navTitle;
    [self initData];
    [self createTableView];
    if (self.survey) {
        [self getDataFromServer];
    }
}
- (void)getDataFromServer{
    __weak typeof(self)weakSelf = self;

    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message  = data[@"message"] ;
            if (success == 1) {
                NSDictionary *dictData = data[@"data"];
                Survey *survey = [[Survey alloc]init];
                [survey setValuesForKeysWithDictionary:dictData];
                 strongSelf.survey = survey;

                [strongSelf preferDataInPersonLabel];
            }else{
                [IBTLoadingView showTips:message];
            }
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] getResultWithSurveyUuid:self.survey.uuid success:succ failure:fail];
}


- (void)initData{

    _dataArr = [NSMutableArray array];
    self.users = [NSMutableArray array];
    [_dataArr addObject:@"标题"];
    [_dataArr addObject:@"商品"];
    [_dataArr addObject:@"开始日期"];
    [_dataArr addObject:@"结束日期"];
    [_dataArr addObject:@"调研人员"];
    [_dataArr addObject:@"备注"];
    uuidObject = [NSNull null];
    billNumberObject  = [NSNull null];
    versionObject = [NSNumber numberWithInt:0];
}

- (void)createTableView
{
    self.view.backgroundColor  = XXFBgColor;

    _tableView = [[UITableView alloc]initWithFrame:(CGRectMake(0, LeftMargin,ScreenSize.width, ScreenSize.height - 64 - LeftMargin)) style:(UITableViewStylePlain)];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.bounces = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 50)];
    
    UIButton *saveBtn =  [IBTCustomButtom creatButtonWithFrame:CGRectMake(LeftMargin, 10, (ScreenSize.width - LeftMargin*3)/2, BtnHeight) target:self sel:@selector(btnClick:) tag:SaveTag image:nil title:@"保存" titleColor: [UIColor whiteColor] isCorner:YES corner:CornerRadius bgColor:GXF_SAVE_COLOR];
    [footView addSubview:saveBtn];
    
    UIButton *commitBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(saveBtn.frame.origin.x + saveBtn.frame.size.width + LeftMargin, 10, (ScreenSize.width - LeftMargin*3)/2, BtnHeight) target:self sel:@selector(btnClick:) tag:CommitTag image:nil title:@"提交" titleColor: [UIColor whiteColor] isCorner:YES corner:CornerRadius bgColor:GXF_COMMIT_COLOR];
    [footView addSubview:commitBtn];
    
    _tableView.tableFooterView = footView;
    [self.view addSubview:_tableView];
}

#pragma mark - 按钮点击事件
- (void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case SaveTag:
        {
            if ([self checkSurvey]) {
                _clickState = @"initial";
                [self saveSurvey:@"initial" message:@"正在保存..."];
            }
        }
            break;
        case CommitTag:
        {
            if ([self checkSurvey]) {
                _clickState = @"submitted";
                [self saveSurvey:@"submitted" message:@"正在提交..."];
            }
        }
            break;
        default:
            break;
    }
}
- (BOOL)checkSurvey{
    self.titleStr = _titleField.text;
    self.remarkStr = _noteTextView.text;
    if (self.titleStr.length == 0 ) {
        ShowMessage(@"调研标题不能为空");
        return NO;
    }
    if (self.productUuidStr.length == 0 || self.productNameStr.length == 0|| self.productCodeStr.length == 0 ) {
        ShowMessage(@"调研商品不能为空");
        return NO;
    }
    if (self.beginDateStr.length == 0) {
        ShowMessage(@"调研开始日期不能为空");
        return NO;
    }
    if (self.endDateStr.length == 0) {
        ShowMessage(@"调研结束日期不能为空");
        return NO;
    }
    if (self.users.count <=0) {
        ShowMessage(@"调研人员不能为空");
        return NO;
    }
    if ([IBTCommon compareDate:self.beginDateStr withDate:self.endDateStr] < 0) {
        ShowMessage(@"开始日期不能小于结束日期");
        return NO;
    }
    
    return YES;
}


#pragma mark - 保存
- (void)saveSurvey:(NSString *)state message:(NSString *)msg
{
    //保存
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message = data[@"message"];
            if (success == 1) {
                //成功
                if ([state isEqualToString:@"initial"]) {//保存成功
                    NSString *uuidS = data[@"data"][@"uuid"];
                    NSString *billNumberS = data[@"data"][@"billNumber"];
                    NSNumber *versionN = data[@"data"][@"version"];
                    uuidObject = uuidS;
                    billNumberObject = billNumberS;
                    versionObject = versionN;
                    [IBTLoadingView showTips:[NSString stringWithFormat:@"当前单据%@已保存成功",billNumberS]];
                }else{//提交成功
                    SurveyViewController *svc = [SurveyViewController new];
                    [self PushViewController:svc animated:YES];
                }
            }else{
                [IBTLoadingView showTips:message];
            }
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    
    if(self.survey.uuid.length > 0 && uuidObject == [NSNull null]){
        uuidObject = self.survey.uuid;
    }
    if (self.survey.billNumber > 0 && billNumberObject == [NSNull null]) {
        billNumberObject = self.survey.billNumber;
    }
    if (self.survey && [versionObject integerValue] == 0) {
        versionObject = self.survey.version;
    }
    NSDictionary *dict = @{@"uuid":uuidObject,
                           @"version":versionObject,
                           @"billnumber":billNumberObject,
                           @"title":[IBTCommon checkString:self.titleStr],
                           @"state":state,
                           @"productUuid":[IBTCommon checkString:self.productUuidStr],
                           @"productCode":[IBTCommon checkString:self.productCodeStr],
                           @"productName":[IBTCommon checkString:self.productNameStr],
                           @"beginDate":[IBTCommon checkString:self.beginDateStr],
                           @"endDate":[IBTCommon checkString:self.endDateStr],
                           @"remark":[IBTCommon checkString:self.remarkStr],
                           @"users":self.users};
    [IBTLoadingView showProgressLabel:msg];    
    [[ICRHTTPController sharedController] saveSurveyWithAuthenticode:dict success:succ failure:fail];
}

#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    SurveyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[SurveyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row >0 && indexPath.row < _dataArr.count - 1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        [self createViewInCell:cell indexPath:indexPath];
    }
    [cell setTitleStr:_dataArr[indexPath.row]];
    return cell;
}

-  (void)createViewInCell:(SurveyCell *)cell indexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        _titleField = [[UITextField alloc] initWithFrame:CGRectMake(100+LeftMargin, 0, ScreenSize.width - 100 - LeftMargin*2-15, TableRowHeight)];
        _titleField.textAlignment = NSTextAlignmentRight;
        _titleField.textColor = GXF_CONTENT_COLOR;
        _titleField.placeholder = @"输入调研标题";
        _titleField.font = GXF_FIFTEENTEN_SIZE;
        _titleField.returnKeyType = UIReturnKeyDone;
        _titleField.delegate = self;
        [cell.contentView addSubview:_titleField];
    }else if (indexPath.row == _dataArr.count -1){
        _noteTextView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(100+LeftMargin, 0, ScreenSize.width - 100 - LeftMargin*2-15, TableRowHeight)];
        _noteTextView.contentInset = UIEdgeInsetsMake(5, 5, 5, 0);
        _noteTextView.minNumberOfLines = 1;
        _noteTextView.maxNumberOfLines = 4;
        _noteTextView.font = GXF_FIFTEENTEN_SIZE;
        _noteTextView.textAlignment = NSTextAlignmentRight;
        _noteTextView.delegate = self;
        _noteTextView.returnKeyType = UIReturnKeyDone;
        _noteTextView.placeholder = @"输入备注内容";
        [cell.contentView addSubview:_noteTextView];
       
        CGRect lineFrame =  cell.lineLabel.frame;
        lineFrame.origin.y = TableRowHeight*2-1;
        cell.lineLabel.frame = lineFrame;
    }else{
        UILabel *contentLabel = [[UILabel alloc]initWithFrame:(CGRectMake(100+LeftMargin, 0, ScreenSize.width - 100 - LeftMargin*2-15, TableRowHeight))];
        contentLabel.textAlignment= NSTextAlignmentRight;
        contentLabel.textColor = GXF_PLACEHOLDER_COLOR;
        contentLabel.font = GXF_FIFTEENTEN_SIZE;
        [cell.contentView addSubview:contentLabel];
        if (indexPath.row == 1) {
            contentLabel.text = @"选择商品";
            _productLabel = contentLabel;
        }else if(indexPath.row == 2){
            contentLabel.text = @"选择日期";
            _startDateLabel = contentLabel;
        }else if(indexPath.row == 3){
            contentLabel.text = @"选择日期";
            _endDateLabel = contentLabel;
        }else if(indexPath.row == 4){
            contentLabel.text = @"选择调研人员";
            _personLabel = contentLabel;
        }
    }
}
- (void)preferDataInPersonLabel{
    if (self.survey) {
        _titleField.text = [IBTCommon checkString:self.survey.title];
        self.titleStr = [IBTCommon checkString:self.survey.title];
    }
    if (self.survey) {
        if (self.survey.endDate.length > 9) {
            _endDateLabel.text = [[IBTCommon checkString:self.survey.endDate]substringToIndex:10];
        }
        _endDateLabel.textColor = GXF_CONTENT_COLOR;
        self.endDateStr = [IBTCommon checkString:self.survey.endDate];
    }

    if (self.survey) {
        if (self.survey.users.count > 0) {
            NSString *personStr = @"";
            for (NSDictionary * userDict in self.survey.users) {
                
                SurveyUser *surveyUser = [[SurveyUser alloc]init];
                [surveyUser setValuesForKeysWithDictionary:userDict];
                if (personStr.length == 0) {
                    personStr = [personStr stringByAppendingFormat:@"%@",surveyUser.userName];
                }else{
                    personStr = [personStr stringByAppendingFormat:@"、%@",surveyUser.userName];
                }
            }
            _personLabel.text = personStr;
            _personLabel.textColor = GXF_CONTENT_COLOR;
        }
        if (self.users > 0) {
            [self.users addObjectsFromArray:self.survey.users];
        }
    }
    if (self.survey) {
        if (self.survey.beginDate.length > 9) {
            _startDateLabel.text = [[IBTCommon checkString:self.survey.beginDate]substringToIndex:10];
        }
        _startDateLabel.textColor = GXF_CONTENT_COLOR;
        self.beginDateStr =[IBTCommon checkString:self.survey.beginDate];
        
    }
    if (self.survey) {
        _productLabel.text = [NSString stringWithFormat:@"%@[%@]",[IBTCommon checkString:self.survey.productName],[IBTCommon checkString:self.survey.productCode]];
        _productLabel.textColor = GXF_CONTENT_COLOR;
        self.productCodeStr = [IBTCommon checkString:self.survey.productCode];
        self.productNameStr = [IBTCommon checkString:self.survey.productName];
        self.productUuidStr = [IBTCommon checkString:self.survey.productUuid];
    }

    if (self.survey) {
        _noteTextView.text =  [IBTCommon checkString:self.survey.remark];
        self.remarkStr = [IBTCommon checkString:self.survey.remark];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 5){
        return TableRowHeight*2;
    }else{
        return TableRowHeight;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2 || indexPath.row == 3) {
        [self keyboardHidden];
        if (indexPath.row == 2) {
            _isClickStart = YES;
        }else{
            _isClickStart = NO;
        }
        [self startDatePickView];
    }else if(indexPath.row == 4){
        ChosePersonViewController *cvc = [ChosePersonViewController new];
        cvc.choseBaseInfo = ^(NSArray *users){
            if(users.count > 0){
                NSString *textStr = @"";
                if (self.users.count > 0) {
                    [self.users removeAllObjects];
                }
                for (SurveyUser *user in users) {
                    if (textStr.length == 0) {
                        textStr = [textStr stringByAppendingFormat:@"%@",user.userName];
                    }else {
                        textStr = [textStr stringByAppendingFormat:@"、%@",user.userName];
                    }
                    [self.users addObject:[user dictForCommit]];
                }
                _personLabel.text = textStr;
                _personLabel.textColor = GXF_CONTENT_COLOR;
            }
        };
        cvc.isMoreChose = YES;
        [self PushViewController:cvc animated:YES];
    }else  if(indexPath.row == 1){
        ChooseProductViewController *cvc = [ChooseProductViewController new];
    
        cvc.choseBaseInfo = ^(NSArray *products){
            Product *product = products[0];
            _productLabel.text = [NSString stringWithFormat:@"%@[%@]",product.name,product.code];
            _productLabel.textColor = GXF_CONTENT_COLOR;
            self.productNameStr = product.name;
            self.productUuidStr = product.uuid;
            self.productCodeStr = product.code;
        };
        cvc.isMoreChose = NO;
        [self PushViewController:cvc animated:YES];
    }
}

- (void)startDatePickView{
    if (!_startTimeView) {
        _startTimeView = [[StartTimeView alloc] initWithFrame:CGRectMake(0, ScreenSize.height, ScreenSize.width, ScreenSize.height - 64)];
        _startTimeView.delegate = self;
        _startTimeView.backgroundColor        = RGBA(0, 0, 0 ,0.5);
        [self.view addSubview:_startTimeView];
        
        [UIView animateWithDuration:0.15 animations:^{
            CGRect startFrame =  _startTimeView.frame;
            startFrame.origin.y =  0;
            _startTimeView.frame = startFrame;
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void)cancelTimeView{
    [self clearDatePickView];
}
- (void)okTimeView:(NSDate *)time{
    if (_isClickStart) {
        _startDateLabel.textColor = GXF_CONTENT_COLOR;
        _startDateLabel.text = [IBTCommon stringFromDate:time];
        self.beginDateStr = [time httpParameterString];
    }else{
        _endDateLabel.textColor = GXF_CONTENT_COLOR;
        _endDateLabel.text = [IBTCommon stringFromDate:time];
        self.endDateStr = [time httpParameterString];
    }
    // 关闭选择器
    [self clearDatePickView];
}
#pragma mark - 取消
- (void)clearDatePickView{
    [UIView animateWithDuration:0.15 animations:^{
        CGRect startFrame =  _startTimeView.frame;
        startFrame.origin.y = ScreenSize.height;
        _startTimeView.frame = startFrame;
    } completion:^(BOOL finished) {
        [_startTimeView removeFromSuperview];
        _startTimeView = nil;
    }];
}
#pragma mark delegate
- (BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView{
    [_noteTextView resignFirstResponder];
    return YES;
}

- (void)keyboardHidden{
    [_titleField resignFirstResponder];
    [_noteTextView resignFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(self.survey && [_clickState isEqualToString:@"initial"]){
        [ICRUserUtil sharedInstance].needFresh = YES;
    }
}

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