//
//  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) NSDictionary *surveyResultDict;
//@property (strong, nonatomic) HGPhWViewController *hgphVC;

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

@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];
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    
//   self.surveyResultDict = @{@"userUuid":user.userId,@"userCode":@"",@"userName":@"",@"price":[NSNull null],@"unit":[NSNull null],@"place":[NSNull null],@"capacity":[NSNull null],@"quality":[NSNull null]};
    void (^succ)(id) = ^(id data){
    
    };
    void (^fail)(id) = ^(id data){
    
    };
    [[ICRHTTPController sharedController] getResultsWithUuid:_surveyUuid
                                                     success:succ
                                                     failure:fail];
    
   
        self.surveyResult = [[SurveyResult alloc]init];
        self.surveyResult.unit = @"南汇8424西瓜调研情况";
        self.surveyResult.place = @"150605000001";
        self.surveyResult.price = @"南汇842[100213]";
        self.surveyResult.capacity = @"22222222222";
        self.surveyResult.quality = @"费卡接口";
        self.surveyResult.userName = @"张三";
        self.surveyResult.feedbackTime = @"2015-04-05 12:04:06";
        
 

}

- (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];
    
    
    NSArray *photosArr = [[XFDB sharedInstance] fetchAllPhotosFromLocal];
    if (photosArr.count > 0) {
        imgV.frame = backView.frame;
        
        XFPhoto *xfphonto = (XFPhoto *)photosArr[0];
       // NSData *da = xfphonto.photoData;
        imgV.image = [UIImage imageWithData:xfphonto.photoData];
        UIImage *img = [UIImage imageWithData:xfphonto.photoData];
        
        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];

    } else {
        imgV.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
        };
        UIImage *img = [UIImage imageNamed:@"xf_camera_no_pic"];
        imgV.image = img;
    }

}

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

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

                          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];
    [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];
//    HGPhWViewController *hgPhVc = [[HGPhWViewController alloc]init];
//    hgPhVc.img = img;
    
    NSData *imgData = UIImagePNGRepresentation(img);
    [self savePhotoToDB:imgData];
    [self PushViewController:[HGPhWViewController shareInstance] animated:YES];
    
   // hgPhVc.url = [NSString stringWithContentsOfURL:imgUrl encoding:NSUTF8StringEncoding error:nil];
}

//在图片上加图片
- (void)selectPhotos: (UIGestureRecognizer *)tpGe {
    NSArray *photosArr = [[XFDB sharedInstance] fetchAllPhotosFromLocal];
    if (photosArr.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:[HGPhWViewController shareInstance] 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];
        //获取url
        
       // UIImage *img = [[UIImage alloc]initWithCGImage:[asset thumbnail]];
        CGImageRef ref = [[asset  defaultRepresentation]fullResolutionImage];
        UIImage *img = [[UIImage alloc]initWithCGImage:ref];
        NSData *imgData = UIImagePNGRepresentation(img);
        [self savePhotoToDB:imgData];
       // UIImage *tempImg = [UIImage imageWithCGImage:[asset po]];
        [self.imgesMuArr addObject: img];//[UIImage imageNamed:@"AttachCamera"]
    }

  //  [[HGPhWViewController shareInstance] addPhotosWithArrayImgs:_imgesMuArr];
 
     [self PushViewController:[HGPhWViewController shareInstance] animated:YES];
    
   
}

- (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 {

    [self saveSurveyResult];

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


#pragma mark - 接口调用:3.1	新增行情反馈
- (void)saveSurveyResult{
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message  = data[@"message"] ;
            if (success == 1) {
               // [self backSurvey];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"返回异常"];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    
    NSDictionary *paramDict = @{@"result":[self getSurveyResult],@"attachments":[self getAttachmentArray]};
    [[ICRHTTPController sharedController]surveySaveResultWithDict:paramDict surveyUuid:_surveyUuid success:succ failure:fail];
}
 
- (NSArray *)getAttachmentArray {
    NSMutableArray *attachArr = [NSMutableArray array];
    NSMutableArray *resultMuArr = [NSMutableArray array];
    NSMutableArray *arrImgsData = [[XFDB sharedInstance]fetchAllPhotosDataFromLocal];
    if (arrImgsData.count == 0) {
      //  return attachArr;
    } else {
        for (int count  = 0; count < arrImgsData.count; count ++) {
            NSData *data = arrImgsData[count];
            NSString *fileName = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSMutableDictionary *phontoMuDict = [NSMutableDictionary dictionaryWithObjects:@[@"",data ] forKeys:@[@"fileName",@"content"]];
            [attachArr addObject:phontoMuDict];
        }
    
    }
    
    return [NSArray arrayWithArray:attachArr];
}
#pragma mark  SurveyResult数据结构
- (NSDictionary *)getSurveyResult{
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    
    NSDictionary *dict = @{@"userUuid":userU.userId,@"userCode":userU.userCode,@"userName":userU.userName,@"unit":@"",
                           @"price":[self getTextFieldTextWithRow:kfeedbackCellPrice],
                           @"place":[self getTextFieldTextWithRow:kfeedbackCellPlace ],
                           @"capacity":[self getTextFieldTextWithRow:kfeedbackCellCapacity],
                           @"quality":[self getTextFieldTextWithRow:kfeedbackCellQulity ]};

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