//
//  GTOHomeViewController.m
//  total
//
//  Created by freecui on 15/9/9.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "GTOHomeViewController.h"
#import "GTOHomeSyncItem.h"
#import "GTOHomeWeatherItem.h"
#import "GTOHomeWarnItem.h"
#import "GTOHomePatrolItem.h"
#import "GTOLicenceCheckListViewController.h"
#import "GTOPatrolPlanListViewController.h"
#import "ICRAnnouncementViewController.h"
#import "GTOPatrolPlan.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>


static NSString *cellID = @"cellID";
static NSString *headerID = @"headerID";
static NSString *cellIDWeather = @"cellIDWeather";
static NSString *cellIDPatrol = @"cellIDPatrol";


@interface GTOHomeViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>


@property (nonatomic, strong) UITableView *c_tableV;
@property (nonatomic, strong) NSMutableDictionary *m_dataMudict;
@property (nonatomic, assign) NSUInteger m_totalSections;
@property (nonatomic, strong) GTOHomeWeatherItem *weatherItem;
@property (nonatomic, copy) NSString *m_city;
@property (nonatomic, copy) NSString *m_cityCode;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, copy) NSString *currentCity;

@end

@implementation GTOHomeViewController

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

}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    __weak typeof(self)weakSelf = self;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf startLocation];
        
    });
    [self httpGetAfficheData];
}


- (void)httpGetAfficheData {
    if (!self.m_dataMudict) {
        self.m_dataMudict = [NSMutableDictionary dictionary];//[@{}mutableCopy];
    }

    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    if (userU.hasAffichePermission) {
        void(^succ)(id) = ^(id data) {
            if ([data[@"success"] integerValue] == 1) {
                NSDictionary *dictData = data[@"data"];
                NSArray *arr = dictData[@"records"];
                [self.m_dataMudict setObject:@(arr.count) forKey:@( kAffiche)];
                [_c_tableV reloadData];
                if (userU.hasLicencePermission) {
                    [self httpGetLicenceData];
                    return ;
                }
                if (userU.hasProjectPatrolPermission) {
                    [self httpGetPatrolDataWithCategory:@"project"];
                    return ;
                }
                if (userU.hasHSEPatrolPermission) {
                    [self httpGetPatrolDataWithCategory:@"HSE"];
                    return ;
                }
            }
        };
        void(^fail)(id) = ^(id data) {
            [IBTLoadingView showTips:data];
                };
        
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        [httpCtrl doGetBoardListWithType:kICRAnnouncementTypeUnread
                              pageNumber:0
                                pageSize:200
                                 success:succ
                                 failure:fail];
    }
}

- (void)httpGetLicenceData {
    if (!self.m_dataMudict) {
        self.m_dataMudict = [NSMutableDictionary dictionary];//[@{}mutableCopy];
    }
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
//    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
//        [IBTLoadingView hideHUDWithText:nil];
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSInteger success = [data[@"success"] integerValue];
//        NSString *message  = data[@"message"] ;
        if (success == 1) {
            NSArray *recodesArr = data[ @"data" ][ @"records" ];
            [self.m_dataMudict setObject:@(recodesArr.count) forKey:@( kLicence)];
//            NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:2];
//            [_c_tableV reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.c_tableV reloadData];
            if (userU.hasProjectPatrolPermission) {
                [self httpGetPatrolDataWithCategory:@"project"];
//                return ;
            }
            if (userU.hasHSEPatrolPermission) {
                [self httpGetPatrolDataWithCategory:@"HSE"];
//                return ;
            }
        }
    };
    void(^fail)(id) = ^(id data) {
//        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    NSDictionary *dict = @{
                           @"userUuid":userU.f_user_uuid,
                           @"billNumberLike":[NSNull null],
                           @"state":GTO_LICENCE__STATE_SUBMITTED,
                           @"repairUuid":@"",
                           @"repairNumberLike":[NSNull null],//repairNumberObject,
                           @"riskGrade":[NSNull null],
                           @"queryOrders":@[@{@"direction":@"desc",@"field":@"billnumber"}],
                           @"pageNumber":@(0),
                           @"pageSize":@(20)};
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC getLicenceListWithData:dict success:succ failure:fail];
}

- (void)httpGetPatrolDataWithCategory: (NSString *)category {
    if (!self.m_dataMudict) {
        self.m_dataMudict = [NSMutableDictionary dictionary];//[@{}mutableCopy];
    }
    void(^succ)(id) = ^(id data) {
//        [IBTLoadingView hideHUDWithText:nil];
        NSInteger success = [data[@"success"] integerValue];
//        NSString *message  = data[@"message"] ;
        if (success == 1) {
            NSArray *recodesArr = data[ @"data" ][ @"records" ];
            if (recodesArr.count <= 0) {
                if([category isEqualToString:@"project"]) {
                    [self.m_dataMudict setObject:[NSNull null] forKey:@( kProjectPatrol)];
                }
                if([category isEqualToString:@"HSE"]) {
                    [self.m_dataMudict setObject:[NSNull null] forKey:@( kHSEPatrol)];
                }
                [self.c_tableV reloadData];
            } else {
                [self fetchPatrolWithArray:recodesArr andCategory:category];
            }
        }
    };
    void(^fail)(id) = ^(id data) {
//        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
//    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController]; //@"2015-10-16 21:46:03"
    [httpCtrl getMyPatrolWithCategory:category
                            startTime:[[NSDate date] httpParameterString]
                             dateType:GTO_PATROL_DATE_TYPE_BEFORE
                           pageNumber:0 pageSize:20 success:succ failure:fail];
 

}

- (void)fetchPatrolWithArray: (NSArray *)arr andCategory: (NSString *)category{
    
    GTOPatrolPlan *patrolPlan = [GTOPatrolPlan DBObject];
    [patrolPlan praseFromJsonDict:arr[0]];
    int finishStores = 0;
    int totalStores = (int)patrolPlan.inspectors.count;
    for(NSDictionary *dict in patrolPlan.inspectors) {
        if ([dict[@"state" ] integerValue] == 1) {
            finishStores ++;
        }
    }
    patrolPlan.finishedStoreNumber = finishStores;
    patrolPlan.totalStoreNumber = totalStores;
    if (totalStores == 0) {
        patrolPlan.processLength = 0.0;
    } else {
        patrolPlan.processLength =  finishStores * 1.0 / totalStores;
    }
    if ([category isEqualToString:@"project"]) {
        [self.m_dataMudict setObject:patrolPlan forKey:@( kProjectPatrol)];
        ICRUserUtil *userU = [ICRUserUtil sharedInstance];
        if (userU.hasHSEPatrolPermission) {
            [self httpGetPatrolDataWithCategory:@"HSE"];
            return ;
        }
    } else {
        [self.m_dataMudict setObject:patrolPlan forKey:@( kHSEPatrol)];
   }
    
    [_c_tableV reloadData];
    //            NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:];
    //            [_c_tableV reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

}
- (void)initTableView {

    
    UIImageView *bgImgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 64)];
    bgImgV.image = [UIImage imageNamed:@"home_bg"];
    bgImgV.userInteractionEnabled = YES;
    [self.view addSubview:bgImgV];
    //weatherItem
    self.weatherItem = [[GTOHomeWeatherItem alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 75)];
    [self.weatherItem updateWithCity:@"" temperature:@"" windDirection:@""];
    [self.view addSubview:_weatherItem];
    self.c_tableV = [[UITableView alloc]
            initWithFrame:CGRectMake(0, _weatherItem.bottom, self.view.width, self.view.height - 64 - _weatherItem.height - 55) style:UITableViewStylePlain];
    _c_tableV.backgroundColor = [UIColor clearColor];
    _c_tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_c_tableV registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    [_c_tableV registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIDWeather];
     [_c_tableV registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIDPatrol];
    _c_tableV.delegate = self;
    _c_tableV.dataSource = self;
    [bgImgV addSubview:_c_tableV];
}

//UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return  1 ;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    NSUInteger total = 0;
    total = userU.hasAffichePermission + userU.hasLicencePermission + userU.hasHSEPatrolPermission + userU.hasProjectPatrolPermission ;
    self.m_totalSections = total;
     NSArray *keysArr = [_m_dataMudict allKeys];
    return keysArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *keysArr = [_m_dataMudict allKeys];
    NSArray *objectsArr = [_m_dataMudict allValues];
    NSUInteger type = [keysArr[indexPath.section] integerValue];
    id object = objectsArr[indexPath.section];
    BOOL condition = (type == kProjectPatrol || type == kHSEPatrol)
    && (![object isKindOfClass:[NSNull class]]);
    if(condition){
        return 140;
    } else {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor clearColor]; //改变背景颜色
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return (section == 0 )? 1 : 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
        NSArray *keysArr = [_m_dataMudict allKeys];
        NSArray *objectsArr = [_m_dataMudict allValues];
        if (keysArr.count > 0) {
            NSUInteger type = [keysArr[indexPath.section] integerValue];
            id object = objectsArr[indexPath.section];
            BOOL condition = (type == kProjectPatrol || type == kHSEPatrol)
            && (![object isKindOfClass:[NSNull class]]);
            if (condition ) {
                cell = [tableView dequeueReusableCellWithIdentifier:cellIDPatrol forIndexPath:indexPath];
            }else {
                cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
            }
        }else {
            cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
        }
    [self configureCell:cell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
  
    return cell;
    
}
- (void)configureCell: (UITableViewCell *)cell forIndexPath: (NSIndexPath *)indexPath {
    UIView *contentView = cell.contentView;
    GTOHomeItem *homeItem = [contentView viewWithClass:[GTOHomeItem class]];
    GTOHomePatrolItem *patrolItem = [contentView viewWithClass:[GTOHomePatrolItem class]];
    
    if (!_m_dataMudict || _m_dataMudict.count == 0 ) {
        return;
    }
    NSArray *keysArr = [_m_dataMudict allKeys];
    NSArray *valuesArr = [_m_dataMudict allValues];
    if (keysArr[indexPath.section] ) {
//        CLog(@"%ld",indexPath.section);
        NSUInteger type = [keysArr[indexPath.section] integerValue];
        id object = valuesArr[indexPath.section];
        BOOL condition = (type == kProjectPatrol || type == kHSEPatrol)
        && (![object isKindOfClass:[NSNull class]]);
        if (condition) {
            if (!patrolItem) {
                patrolItem = [[GTOHomePatrolItem alloc]initWithFrame:contentView.bounds];
                [contentView addSubview:patrolItem];
            }
            if (type == kHSEPatrol) {
                [patrolItem updateWithData:valuesArr[indexPath.section] andCategory:@"HSE"];
            } else {
                [patrolItem updateWithData:valuesArr[indexPath.section] andCategory:@"project"];
            }
            
        } else {
            if (!homeItem) {
                homeItem = [[GTOHomeItem alloc]initWithFrame:contentView.bounds];
                [contentView addSubview:homeItem];
            }
            NSUInteger number = [valuesArr[indexPath.section]integerValue];
            [homeItem updateWithInfoType:type newsNumber:number];
        }
        
    }
    
}
//UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(indexPath.section == 0) {
//        return;
//    }
    NSArray *keysArr = [_m_dataMudict allKeys];
    NSInteger keyInt = [keysArr[indexPath.section]integerValue];
    switch (keyInt) {
        case kAffiche:
        {
            ICRAnnouncementViewController *announceVC = [[ICRAnnouncementViewController alloc]init];
            [self PushViewController:announceVC animated:YES];
        }
        break;
        case kLicence:
        {
            GTOLicenceCheckListViewController *licenceCheckVC = [[GTOLicenceCheckListViewController alloc]init];
            [self PushViewController:licenceCheckVC animated:YES];
        }
        break;
        case kProjectPatrol:
        {
            GTOPatrolPlanListViewController *vc = [[GTOPatrolPlanListViewController alloc]initWithTitle:@"project"];
            [self PushViewController:vc animated:YES];
        }
        break;
        case kHSEPatrol:
        {
            GTOPatrolPlanListViewController *vc = [[GTOPatrolPlanListViewController alloc]initWithTitle:@"HSE"];
            [self PushViewController:vc animated:YES];
        }
        break;
        default:
        break;
    }
}

//开始定位
- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled]) {
//        CLog(@"--------开始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗电量越
        // 总是授权
        [self.locationManager requestAlwaysAuthorization];
        //        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        //            _locationManager.allowsBackgroundLocationUpdates = YES;
        //        }
        self.locationManager.distanceFilter = 10.0f;
        //        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        //            [_locationManager requestAlwaysAuthorization];
        //        }
        //
        [_locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        CLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        CLog(@"无法获取位置信息");
    }
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oCoordinate = newLocation.coordinate;
//    CLog(@"经度：%f，纬度：%f", oCoordinate.longitude, oCoordinate.latitude);
    //[self.locationManager stopUpdatingLocation];
    
//    //创建地理位置解码编码器对象
//    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
//    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        for(CLPlacemark *place in placemarks){
//            NSDictionary *location = [place addressDictionary];
//            CLog(@"国家： %@",location[@"Country"]);
//            CLog(@"城市： %@",location[@"State"]);
//            CLog(@"区：%@",location[@"SubLocality"]);
//            CLog(@" %@",location[@"Country"]);
//            self.m_city = place.country;
//            break;
//        }
//    }];
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];

            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            NSLog(@"city = %@", city);

            [self httpWeatherWithCityName:city];
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
    
}
- (void)initData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"txt"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSString *cities = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (self.m_city.length <= 0) {
        self.m_city = @"上海";
    }
    NSRange range = [cities rangeOfString:[NSString stringWithFormat:@"d2=\"%@\"",self.m_city]];
    if (range.location != NSNotFound) {
        self.m_cityCode = [cities substringWithRange:range];
    }
    
    
}
- (void)httpWeatherWithCityName:(NSString *)cityName {
    void(^succ)(id) = ^(id data) {
//        CLog(@"weather %@",data);
        NSString *temp = data[@"HeWeather data service 3.0"][0][@"now"][@"tmp"];
        NSString *wd = data[@"HeWeather data service 3.0"][0][@"now"][@"wind"][@"dir"];
        NSString *cityName = data[@"HeWeather data service 3.0"][0][@"basic"][@"city"];
        
        [self.weatherItem updateWithCity:cityName temperature:temp windDirection:wd];
    };
    void(^fail)(id) = ^(id data) {
//        CLog(@"%@",data);
    };
    
//    [IBTLoadingView]
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC getWeatherInfoWithCityName:cityName success:succ failure:fail];
    
}



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



@end
