//
//  HomeNoticeViewController.m
//  Macalline
//
//  Created by Z on 16/4/8.
//  Copyright © 2016年 JianjiYuan. All rights reserved.
//

#import "HomeNoticeViewController.h"
#import "NoteDetailViewController.h"
#import "BRNetworkMgr.h"
#import "RDVTabBarController.h"
#import "DBDaoMgr.h"

@interface HomeNoticeViewController ()< BRNetworkMgrDelegate >
{
    UILabel*lblNotice;
    UIImageView* imageNotice;
    UILabel*lblRemind;
    UIImageView* imageRemind;
}
@property(nonatomic,strong)UIButton* btnLeft;
@property(nonatomic,strong)UIButton* btnRight;
@property(nonatomic,strong)NSArray * noticeArr;

@property(nonatomic,strong)NSString * tableType;;



@end

@implementation HomeNoticeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //        self.title = @"公告信息";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _tableType = @"";
    CGFloat w = self.view.bounds.size.width;
    _btnLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, w/2, 50)];
    [_btnLeft addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    _btnLeft.tag = 99;
    [_btnLeft setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:_btnLeft];
    
    lblNotice = [[UILabel alloc] init];
    lblNotice.text = @"公告";
    lblNotice.font =[UIFont systemFontOfSize:14];
    lblNotice.textColor = RGBColor(44, 172, 236, 1);
    lblNotice.textAlignment = NSTextAlignmentCenter;
    [_btnLeft addSubview:lblNotice];
    [lblNotice autoAlignAxis:ALAxisVertical toSameAxisOfView:_btnLeft];
    [lblNotice autoAlignAxis:ALAxisHorizontal toSameAxisOfView:_btnLeft withOffset:10];
    
    imageNotice = [[UIImageView alloc] init];
    imageNotice.image = [UIImage imageNamed:@"Settings/notice_pic_change.png"];
    [_btnLeft addSubview:imageNotice];
    [imageNotice autoAlignAxis:ALAxisVertical toSameAxisOfView:_btnLeft];
    [imageNotice autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:lblNotice withOffset:-2];
    [imageNotice autoSetDimensionsToSize:CGSizeMake(15, 15)];
    
    _btnRight = [[UIButton alloc] initWithFrame:CGRectMake(w/2, 0, w/2, 50)];
    [_btnRight addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_btnRight setBackgroundColor:RGBColor(54, 182, 242, 1)];
    [self.view addSubview:_btnRight];
    
    lblRemind = [[UILabel alloc] init];
    lblRemind.text = @"提醒";
    lblRemind.font =[UIFont systemFontOfSize:14];
    lblRemind.textColor = [UIColor whiteColor];
    lblRemind.textAlignment = NSTextAlignmentCenter;
    [_btnRight addSubview:lblRemind];
    [lblRemind autoAlignAxis:ALAxisVertical toSameAxisOfView:_btnRight];
    [lblRemind autoAlignAxis:ALAxisHorizontal toSameAxisOfView:_btnRight withOffset:10];
    
    imageRemind = [[UIImageView alloc] init];
    imageRemind.image = [UIImage imageNamed:@"Settings/remind_pic_change.png"];
    [_btnRight addSubview:imageRemind];
    [imageRemind autoAlignAxis:ALAxisVertical toSameAxisOfView:_btnRight];
    [imageRemind autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:lblNotice withOffset:-2];
    [imageRemind autoSetDimensionsToSize:CGSizeMake(13, 17)];
    
    if ([[DataMgr getInstance].roleId isEqualToString:@"daqufuzeren"]) {
        lblNotice.textColor = RGBColor(0, 117, 196, 1);
        [_btnLeft setBackgroundColor:[UIColor whiteColor]];
        [_btnRight setBackgroundColor:RGBColor(0, 117, 196, 1)];
    }
    else if ([[DataMgr getInstance].roleId isEqualToString:@"xiaoqufuzeren"]) {
        lblNotice.textColor = RGBColor(0, 171, 202, 1);
        [_btnLeft setBackgroundColor:[UIColor whiteColor]];
        [_btnRight setBackgroundColor:RGBColor(0, 171, 202, 1)];
    }
    else
    {
        lblNotice.textColor = RGBColor(44, 172, 236, 1);
        [_btnLeft setBackgroundColor:[UIColor whiteColor]];
        [_btnRight setBackgroundColor:RGBColor(44, 172, 236, 1)];
        
    }
//    self.tableVContent.backgroundColor = [UIColor redColor];
    self.tableVContent.separatorStyle = UITableViewCellSelectionStyleNone;
}
-(void)btnClick:(UIButton*)sender
{
    self.imageVNoResult.hidden = YES;
    if (sender.tag == 99) {
        _tableType = @"";
        [self.tableVContent reloadData];
        if ([[DataMgr getInstance].roleId isEqualToString:@"daqufuzeren"]) {
            imageNotice.image = [UIImage imageNamed:@"Settings/notice_pic_change.png"];
            imageRemind.image = [UIImage imageNamed:@"Settings/remind_pic_change.png"];
            lblNotice.textColor = RGBColor(0, 117, 196, 1);
            lblRemind.textColor = [UIColor whiteColor];
            
            [_btnLeft setBackgroundColor:[UIColor whiteColor]];
            [_btnRight setBackgroundColor:RGBColor(0, 117, 196, 1)];
        }
        else if ([[DataMgr getInstance].roleId isEqualToString:@"xiaoqufuzeren"]) {
            imageNotice.image = [UIImage imageNamed:@"Settings/notice_pic_change.png"];
            imageRemind.image = [UIImage imageNamed:@"Settings/remind_pic_change.png"];
            lblNotice.textColor = RGBColor(0, 171, 202, 1);
            lblRemind.textColor = [UIColor whiteColor];
            [_btnLeft setBackgroundColor:[UIColor whiteColor]];
            [_btnRight setBackgroundColor:RGBColor(0, 171, 202, 1)];
        }
        else
        {
            imageNotice.image = [UIImage imageNamed:@"Settings/notice_pic_change.png"];
            imageRemind.image = [UIImage imageNamed:@"Settings/remind_pic_change.png"];
            lblNotice.textColor = RGBColor(44, 172, 236, 1);
            lblRemind.textColor = [UIColor whiteColor];
            
            [_btnLeft setBackgroundColor:[UIColor whiteColor]];
            [_btnRight setBackgroundColor:RGBColor(44, 172, 236, 1)];
        }
    }
    else
    {
        if ([[DataMgr getInstance].roleId isEqualToString:@"daqufuzeren"]) {
            imageNotice.image = [UIImage imageNamed:@"Settings/notice_pic.png"];
            imageRemind.image = [UIImage imageNamed:@"Settings/remind_pic.png"];
            lblNotice.textColor = [UIColor whiteColor];
            lblRemind.textColor = RGBColor(0, 117, 196, 1);
            
            [_btnRight setBackgroundColor:[UIColor whiteColor]];
            [_btnLeft setBackgroundColor:RGBColor(0, 117, 196, 1)];
        }
        else if ([[DataMgr getInstance].roleId isEqualToString:@"xiaoqufuzeren"]) {
            imageNotice.image = [UIImage imageNamed:@"Settings/notice_pic.png"];
            imageRemind.image = [UIImage imageNamed:@"Settings/remind_pic.png"];
            lblNotice.textColor = [UIColor whiteColor];
            lblRemind.textColor = RGBColor(0, 171, 202, 1);
            [_btnRight setBackgroundColor:[UIColor whiteColor]];
            [_btnLeft setBackgroundColor:RGBColor(0, 171, 202, 1)];
        }
        else
        {
            imageNotice.image = [UIImage imageNamed:@"Settings/notice_pic.png"];
            imageRemind.image = [UIImage imageNamed:@"Settings/remind_pic.png"];
            lblNotice.textColor = [UIColor whiteColor];
            lblRemind.textColor = RGBColor(44, 172, 236, 1);
            
            [_btnRight setBackgroundColor:[UIColor whiteColor]];
            [_btnLeft setBackgroundColor:RGBColor(44, 172, 236, 1)];
        }
        
        [self selectNoticeDatas];
    }
}

- (void)setViewLayoutConstraint
{
    if ([[DataMgr getInstance].roleId isEqualToString:@"daqufuzeren"]) {
        _btnLeft.hidden = YES;
        _btnRight.hidden = YES;
        [self.tableVContent autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    else
    {
        _btnLeft.hidden = NO;
        _btnRight.hidden = NO;
        [self.tableVContent autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeTop];
        [self.tableVContent autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.btnLeft];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.leftBarButtonItems = nil;
    self.navigationController.navigationBarHidden = NO;
    self.rdv_tabBarController.navigationController.navigationBarHidden = YES;
    [self setViewLayoutConstraint];
    [self requestDatas];
    
}
-(void)selectNoticeDatas
{
    _tableType = @"notice";
    DLog(@"userID:%@",[DataMgr getInstance].userID);
    _noticeArr = [DBDaoMgr fetchNoticeByUserId:[DataMgr getInstance].userID];
    [self.tableVContent reloadData];
    if (_noticeArr.count!=0) {
        self.imageVNoResult.hidden = YES;
    }
    else
    {
        self.imageVNoResult.hidden = NO;
    }
    
}
- (void)requestDatas
{
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"queryNoticeListEX";
    NSDictionary *param = @{@"type":@"2"};
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:param
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    
    [self.networkMgr startOperation:operation];
}

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

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    self.arrContents = result[@"noticeList"];
    [self.tableVContent reloadData];
    
    if (self.arrContents.count == 0 && ![_tableType isEqualToString:@"notice"]) {
        self.imageVNoResult.hidden = NO;
    }
    else
    {
        self.imageVNoResult.hidden = YES;
    }
    
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_tableType isEqualToString:@"notice"]) {
        
        static NSString *cellIdentifier = @"remindCell";
        
        RemindListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[RemindListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        
        cell.lblTitle.text = _noticeArr[indexPath.row][@"title"];
        cell.lblContent.text =  _noticeArr[indexPath.row][@"content"];;
        cell.lblTime.text = _noticeArr[indexPath.row][@"time"];
        
        
        NSString* nid = _noticeArr[indexPath.row][@"isRead"];
        if([nid isEqualToString:@"NO"])
        {
            cell.lblTitle.textColor = [UIColor darkGrayColor];
            cell.lblContent.textColor = [UIColor darkGrayColor];
            cell.lblTime.textColor = [UIColor darkGrayColor];
            cell.view.hidden = NO;
        }
        else
        {
            cell.lblTitle.textColor = [UIColor lightGrayColor];
            cell.lblContent.textColor = [UIColor lightGrayColor];
            cell.lblTime.textColor = [UIColor lightGrayColor];
            cell.view.hidden = YES;
        }
        UIView* lineView = [[UIView alloc] init];
        lineView.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:lineView];
        [lineView autoSetDimension:ALDimensionHeight toSize:0.5];
        [lineView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 10, 0, 10) excludingEdge:ALEdgeTop];
        
        return cell;
    }
    else
    {
        NSString *cellIdentifier = @"NoticeListCell";
        NoticeListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[NoticeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.lblTitle.text = self.arrContents[indexPath.row][@"title"];
        cell.lblcontent.text = self.arrContents[indexPath.row][@"context"];
        
        
        
        cell.lblCreateTime.text = [self.arrContents[indexPath.row][@"createTime"] substringToIndex:10];
        if ([self.arrContents[indexPath.row][@"isRead"] isEqualToString:@"01"]) {
            cell.lblTitle.textColor = [UIColor darkGrayColor];
            cell.lblCreateTime.textColor = [UIColor darkGrayColor];
            cell.lblcontent.textColor = [UIColor darkGrayColor];
            cell.view.hidden = NO;
        }else if ([self.arrContents[indexPath.row][@"isRead"] isEqualToString:@"02"]) {
            cell.lblTitle.textColor = [UIColor lightGrayColor];
            cell.lblCreateTime.textColor = [UIColor lightGrayColor];
            cell.lblcontent.textColor = [UIColor lightGrayColor];
            cell.view.hidden = YES;
        }
        cell.tag = 100+[self.arrContents[indexPath.row][@"isRead"] intValue];
        
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_tableType isEqualToString:@"notice"]) {
        NSString *strTitle = _noticeArr[indexPath.row][@"title"];
        CGFloat hight1 = [strTitle boundingRectWithSize:CGSizeMake(215, CGFLOAT_MAX)
                                                options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                             attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
                                                context:nil].size.height;
        
        NSString *strContent = _noticeArr[indexPath.row][@"content"];
        CGFloat hight2 = [strContent boundingRectWithSize:CGSizeMake(275, CGFLOAT_MAX)
                                                  options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}
                                                  context:nil].size.height+10+22+10+5;
        if (hight2 > 20) {
            return hight1+15+40+10;
        }
        else
        {
            return hight1+15+20+10;
        }
    }
    else
    {
        //        NSString *strTitle = self.arrContents[indexPath.row][@"context"];
        //        return 25+5+5+[strTitle sizeWithFont:[UIFont systemFontOfSize:13]
        //                           constrainedToSize:CGSizeMake(300, 190) lineBreakMode:NSLineBreakByTruncatingTail].height;
        NSString *strTitle = self.arrContents[indexPath.row][@"title"];
        CGFloat hight1 = [strTitle boundingRectWithSize:CGSizeMake(215, CGFLOAT_MAX)
                                                options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                             attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
                                                context:nil].size.height;
        
        NSString *contentTitle = self.arrContents[indexPath.row][@"context"];
        CGFloat hight2 = [contentTitle boundingRectWithSize:CGSizeMake(275, CGFLOAT_MAX)
                                                    options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                                 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}
                                                    context:nil].size.height;
        if (hight2 > 20) {
            return hight1+15+40+10;
        }
        else
        {
            return hight1+15+20+10;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_tableType isEqualToString:@"notice"]) {
        return self.noticeArr.count;
    }
    return self.arrContents.count;
}

#pragma mark =============  UITableView Delegate  =============

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndexPath = indexPath;
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([_tableType isEqualToString:@"notice"]) {
        //        NSDictionary* dic= self.noticeArr[indexPath.row];
        //        NoteDetailViewController *detailVC = [[NoteDetailViewController alloc] initWithNotice:dic];
        //        [self.rdv_tabBarController.navigationController pushViewController:detailVC animated:YES];
        NSString* nid = _noticeArr[indexPath.row][@"noticeId"];
        [DBDaoMgr updateNoticeById:nid];
        [self selectNoticeDatas];
        [[NSNotificationCenter defaultCenter] postNotificationName:kShouldReQueryCountInit object:nil];
    }
    else
    {
        NoteDetailViewController *detailVC = [[NoteDetailViewController alloc] initWithNibName:nil bundle:nil];
        detailVC.dictNotice = self.arrContents[indexPath.row];
        [self.rdv_tabBarController.navigationController pushViewController:detailVC animated:YES];
    }
}

@end
