//
//  NewPurchaseNoticeViewController.m
//  XFFruit
//
//  Created by mac on 15/8/16.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "NewPurchaseNoticeViewController.h"
#import "PurchaseNoticeViewController.h"
#import "SurveyCell.h"
#import "HPGrowingTextView.h"
#import "SeePurchaseNoticeViewController.h"
#import "ChosePersonViewController.h"
#import "SurveyUser.h"
#import "PurchaseNoticeCell.h"
#import "NoticeProductViewController.h"
#import "NoticeProduct.h"
#import "FinishTimeView.h"
#import "PurchaseBillProduct.h"
#define LeftMargin 15
#define LeftWidth 40
#define RightWidth 30
#define SpaceMargin 1
#define BtnHeight 44
#define TableHeight 46
#define CornerRadius 5
#define TitleSize 15
#define BtnSize 19
#define TotalHeight 432
#define KeyboardHeight 258
#define DateViewHeight 300
#define FootOfsetHeight 140
#define BottomViewHeight 60


typedef enum : NSUInteger {
    SaveTag = 8000,
    CommitTag,
} BtnTag;
@interface NewPurchaseNoticeViewController()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,HPGrowingTextViewDelegate,UIAlertViewDelegate,FinishTimeViewDelegate>
{
    NSString *_clickState;
    UITableView *_tableView;
    NSMutableArray *_dataArr;
    NSMutableArray *_shopeArr;
    UITextField *_titleField;
    UILabel *_personLabel;
    UILabel *_finishDateLabel;
    HPGrowingTextView *_noteTextView;
    NSIndexPath *selectedCellIndexPath;
    NSMutableArray *selectCellAry;
    UITableView *mingXiTableView;
    id uuidObject;
    id billNumberObject;
    NSNumber *versionObject;
    NSString *title;
    FinishTimeView *_startTimeView;
    
}
@property (nonatomic,strong)NSString *titleStr;
@property (nonatomic,strong)NSString *purchaseCodeStr;
@property (nonatomic,strong)NSString *purchaseNameStr;
@property (nonatomic,strong)NSString *purchaseUuidStr;
@property (nonatomic,strong)NSString *remarkStr;
@property (nonatomic,strong)NSString *finishDateStr;

@property (nonatomic,strong)UILabel *HeardLabel;
@property (nonatomic,strong)UILabel *FootLabel;
@property (nonatomic,strong)UIButton *addDetailedButton;
@property (nonatomic,strong)NSMutableArray *selectUsers;

@property (nonatomic,strong)NSString *purchaseNoticeUuid;


@end

@implementation NewPurchaseNoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
    //数据默认值
    uuidObject = [NSNull null];
    billNumberObject = [NSNull null];
    versionObject = [NSNumber numberWithInteger:0];
    if (self.purchaseNotice) {
        self.purchaseNoticeUuid = self.purchaseNotice.uuid;
        [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"];
                PurchaseNotice *purchaseNotice = [[PurchaseNotice alloc]init];
                [purchaseNotice setValuesForKeysWithDictionary:dictData];
                 strongSelf.purchaseNotice = purchaseNotice;
                [strongSelf prepareDataInCell];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"     无记录     "];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] getPurchaseNoticeDetailedWithPurchaseUuid:self.purchaseNoticeUuid success:succ failure:fail];
}
- (void)prepareDataInCell{
    if (self.purchaseNotice) {
        if (self.purchaseNotice.title.length > 0) {
            _titleField.text = self.purchaseNotice.title;
            self.titleStr = self.purchaseNotice.title;
        }
        if (self.purchaseNotice.purchaserName.length > 0) {
            _personLabel.text = self.purchaseNotice.purchaserName;
            _personLabel.textColor = GXF_CONTENT_COLOR;
            self.purchaseUuidStr = self.purchaseNotice.purchaserUuid;
            self.purchaseCodeStr = self.purchaseNotice.purchaserCode;
            self.purchaseNameStr = self.purchaseNotice.purchaserName;
            [self.selectUsers addObject:self.purchaseNotice.purchaserUuid];
        }
        if (self.purchaseNotice.finishDate) {
            if (self.purchaseNotice.finishDate.length > 15) {
                _finishDateLabel.text = [[IBTCommon checkString:self.purchaseNotice.finishDate]substringToIndex:16];
            }
            _finishDateLabel.textColor = GXF_CONTENT_COLOR;
            self.finishDateStr = [IBTCommon checkString:self.purchaseNotice.finishDate];
        }
        if (self.purchaseNotice.remark) {
            _noteTextView.text = self.purchaseNotice.remark;
            self.remarkStr = self.purchaseNotice.remark;
        }
    }
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *productDict in self.purchaseNotice.products) {
        NoticeProduct *billProduct = [[NoticeProduct alloc]init];
        [billProduct setValuesForKeysWithDictionary:productDict];
        [arr addObject:billProduct];
    }
    _shopeArr = arr;
    [mingXiTableView reloadData];
}



-(void)setupSubviews
{
    selectCellAry=[[NSMutableArray alloc]initWithCapacity:1000];
    self.selectUsers = [NSMutableArray array];

    _dataArr=[[NSMutableArray alloc]initWithObjects:@"标题:",@"采购员:",@"要求采购完成时间:",@"备注:", nil];
    _shopeArr=[[NSMutableArray alloc]init];
    self.view.backgroundColor  = XXFBgColor;
    
    _tableView = [[UITableView alloc]initWithFrame:(CGRectMake(0, LeftMargin,ScreenSize.width, ScreenSize.height/3)) style:(UITableViewStylePlain)];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.tag=1001;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    mingXiTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 2*LeftMargin+_tableView.frame.size.height, ScreenSize.width, ScreenSize.height-_tableView.height-ScreenSize.height/6 - 50)];
    mingXiTableView.backgroundColor = [UIColor whiteColor];
    mingXiTableView.tag=1002;
    mingXiTableView.delegate=self;
    mingXiTableView.dataSource=self;
    
    UIView *footView2=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, TableHeight)];
    footView2.backgroundColor=[UIColor clearColor];
    NSArray *ary=[NSArray arrayWithObjects:@"商品",@"包装规格",@"包装数量", nil];
    //    NSArray *ary=[NSArray arrayWithObjects: nil];
    CGFloat gipWidth = (ScreenSize.width-LeftWidth-RightWidth)/3;
    
    for (int i=0; i< ary.count;i++ ) {
        UILabel *lable=[[UILabel alloc]init];
        if (i==0) {
            lable.frame=CGRectMake(LeftWidth, 0, gipWidth,TableHeight);
        }
        if (i==1) {
            lable.frame=CGRectMake(LeftWidth+gipWidth+1, 0, gipWidth,TableHeight);
        }
        if (i==2) {
            lable.frame=CGRectMake(LeftWidth+2*gipWidth+2, 0, gipWidth,TableHeight);
        }
        
        //        UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(LeftWidth + (SpaceMargin + headWidth)*i,0, headWidth, 50)];
        lable.text=[ary objectAtIndex:i];
        lable.textColor=GXF_PLACEHOLDER_COLOR;
        lable.font = GXF_FIFTEENTEN_SIZE;
        [footView2 addSubview:lable];
    }
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(ScreenSize.width - LeftWidth - SpaceMargin, 0, LeftWidth, 40);
    [addBtn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [addBtn setTitleColor:GXF_PLACEHOLDER_COLOR forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addShopeDetailed) forControlEvents:UIControlEventTouchUpInside];
    addBtn.titleLabel.font = GXF_FIFTEENTEN_SIZE;
    [footView2 addSubview:addBtn];
    
    UIView *footView3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, TableHeight)];
    footView3.backgroundColor=[UIColor clearColor];
    self.addDetailedButton=[UIButton  buttonWithType: UIButtonTypeCustom];
    [self.addDetailedButton  setFrame:CGRectMake(0, 0, ScreenSize.width, TableHeight)];
    [self.addDetailedButton setTitle:@"+ 点击添加商品明细" forState:UIControlStateNormal];
    self.addDetailedButton.titleLabel.font = GXF_FIFTEENTEN_SIZE;
    [self.addDetailedButton addTarget:self action:@selector(addShopeDetailed) forControlEvents:UIControlEventTouchUpInside];
    [self.addDetailedButton setTitleColor:GXF_PLACEHOLDER_COLOR forState:UIControlStateNormal];
    self.FootLabel=[[UILabel alloc]initWithFrame:(CGRectMake(LeftMargin, footView3.size.height-1, footView3.size.width-2*LeftMargin, 1))];
    self.FootLabel.backgroundColor = HexColor(@"e5e5e5");
    self.FootLabel.font = FontSize(TitleSize);
    self.HeardLabel=[[UILabel alloc]initWithFrame:(CGRectMake(LeftMargin, 0, footView3.size.width-2*LeftMargin, 1))];
    self.HeardLabel.backgroundColor = HexColor(@"e5e5e5");
    self.HeardLabel.font = FontSize(TitleSize);
    //HexColor(@"e5e5e5")
    
    
    UIView *footView4 = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenSize.height - BottomViewHeight - 64, ScreenSize.width, BottomViewHeight)];
    UIButton *saveBtn =  [IBTCustomButtom creatButtonWithFrame:CGRectMake(15, 8, (ScreenSize.width - 15*3)/2, 44) target:self sel:@selector(btnClick:) tag:SaveTag image:nil title:@"保存" titleColor: [UIColor whiteColor] isCorner:YES corner:5 bgColor:HexColor(@"50bd62")];
    [footView4 addSubview:saveBtn];
    
    UIButton *commitBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(CGRectGetMaxX(saveBtn.frame) + 15, 8, (ScreenSize.width - 15*3)/2, 44) target:self sel:@selector(btnClick:) tag:CommitTag image:nil title:@"提交" titleColor: [UIColor whiteColor] isCorner:YES corner:5 bgColor:HexColor(@"f69100")];
    [footView4 addSubview:commitBtn];
    
    [self.view addSubview:footView4];
    [footView3 addSubview:self.addDetailedButton];
    [footView3 addSubview:self.HeardLabel];
    [footView3 addSubview:self.FootLabel];
    
    mingXiTableView.tableFooterView = footView3;
    mingXiTableView.tableHeaderView=footView2;
    [self.view addSubview:_tableView];
    [self.view addSubview:mingXiTableView];
    [self.view addSubview:footView4];
    
}

#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_tableView]) {
        return 1;
    }else if ([tableView isEqual:mingXiTableView])
    {
        return 1;
    }
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_tableView]) {
        return _dataArr.count;
    }else if ([tableView isEqual:mingXiTableView])
    {
        return _shopeArr.count;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_tableView]) {
        
        static NSString *cellID = @"SurveyCell";
        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;
            }
            cell.titleLabel.width = 130;
            [self createViewInCell:cell indexPath:indexPath];
        }
        [cell setTitleStr:_dataArr[indexPath.row]];
        return cell;
    }else if ([tableView isEqual:mingXiTableView])
    {
        
        static NSString *CellID = @"PurchaseNoticeCell";
        PurchaseNoticeCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellID];
        if (Cell == nil) {
            Cell = [[PurchaseNoticeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            Cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [self  showShopDetail:Cell indexPath:indexPath];
        if ([self comperIndexpath:indexPath]) {
            Cell.arrowView.image = [UIImage imageNamed:@"arrowdown"];
            Cell.backgroundColor=XXFBgColor;
            Cell.subSview.hidden=NO;
        }else
        {
            Cell.arrowView.image = [UIImage imageNamed:@"arrowright"];
            Cell.backgroundColor=[UIColor whiteColor];
            Cell.subSview.hidden=YES;
            
        }
        Cell.button.tag=indexPath.row;
        [Cell.button addTarget:self action:@selector(didtoucher:) forControlEvents:UIControlEventTouchUpInside];
        return Cell;
        
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableView]) {
        return TableHeight;
    }else if ([tableView isEqual:mingXiTableView])
    {
        if ([self  comperIndexpath:indexPath]) {
            return TableHeight*3;
        }else
        {
            return TableHeight;
        }
        
    }
    return TableHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableView]) {
        
        if(indexPath.row == 1){
            ChosePersonViewController *cvc = [ChosePersonViewController new];
            if (self.selectUsers.count > 0) {
                cvc.selectArr = self.selectUsers;
            }
            cvc.choseBaseInfo = ^(NSArray *users){
                if (users.count > 0) {
                    if (self.selectUsers.count > 0) {
                        [self.selectUsers removeAllObjects];
                    }
                    SurveyUser *user = users[0];
                    _personLabel.text = user.userName;
                    _personLabel.textColor = GXF_CONTENT_COLOR;
                    self.purchaseNameStr = user.userName;
                    self.purchaseCodeStr = user.userCode;
                    self.purchaseUuidStr = user.userUuid;
                    [self.selectUsers addObject:user.userUuid];
                }
            };
            cvc.isMoreChose = NO;
            [self PushViewController:cvc animated:YES];
        }else if(indexPath.row == 2){
            [self startDatePickView];
        }
    }else if ([tableView isEqual:mingXiTableView])
    {
        PurchaseNoticeCell *Cell=(PurchaseNoticeCell*)[mingXiTableView cellForRowAtIndexPath:indexPath ];
        if (![self comperIndexpath:indexPath]) {
            Cell.isSelected=YES;
            Cell.subSview.hidden = NO;
            [selectCellAry addObject:indexPath];
        }else{
            Cell.isSelected=NO;
            Cell.subSview.hidden = YES;
            [selectCellAry removeObject:indexPath];
        }
        selectedCellIndexPath = indexPath;
        [mingXiTableView reloadData];
    }
}


-  (void)createViewInCell:(SurveyCell *)cell indexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        _titleField = [[UITextField alloc] initWithFrame:CGRectMake(cell.titleLabel.right, 0, ScreenSize.width - cell.titleLabel.width - LeftMargin*2-15, TableHeight)];
        _titleField.textAlignment = NSTextAlignmentRight;
        _titleField.textColor = GXF_CONTENT_COLOR;
        _titleField.placeholder = @"输入采购通知单标题";
        _titleField.font = FontSize(15);
        _titleField.returnKeyType = UIReturnKeyDone;
        _titleField.delegate = self;
        title=_titleField.text;
        [cell.contentView addSubview:_titleField];
        
    }else if (indexPath.row == _dataArr.count -1){
        _noteTextView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(cell.titleLabel.right, 0, ScreenSize.width - cell.titleLabel.width - LeftMargin*2-15, TableHeight)];
        _noteTextView.contentInset = UIEdgeInsetsMake(5, 5, 5, 0);
        _noteTextView.minNumberOfLines = 1;
        _noteTextView.maxNumberOfLines = 1;
        _noteTextView.isScrollable = YES;
        _noteTextView.font = FontSize(15);
        _noteTextView.textAlignment = NSTextAlignmentRight;
        _noteTextView.delegate = self;
        _noteTextView.returnKeyType = UIReturnKeyDone;
        _noteTextView.placeholder = @"输入备注内容";
        [cell.contentView addSubview:_noteTextView];
//        CGRect lineFrame =  cell.lineLabel.frame;
//        lineFrame.origin.y = TableHeight*2-1;
//        cell.lineLabel.frame = lineFrame;
    }else{
        UILabel *contentLabel = [[UILabel alloc]initWithFrame:(CGRectMake(cell.titleLabel.right, 0, ScreenSize.width - cell.titleLabel.width - LeftMargin*2-15, TableHeight))];
        contentLabel.textAlignment= NSTextAlignmentRight;
        contentLabel.textColor = GXF_PLACEHOLDER_COLOR;
        contentLabel.font = FontSize(TitleSize);
        [cell.contentView addSubview:contentLabel];
        if (indexPath.row == 1) {
            contentLabel.text = @"选择采购员";
            _personLabel = contentLabel;
        }else if(indexPath.row == 2){
            contentLabel.text = @"选择要求完成日期";
            _finishDateLabel = contentLabel;
        }
    }
}
-(BOOL)comperIndexpath:(NSIndexPath *)indexPath
{
    for (NSIndexPath *path in selectCellAry) {
        if (path.row == indexPath.row) {
            return YES;
        }
    }
    return NO;
}

//添加商品明细
-(void)addShopeDetailed
{
    NoticeProductViewController *nvc = [NoticeProductViewController new];
    nvc.navTitle = @"添加商品明细";
    nvc.choseNoticeProduct = ^(NoticeProduct *product,NSIndexPath *indexPath){
        if (product) {
            [_shopeArr addObject:product];
            [mingXiTableView reloadData];
        }
    };
    
    [self PushViewController:nvc animated:YES];
}
-(void)showShopDetail:(PurchaseNoticeCell*)Cell indexPath:(NSIndexPath *)indexPath
{
    NoticeProduct *noticeProduct=[_shopeArr objectAtIndex:indexPath.row];
    Cell.SpLabel.text=noticeProduct.productName;//商品
    Cell.shopeName.text=[NSString stringWithFormat:@"%@[%@]",noticeProduct.productName,noticeProduct.productCode];
    Cell.BzggLabel.text= [NSString stringWithFormat:@"1*%@%@",noticeProduct.qpc,noticeProduct.baseUnit];//包装规格
    Cell.packageUnit.text=noticeProduct.packUnit;//包装单位
    Cell.BzslLabel.text=[NSString stringWithFormat:@"%@%@",noticeProduct.qpcQuantity,noticeProduct.packUnit];//包装数量
    Cell.packageQuantity.text=[NSString stringWithFormat:@"%@%@",noticeProduct.qpcQuantity,noticeProduct.packUnit];
    Cell.packageSpecification.text=[NSString stringWithFormat:@"1*%@%@",noticeProduct.qpc,noticeProduct.baseUnit];//包装规格
    Cell.foundationQuantity.text= [NSString stringWithFormat:@"%@%@",noticeProduct.quantity,noticeProduct.baseUnit];//基础数量
    Cell.remark.text=noticeProduct.remark;//备注
    
}
//编辑
- (void)didtoucher:(UIButton*)button
{
    NoticeProductViewController *nvc = [NoticeProductViewController new];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
    NoticeProduct *shopDetail=[_shopeArr objectAtIndex:button.tag];

    if (indexPath) {
        nvc.navTitle = @"编辑商品明细";
        nvc.indexPath = indexPath;
        nvc.noticeProduct = shopDetail;
    }
    nvc.choseNoticeProduct = ^(NoticeProduct *fee,NSIndexPath *indexPath){
        if (fee) {
            [_shopeArr replaceObjectAtIndex:indexPath.row withObject:fee];
            [mingXiTableView reloadData];

        }
    };
    nvc.deleteNoticeProduct = ^(NoticeProduct *fee,NSIndexPath *indexPath){
        if (fee) {
            [_shopeArr removeObjectAtIndex:indexPath.row];
            [mingXiTableView reloadData];

        }
    };

    [self PushViewController:nvc animated:YES];
}
#pragma mark delegate
- (BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView{
    [_noteTextView resignFirstResponder];
    return YES;
}
- (void)keyboardHidden{
    [_titleField resignFirstResponder];
    [_noteTextView resignFirstResponder];
}
- (void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case SaveTag:
        {
            if ([self checkSurvey]) {
                _clickState = PURCHASENOTICE_STATE_INITIAL;
                [self saveSurvey:PURCHASENOTICE_STATE_INITIAL message:@"正在保存..."];
            }
        }
            break;
        case CommitTag:
        {
            if ([self checkSurvey]) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认提交" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                alertView.delegate = self;
                [alertView show];
            }
        }
            break;
        default:
            break;
    }
}
- (BOOL)checkSurvey{
    self.titleStr = _titleField.text;
    self.remarkStr = _noteTextView.text;
    if ( self.titleStr.length==0) {
        ShowMessage(@"采购通知单标题不能为空");
        return NO;
    }
    if (_personLabel.text.length == 0 ) {
        ShowMessage(@"采购员不能为空");
        return NO;
    }
    if (_shopeArr.count==0) {
        ShowMessage(@"商品明细不能为空");
        return NO;
    }
    for (NoticeProduct *billProduct in _shopeArr) {
        if ([billProduct.quantity integerValue] <= 0 || [billProduct.qpcQuantity integerValue] <= 0) {
            ShowMessage(@"有数量等于0的商品明细，请编辑后保存");
            return NO;
        }
    }
    return YES;
}
- (void)startDatePickView{
    if (!_startTimeView) {
        NSString *currentStr  = @"";
        if ([_finishDateLabel.text isEqualToString:@"选择要求完成日期"] || _finishDateLabel.text.length < 1) {
            currentStr = [IBTCommon stringFromDateWithFormat:[NSDate date] format:@"yyyy-MM-dd HH:mm"];
        }else{
            currentStr = _finishDateLabel.text;
        }
        
        _startTimeView = [[FinishTimeView alloc] initWithFrame:CGRectMake(0, ScreenSize.height, ScreenSize.width, ScreenSize.height - 64) withDate:currentStr];
        _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:(NSString *)time{
    
    _finishDateLabel.textColor = GXF_CONTENT_COLOR;
    _finishDateLabel.text = time;
    self.finishDateStr = time;
    // 关闭选择器
    [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;
    }];
}


- (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]];
                    //成功之后在次请求详情数据
                    self.purchaseNoticeUuid = uuidS;
                    [self getDataFromServer];
                    
                }else{//提交成功
                    PurchaseNoticeViewController *svc = [PurchaseNoticeViewController new];
                    svc.title = @"查看采购通知单";
                    [self PushViewController:svc animated:YES];
                }
            }else{
                [IBTLoadingView showTips:message];
            }
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    
    if(self.purchaseNotice.uuid.length > 0 && uuidObject == [NSNull null]){
        uuidObject = self.purchaseNotice.uuid;
    }
    if (self.purchaseNotice.billnumber > 0 && billNumberObject == [NSNull null]) {
        billNumberObject = self.purchaseNotice.billnumber;
    }
    if (self.purchaseNotice && [versionObject integerValue] == 0) {
        versionObject = self.purchaseNotice.version;
    }
    NSMutableArray *billProducts = [NSMutableArray array];
    for (NoticeProduct *product in _shopeArr) {
        [billProducts  addObject:[product dictForCommit]];
        }

    NSDictionary *dict = @{@"uuid":uuidObject,//唯一标识
                           @"billnumber":billNumberObject,
                           @"version":versionObject,
                           @"title":[IBTCommon checkString:self.titleStr],
                           @"state":[IBTCommon checkString:state],
                           @"purchaserUuid":[IBTCommon checkString:self.purchaseUuidStr],
                           @"purchaserCode":[IBTCommon checkString:self.purchaseCodeStr],
                           @"purchaserName":[IBTCommon checkString:self.purchaseNameStr],
                           @"finishDate":[IBTCommon checkString:self.finishDateStr],
                           @"remark":[IBTCommon checkString:self.remarkStr],
                           @"products":billProducts};
    [IBTLoadingView showProgressLabel:msg];
    [[ICRHTTPController sharedController] savePurchaseNoticeWithData:dict success:succ failure:fail];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        _clickState = PURCHASENOTICE_STATE_NOTACCEPTED;
         [self saveSurvey:PURCHASENOTICE_STATE_NOTACCEPTED message:@"正在提交..."];
    }
}

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


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

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
