//
//  ICRStoreViewController.m
//  XFFruit
//
//  Created by Xummer on 3/24/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#define HEAD_IMG_HEIGHT_WIDTH_PROPORTION  (101/320)
#define STORE_DETAIL_LABEL_HEIGHT         (21)
#define STORE_DETAIL_LABEL_LEFT           (20)
#define SELECT_STORE_BUTTON_WIDTH         (44)
#define SELECT_STORE_BUTTON_RIGHT         (20)

#import "ICRStoreViewController.h"
#import "ICRStoreListViewController.h"
#import "ICRTaskEditViewController.h"
#import "ICRPatrolPlanViewController.h"
#import "ICRStoreDetailViewController.h"
#import "ICRTaskHandleViewController.h"

#import "ICRFunctionBaseView.h"
#import "ICRFunctionEntity.h"
#import "ICRNavigationViewController.h"
#import "ICRStore.h"

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface ICRStoreViewController ()
<
    ICRFunctionBaseViewDelegate,
    ICRStoreListViewDelegate,
    CLLocationManagerDelegate
>

@property (strong, nonatomic) UIImageView *m_headImageView;
@property (strong, nonatomic) UILabel *m_storeDetailLabel;
@property (strong, nonatomic) UIButton *m_selectStoreButton;


@property (strong,nonatomic) UIView *alertView;
@property (strong,nonatomic) UIView *alertInfo;

@property (strong, nonatomic) ICRStore *m_currentStore;
@property (strong,nonatomic) CLLocationManager *locationManager;
@property (strong,nonatomic) NSString *mylocationLongitude;
@property (strong,nonatomic) NSString *mylocationLatitude;

@end

@implementation ICRStoreViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:nil];
//    self.navigationItem.backBarButtonItem = backBtn;
    [self setupSubviews];
//
    if ([CLLocationManager locationServicesEnabled]) {
        
        self.locationManager = [[CLLocationManager alloc] init];
        
        _locationManager.delegate = self;
        
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗电量越大。
        
        _locationManager.distanceFilter = 100; //控制定位服务更新频率。单位是“米”
        
        [_locationManager startUpdatingLocation];
        
        //在ios 8.0下要授权
        
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
            
            [_locationManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
        
    }
}

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

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self fetchCurrentStore];
}

#pragma mark - Setter
- (void)setM_currentStore:(ICRStore *)currentStore {
    if (_m_currentStore == currentStore) {
        return;
    }
    
    _m_currentStore = currentStore;
    
    self.m_storeDetailLabel.text = _m_currentStore.name;
}

#pragma mark - Private Method
- (void)setupSubviews {
    
    self.m_headImageView = [[UIImageView alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = self.view.width,
        .size.height = self.view.width * 101/320
    }];
    _m_headImageView.userInteractionEnabled = YES;
    _m_headImageView.image = [UIImage imageNamed:@"CurrentStoreBG"];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHeadImageAction:)];
    tapGes.numberOfTapsRequired = 1;
    [_m_headImageView addGestureRecognizer:tapGes];
    
    self.m_selectStoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _m_selectStoreButton.frame = (CGRect){
        .origin.x = _m_headImageView.width - SELECT_STORE_BUTTON_WIDTH - SELECT_STORE_BUTTON_RIGHT,
        .origin.y = (_m_headImageView.height - SELECT_STORE_BUTTON_WIDTH)/2,
        .size.width = SELECT_STORE_BUTTON_WIDTH,
        .size.height = SELECT_STORE_BUTTON_WIDTH
    };
    [_m_selectStoreButton setImage:[UIImage imageNamed:@"RefreshBtn"] forState:UIControlStateNormal];
    _m_selectStoreButton.layer.masksToBounds = YES;
    _m_selectStoreButton.layer.cornerRadius = SELECT_STORE_BUTTON_WIDTH * 0.5;
    [_m_selectStoreButton addTarget:self action:@selector(selectStoreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_m_headImageView addSubview:_m_selectStoreButton];
    
    
    self.m_storeDetailLabel = [[UILabel alloc] initWithFrame:(CGRect){
        .origin.x = STORE_DETAIL_LABEL_LEFT,
        .origin.y = (_m_headImageView.height - STORE_DETAIL_LABEL_HEIGHT)/2,
        .size.width = self.view.width - STORE_DETAIL_LABEL_LEFT * 3 - SELECT_STORE_BUTTON_WIDTH,
        .size.height = STORE_DETAIL_LABEL_HEIGHT
    }];
    
    _m_storeDetailLabel.textAlignment = NSTextAlignmentLeft;
    _m_storeDetailLabel.font = [UIFont systemFontOfSize:21];
    _m_storeDetailLabel.textColor = [UIColor whiteColor];
    _m_storeDetailLabel.backgroundColor = [UIColor clearColor];
    
    [_m_headImageView addSubview:_m_storeDetailLabel];
    
    [self.view addSubview:_m_headImageView];
    
    NSMutableArray *arrFunctionEntities = [NSMutableArray array];
    NSArray *functionImageNames = @[ @"NavigateIcon",
                                     @"SignUpIcon",
                                     @"LeaveStoreIcon",
                                     @"PatrolPlanIcon",
                                     @"CreateNewTaskIcon",
                                     @"HandleTaskIcon" ];
    
    NSArray *fuctionNames = @[ [IBTCommon localizableString:@"Navigate"],
                               [IBTCommon localizableString:@"SignUp"],
                               [IBTCommon localizableString:@"LeaveStore"],
                               [IBTCommon localizableString:@"PatrolPlan"],
                               [IBTCommon localizableString:@"CreateNewTask"],
                               [IBTCommon localizableString:@"HandleTask"] ];
    
    NSArray *functionTags = @[ @(kFunctionNavigation),
                               @(kFunctionComeShopReg),
                               @(kFunctionLeaveShopReg),
                               @(kFunctionPatrolPlan),
                               @(kFunctionCreatTask),
                               @(kFunctionHandleTask)];
    
    int i = 0;
    for (NSString *functionName in fuctionNames) {
        ICRFunctionEntity *funtionEntity = [[ICRFunctionEntity alloc] init];
        funtionEntity.functionName = functionName;
        funtionEntity.iconName = [functionImageNames objectAtIndex:i];
        funtionEntity.functionItemTag = [[functionTags objectAtIndex:i] integerValue];
        [arrFunctionEntities addObject:funtionEntity];
        i ++;
    }
    
    ICRFunctionBaseView *baseView = [ICRFunctionBaseView initWithFunctionData:arrFunctionEntities];
    
    baseView.frame = (CGRect){
        .origin.x = 0,
        .origin.y = _m_headImageView.height,
        .size.width = self.view.width,
        .size.height = 240
    };
    baseView.backgroundColor = [UIColor clearColor];
    baseView.m_delegate = self;
    [self.view addSubview:baseView];
   
}

- (void)fetchCurrentStore {

    ICRUserUtil *userInfo = [ICRUserUtil sharedInstance];
    NSString *currentStoreID = userInfo.currentStoreID;

    if ([currentStoreID integerValue] == 0) {
        self.m_currentStore = nil;
        [self showStoreListWithHaveToChoose:YES];
        return;
    }
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRStore TableName], @"uuid"];
        return [db executeQuery:sql, currentStoreID];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_currentStore = [fetchedObjects firstObject];
        
        if (!_m_currentStore) {
            [strongSelf showStoreListWithHaveToChoose:YES];
        }
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRStore class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
   
}

- (void)updateCurrentStore:(ICRStore *)store {
    if (store == _m_currentStore) {
        return;
    }
    
    self.m_currentStore = store;
    
    ICRUserUtil *userInfo = [ICRUserUtil sharedInstance];
    [userInfo storageCurrentStoreID: store.storyID ];
}

#pragma mark - Actions
- (void)tapHeadImageAction:(__unused id)sender {
    ICRStoreDetailViewController *dVC = [[ICRStoreDetailViewController alloc] initWithStoreData:_m_currentStore];
    dVC.title = [IBTCommon localizableString:@"Store Detail:"];
    [self PushViewController:dVC animated:YES];
}

- (void)selectStoreButtonAction:(__unused id)sender {
    [self showStoreListWithHaveToChoose:NO];
}

- (void)showStoreListWithHaveToChoose:(BOOL)bHaveTo {
    ICRStoreListViewController *sVC = [[ICRStoreListViewController alloc] initWithBHaveToChooseOne:bHaveTo];
    sVC.title = [IBTCommon localizableString:@"Choose a Store"];
    sVC.m_delegate = self;
    [self PresentViewControllerInNewNavigation:sVC animated:YES completion:NULL];
}

#pragma mark - ICRStoreListViewDelegate
- (void)storeListViewCtrl:(ICRStoreListViewController *)vCtrl didSelectedStore:(ICRStore *)store {
    [self updateCurrentStore:store];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - ICRFunctionBaseViewDelegate
- (void)ICRFunctionBaseView:(ICRFunctionItemControl *)imageView {
    /*
     kFunctionPatrolPlan,
     kFunctionNavigation,
     kFunctionComeShopReg,
     kFunctionLeaveShopReg,
     kFunctionCreatTask,
     kFunctionHandleTask
     */
    switch (imageView.tag) {
        case kFunctionPatrolPlan:
        {
            ICRPatrolPlanViewController *pVC = [[ICRPatrolPlanViewController alloc] initWithStore:_m_currentStore isHomeShow:NO];
            [self PushViewController:pVC animated:YES];
        }
            break;
        case kFunctionNavigation:
            NSLog(@"kFunctionNavigation");
        {
            ICRNavigationViewController *nVC = [[ICRNavigationViewController alloc]init];
            nVC.m_currentStore = self.m_currentStore;
            [self PushViewController:nVC animated:YES];
        
        }
            break;
        case kFunctionComeShopReg:
            [self creatAlphaView];
            [self creatAlterInfo:@"进店签到"];
            break;
        case kFunctionLeaveShopReg:
            [self creatAlphaView];
            [self creatAlterInfo:@"离店登记"];
            break;
        case kFunctionCreatTask:
        {
            ICRTaskEditViewController *tVC =
            [[ICRTaskEditViewController alloc] initWithTask:nil store:self.m_currentStore];
            [self PushViewController:tVC animated:YES];
        }
            break;
        case kFunctionHandleTask:
        {
            ICRTaskHandleViewController *tVC =
            [[ICRTaskHandleViewController alloc] initWithStore:self.m_currentStore];
            [self PushViewController:tVC animated:YES];
            
        }
            break;
            
        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currentPosition = [locations lastObject];

    _mylocationLongitude = [NSString stringWithFormat:@"%.3f",currentPosition.coordinate.longitude];
    _mylocationLatitude = [NSString stringWithFormat:@"%.3f",currentPosition.coordinate.latitude];
    //_mylocationLongitude
    [_locationManager stopUpdatingLocation];
}

- (void)creatAlphaView{
    //UIViewController

    //_alertView = [[UIView alloc]initWithFrame:self.view.bounds];
    _alertView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _alertView.backgroundColor = [UIColor clearColor];
    [[UIApplication sharedApplication].keyWindow addSubview:_alertView];
    
    UIView *alphaView = [[UIView alloc]initWithFrame:_alertView.frame];
    alphaView.backgroundColor = [UIColor blackColor];
    alphaView.alpha = 0.3;
    [_alertView addSubview: alphaView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [tap setDelegate:(id<UIGestureRecognizerDelegate>)self];
    tap.numberOfTouchesRequired = 1;
    tap.numberOfTapsRequired = 1;
    [_alertView setTag:10000];
    [_alertView addGestureRecognizer:tap];

}

- (void)tap:(UIGestureRecognizer *)recognizer{
    
}

- (void)creatAlterInfo: (NSString *)topTitle{
    
    [_locationManager startUpdatingLocation];
    CGFloat alertInfoY = CGRectGetMaxY(_m_headImageView.frame)+ 64;
    CGFloat alertInfoW = CGRectGetWidth(self.view.frame);
    CGFloat alertInfoH = CGRectGetHeight(self.view.bounds)- CGRectGetHeight(_m_headImageView.frame);
    CGFloat padding = 10;
    if (!_alertInfo) {
        _alertInfo = [[UIView alloc]initWithFrame:CGRectMake(0,alertInfoY,alertInfoW,alertInfoH)];
        [_alertInfo setBackgroundColor:[UIColor grayColor]];
        [_alertView  addSubview:_alertInfo];
        
        UIView *info = [[UIView alloc]initWithFrame:CGRectMake(0, padding, alertInfoW, alertInfoH - 64)];
        info.backgroundColor = [UIColor whiteColor];
        [_alertInfo addSubview:info];
        
        CGFloat topH = 40; CGFloat W = alertInfoW;
        CGFloat otherH = (CGRectGetHeight(info.bounds) - (topH + padding) * 2.0)/4.0;
        UILabel *lblCome = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,W , topH)];
        lblCome.font = [UIFont systemFontOfSize:20];
        lblCome.text = topTitle;
        [lblCome setTextAlignment:NSTextAlignmentCenter];
        [info addSubview:lblCome];
        
        UIButton *btnClose = [[UIButton alloc]initWithFrame:CGRectMake(W - padding - 40, 0, 40, topH)];
        [btnClose setTitleColor:ICR_BLUE_BTN_COLOR  forState:UIControlStateNormal];
        [btnClose setTitle:@"关闭" forState:UIControlStateNormal];
        [btnClose addTarget:self action:@selector(closed) forControlEvents:UIControlEventTouchUpInside];
        [info addSubview:btnClose];
        
        NSArray *arrlblTitles = @[@"签到人",@"签到时间（以实际提交为标准）",@"签到门店",@"签到坐标"];
        NSDate *currentDate = [NSDate date];
        NSDateFormatter *dateMatter = [[NSDateFormatter alloc]init];
        [dateMatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *strCurrentDate = [dateMatter stringFromDate:currentDate];
        NSString *strPosition = [NSString stringWithFormat:@"%@,%@",_mylocationLongitude,_mylocationLatitude];

        NSArray *arrInfo = @[
                             _m_currentStore.createInfo[@"operator"][@"operName"],strCurrentDate,_m_currentStore.name,strPosition];
        
        //签到类型和获取现在时间
        NSUserDefaults *signInfo = [NSUserDefaults standardUserDefaults];
        [signInfo setObject:strCurrentDate forKey:@"currentDate"];
        if([topTitle isEqualToString:@"进店签到"]) {
            [signInfo setObject:@"in" forKey:@"signType"];
        }else if ([topTitle isEqualToString:@"离店登记"]){
            [signInfo setObject:@"out" forKey:@"signType"];
        }else{
        
        }
        
        CGFloat lblH = 19;
        for (int count = 0; count < [arrlblTitles count]; count++) {
            CGFloat viewContY = CGRectGetMaxY(lblCome.frame) + otherH * count;
            UIView *viewCont = [[UIView alloc]initWithFrame:CGRectMake(padding, viewContY, alertInfoW - padding, otherH )];
            [info addSubview:viewCont];
            UILabel *lblCont = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, W, lblH)];
            lblCont.font = [UIFont systemFontOfSize:16];
            [lblCont setTextColor:ICR_GRAY_BTN_COLOR];
            lblCont.text = [arrlblTitles objectAtIndex:count];
            [viewCont addSubview:lblCont];
            
            UILabel *cont = [[UILabel alloc]initWithFrame:CGRectMake(0, lblH, W, lblH)];
            cont .text = [arrInfo objectAtIndex:count];
            [viewCont  addSubview:cont ];
        }
        UIButton *btnSubmit = [[UIButton alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(info.frame) - topH , W, topH)];
        [btnSubmit setBackgroundColor:ICR_ORANGE_BTN_COLOR ];
        [btnSubmit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btnSubmit setTitle:@"确认并提交" forState:UIControlStateNormal];
        [btnSubmit addTarget:self action:@selector(submited) forControlEvents:UIControlEventTouchUpInside];
        [info addSubview:btnSubmit];
    }
    
}

- (void)closed {
    if (_alertInfo) {
        [_alertInfo removeFromSuperview];
        _alertInfo = nil;
    }
    
    if (_alertView) {
        [_alertView removeFromSuperview];
        _alertView = nil;
    }


}
- (void)submited{

    ICRHTTPController *httpCon = [ICRHTTPController sharedController];
    NSUserDefaults *signInfo = [NSUserDefaults standardUserDefaults];
     NSString *storeID = _m_currentStore.storyID;
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
      NSString *currentData = [[NSDate date] httpParameterString];
    NSString *signType = [signInfo objectForKey:@"signType"] ;
    _mylocationLatitude = _mylocationLatitude==NULL ? @"0" :_mylocationLatitude;
    _mylocationLongitude = _mylocationLongitude==NULL ? @"0" :_mylocationLongitude;
    NSDictionary *dataInfo = @{@"storeUuid":storeID,
                               @"signInTime":currentData,
                               @"type":signType,
                               @"longitude":_mylocationLongitude,
                               @"latitude":_mylocationLatitude,
                               @"signerUuid": user.userId};
    [self closed];
    [httpCon doSignupWithInfo:dataInfo success:nil failure:nil];
}
@end
