//
//  TaskPointViewController.m
//  Macalline
//
//  Created by JianjiYuan on 14-12-4.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "CheckImageViewController.h"
#import "ImageBrowserViewController.h"
#import "CheckResultChangeViewController.h"

@interface CheckImageViewController ()<ImageBrowserDelegate,UIAlertViewDelegate>
{
    NSMutableArray *arrStandardImages;
    
    NSMutableArray* arrImage;
    
    int index;
    
    UIButton* btnSubmit;
}

@property (nonatomic, strong) UIView *imageView;

@property (nonatomic, strong) UIView *evaluteView;

@property (nonatomic, strong) EDStarRating *ratingView;

@property (nonatomic, strong) ImageBrowserViewController *vcImageBCheck;
@end

@implementation CheckImageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"抽查(0/0)";
    
    self.vcImageBCheck = [[ImageBrowserViewController alloc] initWithNibName:nil bundle:nil];
    _vcImageBCheck.delegate = self;
    _vcImageBCheck.itemSize = CGSizeMake(CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-200);
    _vcImageBCheck.showAddPicsButton = NO;
    _vcImageBCheck.collectionView.scrollEnabled = NO;
    _vcImageBCheck.vcImagePickerPrensentFrom = self.navigationController;
    [self addChildViewController:_vcImageBCheck];
    
    _imageView = [[UIView alloc] init];
    _imageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_imageView];
    [_imageView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 130, 0)];
    [_imageView addSubview:self.vcImageBCheck.view];
    [self.vcImageBCheck.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    
    UIView *viewLine = [[UIView alloc] init];
    viewLine.backgroundColor = [UIColor colorWithRed:0.9143 green:0.9143 blue:0.9143 alpha:1];
    [_imageView addSubview:viewLine];
    [viewLine autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 10, 0, 10) excludingEdge:ALEdgeTop];
    [viewLine autoSetDimension:ALDimensionHeight toSize:1];
    
    
    _evaluteView = [[UIView alloc] init];
    _evaluteView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_evaluteView];
    [_evaluteView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeTop];
    [_evaluteView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_imageView];

    UILabel* lblEvalute = [[UILabel alloc] init];
    lblEvalute.textColor = [UIColor darkGrayColor];
    lblEvalute.font = [UIFont systemFontOfSize:13];
    lblEvalute.text = @"您的评分:";
    [_evaluteView addSubview:lblEvalute];
    [lblEvalute autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
    [lblEvalute autoAlignAxis:ALAxisHorizontal toSameAxisOfView:_evaluteView withOffset:-20];
    
    
    UILabel* lblTX = [[UILabel alloc] init];
    lblTX.textColor = [UIColor redColor];
    lblTX.font = [UIFont systemFontOfSize:11];
    lblTX.text = @"(注:评分结果最多五星最少一星)";
    [_evaluteView addSubview:lblTX];
    [lblTX autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:lblEvalute withOffset:5];
    [lblTX autoAlignAxis:ALAxisHorizontal toSameAxisOfView:lblEvalute];
    
    _ratingView = [[EDStarRating alloc] init];
    _ratingView.backgroundColor=[UIColor clearColor];
    _ratingView.starImage = [UIImage imageNamed:@"Settings/star_gary.png"];
    _ratingView.starHighlightedImage = [UIImage imageNamed:@"Settings/star_yellow.png"];
    _ratingView.maxRating = 5.0;
    _ratingView.delegate = self;
//    _ratingView.horizontalMargin = 12;
    _ratingView.editable=YES;
    _ratingView.rating= 0;
    _ratingView.displayMode=EDStarRatingDisplayFull;
    [_evaluteView addSubview:_ratingView];
    [_ratingView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:5];
    [_ratingView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:lblEvalute withOffset:10];
    [_ratingView autoSetDimensionsToSize:CGSizeMake(150, 25)];
    
    btnSubmit = [[UIButton alloc] init];
    btnSubmit.clipsToBounds = YES;
    [btnSubmit setTintColor:[UIColor whiteColor]];
    [btnSubmit setBackgroundImage:[UIImage imageWithColor:RGBColor(3, 119, 193, 1)] forState:UIControlStateNormal];
    [btnSubmit setTitle:@"评分完成,下一张" forState:UIControlStateNormal];
    btnSubmit.titleLabel.font = [UIFont systemFontOfSize:13];
    btnSubmit.layer.cornerRadius = 3;
    [btnSubmit addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
    [_evaluteView addSubview:btnSubmit];
    [btnSubmit autoAlignAxis:ALAxisHorizontal toSameAxisOfView:_ratingView];
    [btnSubmit autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:_ratingView withOffset:10];
    [btnSubmit autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
    [btnSubmit autoSetDimension:ALDimensionHeight toSize:25];

    arrImage = [[NSMutableArray alloc] init];

    [self requestDatas];
}

-(void)submitClick
{
    if (_ratingView.rating == 0) {
        [UIApplication showToastViewMessage:@"评分结果最少一星"];
    }
    else
    {
        [self updateSurveyPicScore];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    if ([[UIApplication getObjectType:Number key:kShouldRequestDataWhenBack] boolValue]) {
    //        [self requestDatas];
    //    }
}


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

- (void)btnHomeClick
{
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:NSClassFromString(@"TabBarViewController")]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}


- (void)requestDatas
{
    NSDictionary *dicParam = @{@"surveyId":self.surveyID};
    
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"querySurveyDetailsEX";
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

-(void)updateSurveyPicScore
{
    NSDictionary *dicParam = @{@"surveyDetailId":self.arrContents[index][@"surveyDetailId"],@"score":[NSString stringWithFormat:@"%.0f",_ratingView.rating]};
    
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"updateSurveyPicScoreEX";
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    if ([operation.userInfo[@"interface"] isEqualToString:@"querySurveyDetailsEX"])
    {
        self.arrContents = [result[@"surveyDetails"] validDataOfClass:[NSArray class]];
        
        if (self.arrContents.count == 0) {
         
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"暂无可抽查图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.delegate = self;
            alert.tag=2046;
            [alert show];
            
        }
        else
        {
            self.imageVNoResult.hidden = YES;
            for (int i = 0; i < self.arrContents.count; i++) {
                NSString* str = self.arrContents[i][@"status"];
                if ([str isEqualToString:@"0"]) {
                    index = i;
                    break;
                }
            }
            self.navigationItem.title = [NSString stringWithFormat:@"抽查(%d/%d)",index+1,self.arrContents.count];
            
            [self reloadImage];
        }
    }
    if ([operation.userInfo[@"interface"] isEqualToString:@"updateSurveyPicScoreEX"])
    {
        if (index < self.arrContents.count-1) {
            index++;
            [self reloadImage];
            self.navigationItem.title = [NSString stringWithFormat:@"抽查(%d/%d)",index+1,self.arrContents.count];
            
            if (index == self.arrContents.count) {
                [btnSubmit setTitle:@"评分完成" forState:UIControlStateNormal];
            }
        }
        else
        {
            CheckResultChangeViewController* vc = [[CheckResultChangeViewController alloc] init];
            vc.surveyID = self.surveyID;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)reloadImage
{
    ImageBrowserObj *obj = [[ImageBrowserObj alloc] init];
    obj.imageURL = self.arrContents[index][@"surveyPicUrl"];
    obj.sourceType = ImageSourceTypeWebURL;
    obj.imageId = nil;
    obj.isBGGray = NO;
    
    arrImage = [NSMutableArray arrayWithObject:obj];
    _vcImageBCheck.selectedImages = arrImage;
    [_vcImageBCheck reloadImageDatas];
}

#pragma mark =============  ImageBrowserViewController Delegate  =============

- (void)imageBrowser:(ImageBrowserViewController *)imageBrowser didSelectImages:(NSArray *)images
{
    
}

@end
