//
//  WriteFeedbackViewController.m
//  XFFruit
//  填写行情反馈
//  Created by freecui on 15/8/20.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//



#import "WriteFeedbackViewController.h"

#import "HGPhWViewController.h"
#import "ZYQAssetPickerController.h"
#import "IBTImagePicker.h"
#import "SurveyResult.h"
#import "XFDB.h"
#import "XFPhoto.h"
@interface WriteFeedbackViewController ()<ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>



#define IBT_DEFAULT_CELL_HEIGHT          (44.0f)
#define BTN_PADDING  20
#define BOTTOM_BTN_WIDTH self.view.width - BTN_PADDING*2 //只有一个按钮时的长度
#define BTN_HEIGHT 40


@property (strong, nonatomic) IBTTableViewInfo *tableViewInfo;
@property (strong, nonatomic) NSString *imgName;
@property (strong, nonatomic) HGPhWViewController *hgPhVC;
@property (strong, nonatomic) IBTImagePicker *m_imagePicker;
@property (strong, nonatomic) UIActionSheet *m_actionSheet;
@property (strong, nonatomic) NSMutableArray *imgesMuArr;
@property (strong, nonatomic) SurveyResult *surveyResult;
@property (strong, nonatomic) UIImageView *headImageView;
@property (nonatomic, strong) UIImageView *noImageHeadView;
//@property (strong, nonatomic) NSDictionary *surveyResultDict;
//@property (strong, nonatomic) HGPhWViewController *hgphVC;

typedef NS_ENUM(NSUInteger, feedbackCellInfo){
    kfeedbackCellPlace = 0,
    kfeedbackCellPrice,
    kfeedbackCellCapacity,
    kfeedbackCellQulity,
    kfeedbackCellRemark
};

@end

@implementation WriteFeedbackViewController


- (instancetype)initWithImgName:(NSString *)imgName {
    self = [super init];
    if (!self) {
        return nil;
    }
    self.imgName = imgName;
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"填写行情反馈";
    
    [self initData];
    [self initSubviews];
   
}
- (void)viewDidAppear:(BOOL)animated {
    
    
    if (_hgPhVC) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imgFiles:) name:kimgsFiles object:_hgPhVC];

    } else {
        return;
    }
    
}
- (void)imgFiles:(NSNotification *)notification {
    //HGPhWViewController *h
}
- (void)initData {
    
    self.imgesMuArr = [NSMutableArray array];

    void (^succ)(id) = ^(id data){
    
    };
    void (^fail)(id) = ^(id data){
    
    };
    [[ICRHTTPController sharedController] getResultsWithUuid:_surveyUuid
                                                     success:succ
                                                     failure:fail];
    
#ifdef DEBUG
//    self.surveyResult = [[SurveyResult alloc]init];
//    self.surveyResult.unit = @"南汇8424西瓜调研情况";
//    self.surveyResult.place = @"上海徐汇iOS";
//    self.surveyResult.price = @"26";
//    self.surveyResult.capacity = @"250";
//    self.surveyResult.quality = @"优质";
//    self.surveyResult.userName = @"张三";
//    self.surveyResult.feedbackTime = @"2015-04-05 12:04:06";
//    self.surveyResult.reMark = @"今天工作人员效率很高";
#endif
 

}

- (void)initSubviews {
    [self buildPhoto];
    [self buildContent];
    [self buildBottomButton];
    
}

- (void)buildPhoto {
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height * 0.4)];
    backView.backgroundColor =  HexColor(@"7ebf74");//ICR_TABBAR_TINT_COLOR;
    [self.view addSubview:backView];

    UIImageView *imgV = [[UIImageView alloc]init];
    imgV.userInteractionEnabled = YES;
    //[img originImage:img scaleToSize:CGSizeMake(50,50)];//(imgV.width / 2.0, imgV.height / 2.0)];
    
    UITapGestureRecognizer *tpGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectPhotos:)];
    tpGes.numberOfTapsRequired = 1;
    [imgV addGestureRecognizer:tpGes];
    [backView addSubview:imgV];
    _headImageView = imgV;

    imgV.frame = backView.frame;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = (CGRect){
        .origin.x = imgV.width * 0.2,
        .origin.y = imgV.height * 0.8,
        .size.width = 24,
        .size.height = 24
    };
    [btn setBackgroundImage:[UIImage imageNamed:@"xf_camera_add_pic"] forState:UIControlStateNormal];
    [imgV addSubview:btn];
    
    UIButton *delbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    delbtn.frame = (CGRect){
        .origin.x = imgV.width * 0.8,
        .origin.y = imgV.height * 0.8,
        .size.width = 24,
        .size.height = 24
    };
    [delbtn addTarget:self action:@selector(photosDisplay) forControlEvents:UIControlEventTouchUpInside];
    [delbtn setBackgroundImage:[UIImage imageNamed:@"xf_delete_pic"] forState:UIControlStateNormal];
    [imgV addSubview:delbtn];
    _headImageView.hidden = YES;
    
    _noImageHeadView = [[UIImageView alloc] init];
    _noImageHeadView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tpGes2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectPhotos:)];
    tpGes2.numberOfTapsRequired = 1;
    [_noImageHeadView addGestureRecognizer:tpGes2];
    [backView addSubview:_noImageHeadView];
    _noImageHeadView.frame = (CGRect){
        .origin.x = backView.width / 4.0,
        .origin.y = backView.height / 4.0,
        .size.width = backView.width / 2.0,
        .size.height = backView.height / 2.0
    };
    _noImageHeadView.image = [UIImage imageNamed:@"xf_camera_no_pic"];


}

- (void)buildContent {
    self.tableViewInfo = [[IBTTableViewInfo alloc]

                          initWithFrame:CGRectMake(10, self.view.height * 0.4, self.view.width - 20, IBT_DEFAULT_CELL_HEIGHT * 7)

                          style:UITableViewStylePlain];

    

    
    IBTTableViewSectionInfo *secInfo;
    IBTTableViewCellInfo *cellInfo;
     UIColor *titleColor = [UIColor colorWithW:145 a:1];
    CGFloat fCellHeight = IBT_DEFAULT_CELL_HEIGHT;
    secInfo = [IBTTableViewSectionInfo sectionInfoDefaut];
    
    //产地
    cellInfo =  [IBTTableViewCellInfo editorCellForSel:nil
                                                   target:nil
                                                    title:@"产地:"
                                                   margin:0
                                                      tip:nil
                                              autoCorrect:NO
                                                    focus:NO

                                                     text:_surveyResult.place];

    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    
    //价格
    cellInfo =  [IBTTableViewCellInfo editorCellForSel:nil
                                                target:nil
                                                 title:@"价格:"
                                                margin:0
                                                   tip:nil
                                           autoCorrect:NO
                                                 focus:NO

                                                  text:_surveyResult.price];

    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    //市场容量
    cellInfo =  [IBTTableViewCellInfo editorCellForSel:nil
                                                target:nil
                                                 title:@"市场容量:"
                                                margin:0
                                                   tip:nil
                                           autoCorrect:NO
                                                 focus:NO
                                                  text:_surveyResult.capacity];

    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    //质量情况
    cellInfo =  [IBTTableViewCellInfo editorCellForSel:nil
                                                target:nil
                                                 title:@"质量情况:"
                                                margin:0
                                                   tip:nil
                                           autoCorrect:NO
                                                 focus:NO

                                                  text:_surveyResult.quality];


    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    
    //备注
    cellInfo = [IBTTableViewCellInfo editorCellForSel:nil
                                               target:nil
                                                title:@"备注:"
                                               margin:0
                                                  tip:nil
                                          autoCorrect:NO
                                                focus:NO
                                                 text:_surveyResult.reMark];
    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    [self.tableViewInfo addSection:secInfo];
    
    IBTTableView *tableView = [_tableViewInfo getTableView];
    [self.view addSubview:tableView];
    
}

- (IBTImagePicker *)imagePicker {
    if (!_m_imagePicker) {
        self.m_imagePicker = [[IBTImagePicker alloc] init];
    }
    
    return _m_imagePicker;
}
#pragma  mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            [self openCamera];
            break;  
        case 1:
            [self libraryPhoto];
            break;
        default:
            break;
    }
}
- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = sourceType;
    [self PresentModalViewController:picker animated:YES];
    
    
}
- (void)libraryPhoto {
//    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
//    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary
//    ;
//    picker.delegate = self;
//    picker.allowsEditing = NO;
//    [self PresentModalViewController:picker animated:YES];
    ZYQAssetPickerController *assetPicker = [[ZYQAssetPickerController alloc]init];
    assetPicker.maximumNumberOfSelection = 10;
    assetPicker.assetsFilter = [ALAssetsFilter allPhotos];
    assetPicker.showEmptyGroups = NO;
    assetPicker.delegate = self;
    assetPicker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self PresentModalViewController:assetPicker animated:YES];
    
}
#pragma mark - UIImagePickerControllerDelegate


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//    NSURL *imgUrl = [info objectForKey:UIImagePickerControllerReferenceURL];
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    
//    NSData *imgData = UIImagePNGRepresentation(img);
//    [self savePhotoToDB:imgData];
    [[JavenImages shareInstance] insertAImage:[img scaledToWidth:200]];
    [self pushToHGphVC];
}

//在图片上加图片
- (void)selectPhotos: (UIGestureRecognizer *)tpGe {
    //NSArray *photosArr = [[XFDB sharedInstance] fetchAllPhotosFromLocal];
    if ([JavenImages shareInstance].imageArr.count > 0) {
        [self photosDisplay];
    } else {
        self.m_actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"打开照相机", @"从手机相册获取", nil];
        [_m_actionSheet showInView:self.view];

    }

}


#pragma  mark btn action
- (void)photosDisplay {
    HGPhWViewController *ghphVC = [[HGPhWViewController alloc]init];
    [self PushViewController:ghphVC animated:YES];
}


#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    if (_imgesMuArr.count > 0) {
        [_imgesMuArr removeAllObjects];
    }
    for (int i=0; i<assets.count; i++) {
        ALAsset *asset = assets[i];
        
        CGImageRef ref = [[asset  defaultRepresentation]fullResolutionImage];
        UIImage *img = [[UIImage alloc]initWithCGImage:ref];
        
        [self.imgesMuArr addObject: [img scaledToWidth:200]];//[UIImage imageNamed:@"AttachCamera"]
    }
    
    [[JavenImages shareInstance] insertImages:self.imgesMuArr];
    
    [self pushToHGphVC];
    
   
}

- (void)buildBottomButton {
    // 提交反馈
    UIButton *btnBack =
    [IBTUIButton RoundCornerBtnWithTitle:@"提交反馈"
                                 bgColor:nil];
    btnBack.frame = (CGRect) {
        .origin.x = BTN_PADDING,
        .origin.y = self.view.height - 64 - BTN_HEIGHT - 10,
        .size.width = BOTTOM_BTN_WIDTH,
        .size.height = BTN_HEIGHT
    };
    
    [btnBack addTarget:self
                action:@selector(commitFeedback)
      forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btnBack];
}

- (void)commitFeedback {
    NSString *priceStr = [self getTextFieldTextWithRow:kfeedbackCellPrice];
    if ([self isPureFloat:priceStr] || [self isPureInt:priceStr]) {
        
        [self saveSurveyResult];
    }else{
        [IBTLoadingView showTips:@"请输入正确的价格"];
    }

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


#pragma mark - 接口调用:3.1	新增行情反馈
- (void)saveSurveyResult{

    [IBTLoadingView showProgressLabel:@"正在加载..."];
    
    NSDictionary *paramDict = @{@"result":[self getSurveyResult],@"attachments":[self getAttachmentArray]};
    
    [[ICRHTTPController sharedController] surveySaveResultWithDict:paramDict surveyUuid:_aSurvey.uuid success:^(id succ) {
        
        [IBTLoadingView hideHUDWithText:nil];
        
        if (succ) {
            NSInteger success = [succ[@"success"] integerValue];
            NSString *message  = succ[@"message"] ;
            if (success == 1) {
                // [self backSurvey];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"返回异常"];
        }
        
    } failure:^(id fail) {
        
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:fail];
        
    }];
}
 
- (NSArray *)getAttachmentArray {
    NSMutableArray *attachArr = [NSMutableArray array];
    NSMutableArray *resultMuArr = [NSMutableArray array];
    //NSMutableArray *arrImgsData = [[XFDB sharedInstance]fetchAllPhotosDataFromLocal];
    if ([JavenImages shareInstance].imageArr.count == 0) {
      //  return attachArr;
    } else {
        for (int count  = 0; count < [JavenImages shareInstance].imageArr.count; count ++) {
           UIImage *image = [JavenImages shareInstance].imageArr[count];
            NSData *data = [image scaledToSpaceMaxSize:20];
            NSString *enCodeImageStr = [data base64EncodedString];
            NSMutableDictionary *phontoMuDict = [NSMutableDictionary dictionaryWithObjects:@[[NSDate randomImageName],enCodeImageStr ] forKeys:@[@"fileName",@"content"]];
            [attachArr addObject:phontoMuDict];
        }
    
    }
    
    return [NSArray arrayWithArray:attachArr];
}
#pragma mark  SurveyResult数据结构
- (NSDictionary *)getSurveyResult{
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    
    NSString *priceStr = [self getTextFieldTextWithRow:kfeedbackCellPrice];
    
    
    NSDictionary *dict = @{@"userUuid":userU.userId,
                           @"userCode":userU.userCode,
                           @"userName":userU.userName,
//                           @"unit":@"",
                           @"price":priceStr,
                           @"place":[self getTextFieldTextWithRow:kfeedbackCellPlace ],
                           @"capacity":[self getTextFieldTextWithRow:kfeedbackCellCapacity],
                           @"quality":[self getTextFieldTextWithRow:kfeedbackCellQulity],
                           @"remark":[self getTextFieldTextWithRow:kfeedbackCellRemark]};

    return dict;
}


//1. 整形判断
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

//2.浮点形判断:
- (BOOL)isPureFloat:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

- (NSString *)getTextFieldTextWithRow: (NSInteger)cellRow {
    NSString *textStr = [NSString string];
    IBTTableViewCellInfo *cellInfo = [_tableViewInfo getCellAtSection:0 row:cellRow];
    UITextField * titleTextF = [cellInfo getUserInfoValueForKey:CInfoEditorKey];
    if (!titleTextF.text || [titleTextF.text isEqual:[NSNull null]]) {
       textStr = @"";
    } else {
        textStr = titleTextF.text;
    }
    return textStr;
}

+ (NSString *)idIsNilOrNullToString: (id)data{
    NSString *returnStr = [NSString string];
    if ([data isEqual:[NSNull null]]|| !data) {
        data = @"";
        
    }
    
    return data;
}

#pragma mark ----跳转到图片展示界面----

- (void)pushToHGphVC{
    HGPhWViewController *hgphVC = [[HGPhWViewController alloc] init];
    [self PushViewController:hgphVC animated:NO];
}

- (void)dealloc {
    [[JavenImages shareInstance] removeAllImage];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([JavenImages shareInstance].imageArr.count > 0) {
        _headImageView.image = [JavenImages shareInstance].imageArr[0];
        _headImageView.hidden = NO;
        _noImageHeadView.hidden = YES;
    }else{
        _headImageView.hidden = YES;
        _noImageHeadView.hidden = NO;
    }
}


#pragma 把选择的图片放入到本地数据库中
- (void)savePhotoToDB: (NSData *)imgData {
//    XFPhoto *xfphoto = [[XFPhoto alloc]initWithPhotoData:imgData];
//    BOOL isSave = [[XFDB sharedInstance]savePhoto:xfphoto];
//    if (isSave) {
//        NSLog(@"保存成功");
//    } else {
//        NSLog(@"保存失败");
//    }
}
@end