//
//  AnnoDetailViewController.m
//  redstar
//
//  Created by admin on 15/11/30.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "AnnoDetailViewController.h"
#import "AnnounceDetailHeadView.h"
#import "AnnoContentTableViewCell.h"
#import "AnnounceDetailFootView.h"
#import "AttachmentModel.h"
#import "ReaderViewController.h"


#import "HttpClient.h"

#import "AnnounceDetailModel.h"

#import "AttachmentTableViewCell.h"

#import <AFNetworking.h>

#define kAnnounceContentCell @"AnnoContentTableViewCell"
#define kAttachmentTableViewCell @"AttachmentTableViewCell"
@interface AnnoDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, ReaderViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) AnnounceDetailHeadView *headerView;
@property (nonatomic, strong) AnnounceDetailFootView *footerView;
@property (nonatomic, strong) AnnounceDetailModel *annoDetail;

@property (nonatomic, strong) NSMutableArray *attachmentArray;
@end

@implementation AnnoDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.attachmentArray = [NSMutableArray array];
    
    [self setNav];
    
    [self requestAnnoDetail];
    
    [self settingYetRead];
}

- (void)requestAnnoDetail
{
    NSString *url = [NSString stringWithFormat:@"%@%@%@", kRedStarURL, kAnnounceDetailURL, self.affiche_uuid];
    HttpClient *httpCilent = [[HttpClient alloc] initWithUrl:url];
    [httpCilent getAnnounceDetailWithCompletion:^(id response, NSError *error) {
        NSDictionary *dict = response[@"data"];
        AnnounceDetailModel *annoDetail = [AnnounceDetailModel announceDetailModelWithDict:dict];
        _annoDetail = annoDetail;
        
        for (NSDictionary *attachmentDict in _annoDetail.attachmentUrls) {
            AttachmentModel *atta = [[AttachmentModel alloc] init];
            [atta setValuesForKeysWithDictionary:attachmentDict];
            [_attachmentArray addObject:atta];
        }
        
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
    }];
}

- (void)settingYetRead
{
    NSString *user_uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_uuid"];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:date];
    NSString *url = [NSString stringWithFormat:@"%@%@%@?user_uuid=%@&read_time=%@", kRedStarURL, kAnnounceYetReadURL, self.affiche_uuid, user_uuid, dateString];
    url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

    HttpClient *httpCilent = [[HttpClient alloc] initWithUrl:url];
    [httpCilent settingAnnounceYetReadWithCompletion:^(id response, NSError *error) {
    }];
}

// 返回上一页面
- (void)doBack:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setNav
{
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"公告"];
    customLab.font = [UIFont boldSystemFontOfSize:19];
    self.navigationItem.titleView = customLab;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 44);
    [backBtn setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
}

- (void)showFile:(UIButton *)sender
{
    NSInteger row = sender.tag - 998473;
    AttachmentModel *atta = _attachmentArray[row];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = paths.lastObject;
    NSString *url = [NSString stringWithFormat:@"%@/%@", path, atta.fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:url]) {
        
        
        NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
        
        
        ReaderDocument *document = [ReaderDocument withDocumentFilePath:url password:phrase];
        
        if (document != nil) // Must have a valid ReaderDocument object in order to proceed with things
        {
            ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
            readerViewController.delegate = self; // Set the ReaderViewController delegate to self
            
            [self.navigationController pushViewController:readerViewController animated:YES];
        }

    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"文件不存在，请下载后再查看！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

- (void)dismissReaderViewController:(ReaderViewController *)viewController
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
    
}


- (void)downloadFile:(UIButton *)sender
{
    NSInteger row = sender.tag - 998473;
    AttachmentModel *atta = _attachmentArray[row];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = paths.lastObject;
    
    NSString *fileName = [NSString stringWithFormat:@"%@", atta.fileName];
    [self downloadFileURL:[NSString stringWithFormat:@"%@%@", kRedStarURL, atta.fileUrl] savePath:path fileName:fileName];
}


- (void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath fileName:(NSString *)aFileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //检查本地文件是否已存在
    NSString *fileName = [NSString stringWithFormat:@"%@/%@", aSavePath, aFileName];
    //检查附件是否存在
    if ([fileManager fileExistsAtPath:fileName]) {
    }else{
        
        //创建附件存储目录
        if (![fileManager fileExistsAtPath:aSavePath]) {
            [fileManager createDirectoryAtPath:aSavePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        //下载附件
        aUrl = [aUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        NSURL *url = [[NSURL alloc] initWithString:aUrl];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.inputStream   = [NSInputStream inputStreamWithURL:url];
        operation.outputStream  = [NSOutputStream outputStreamToFileAtPath:fileName append:NO];
        
        //下载进度控制
        
        //已完成下载
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            [self.tableView reloadData];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"下载失败！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            
            [self.tableView reloadData];
            
        }];
        
        [operation start];
    }
}


#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 66690) {
        if (buttonIndex == 0) {
            [self.tableView reloadData];
        }
    }
}

#pragma mark - UITableView Delegate/DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        return _attachmentArray.count;
    }
}

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AnnoContentTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kAnnounceContentCell];
        if (!cell) {
            cell = [[AnnoContentTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAnnounceContentCell];
        }
        cell.titleLabel.text = @"内容";
        
        NSString *str = [NSString stringWithFormat:@"<style> html{ font-size: 15px; color: #444444 } </style>%@", _annoDetail.content];
        NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
        cell.contentLabel.attributedText = attrStr;
        
        cell.backgroundColor = kAnnounceHeaderColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        AttachmentTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kAttachmentTableViewCell];
        if (!cell) {
            cell = [[AttachmentTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAttachmentTableViewCell];
        }
        AttachmentModel *atta = _attachmentArray[indexPath.row];
        NSString *name = atta.fileName;
        [cell.nameBtn setTitle:name forState:UIControlStateNormal];
        
        
        [cell.nameBtn addTarget:self action:@selector(showFile:) forControlEvents:UIControlEventTouchUpInside];
        [cell.downloadBtn addTarget:self action:@selector(downloadFile:) forControlEvents:UIControlEventTouchUpInside];
        cell.downloadBtn.tag = 998473 + indexPath.row;
        cell.nameBtn.tag = 998473 + indexPath.row;
        
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = paths.lastObject;
        NSString *url = [NSString stringWithFormat:@"%@/%@", path, atta.fileName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:url]) {
            cell.downloadBtn.selected = YES;
            cell.downloadBtn.backgroundColor = [UIColor grayColor];
        } else {
            cell.downloadBtn.selected = NO;
            cell.downloadBtn.backgroundColor = [UIColor colorWithRed:47 / 255.0 green:209/ 255.0 blue:92 / 255.0 alpha:1.0];

        }

        return cell;
    }
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 100.0;
        _tableView.tableHeaderView = self.headerView;
        [_tableView registerClass:[AnnoContentTableViewCell class] forCellReuseIdentifier:kAnnounceContentCell];
        [_tableView registerClass:[AttachmentTableViewCell class] forCellReuseIdentifier:kAttachmentTableViewCell];
        [self.view addSubview:_tableView];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        [self.view addConstraint:tableTop];
        
        NSLayoutConstraint *tableLeft = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        [self.view addConstraint:tableLeft];
        
        NSLayoutConstraint *tableRight = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self.view addConstraint:tableRight];
        
        NSLayoutConstraint *tableBottom = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        [self.view addConstraint:tableBottom];
    }
    return _tableView;
}

- (AnnounceDetailHeadView *)headerView
{
    if (!_headerView) {
        _headerView = [[AnnounceDetailHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 120)];
        _headerView.backgroundColor = kAnnounceHeaderColor;
        _headerView.annoDetail = _annoDetail;
        }
    return _headerView;
}

- (AnnounceDetailFootView *)footerView
{
    if (!_footerView) {
        _footerView = [[AnnounceDetailFootView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    }
    return _footerView;
}

@end
