|
//
// detailPageViewModel.m
// ThePaperBase
//
// Created by scar1900 on 15/8/3.
// Copyright (c) 2015年 scar1900. All rights reserved.
//
#import "detailPageViewModel.h"
#define getPageInfoTag 100
#define getCommentInfoTag 101
#define getAskInfoTag 102
#define collectTag 1002
#define cancelCollectTag 1003
#define trackTag 1004
#define cancelTrackTag 1005
#define praiseTag 1006
#define refreshPageTag 1007
#define imageLineSpace isPad?@"13":@"5"
#define paragraphSpace isPad?@"30":@"20"
#define imageDescWidth isPad?(float)1320/2:(float)rect_screen.size.width-20
@interface detailPageViewModel()<RemoteDelegate>
@property(nonatomic, assign)NSInteger actionFlag;
@property(nonatomic, strong)contentObjectBO *contentBO;
@end
@implementation detailPageViewModel
@synthesize detailContentBO = _detailContentBO;
@synthesize currentDetaialDB = _currentDetaialDB;
@synthesize actionFlag = _actionFlag;
@synthesize contentBO;
- (instancetype)init {
self = [super init];
if (self) {
self.isOffline = NO;
}
return self;
}
#pragma mark - set and get method
- (void)setActionFlag:(NSInteger)flag {
_actionFlag = flag;
if (flag == 0) {
if ([self.delegate respondsToSelector:@selector(stopHud)]) {
[self.delegate stopHud];
}
}
}
- (void)setDetailContentBO:(contDetailPageVO *)data {
_detailContentBO = data;
self.contentBO = setJsonDicToDataModel(data.content, [contentObjectBO class]);
if ([self.delegate respondsToSelector:@selector(returnDetailPageInfo:)]) {
[self.delegate returnDetailPageInfo:data];
}
}
#pragma mark - core data method
- (void)checkContentDataInCoreData:(NSString*)nodeIDstr tableView:(UITableView*)table{
if (!self.offlineDetailContentBO) {
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc]init];
//为已创建好的实体利用检索到的上下文创建一个实体描述
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ContDetailPageDB"
inManagedObjectContext:[CoreDataManager shareInstance].managedObjectContext];
[request setEntity:entityDescription];
//确定持久库中是否存在与此字段相对应的托管对象,所以穿件一个谓词来确定字段的正确对象:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"contId == %@",nodeIDstr];
[request setPredicate:pred];
ContDetailPageDB *contentDetailPageDB = nil;
NSArray *objs = [[CoreDataManager shareInstance].managedObjectContext executeFetchRequest:request error:&error];
if (objs == nil) {
TPLOG(@"there was an error!!");
}
if (objs.count > 0) {
contentDetailPageDB = [objs objectAtIndex:0];
self.currentDetaialDB = contentDetailPageDB;
contDetailPageVO *data = makeCoreDataModelToRemoteModel(contentDetailPageDB, [contDetailPageVO class]);
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:data.content];
NSMutableDictionary *nodeInfoDic = [NSMutableDictionary dictionaryWithDictionary:dic[@"nodeInfo"]];
if ([[TPUserDefault instance].orderEventTempList containsObject:nodeInfoDic[@"nodeId"]]) {
[nodeInfoDic setValue:@"1" forKey:@"isOrder"];
[dic setValue:nodeInfoDic forKey:@"nodeInfo"];
data.content = dic;
}else {
[nodeInfoDic setValue:@"0" forKey:@"isOrder"];
[dic setValue:nodeInfoDic forKey:@"nodeInfo"];
data.content = dic;
}
self.detailContentBO = data;
TPLOG(@"get from core data first!!");
}else {
[self remoteAction];
return;
}
if ([TPUserDefault instance].lastContentID && [[TPUserDefault instance].lastContentID isEqualToString:nodeIDstr]) {
NSDictionary *dic = @{@"c":nodeIDstr};
self.actionFlag = 2;
[Remote doJsonAction:getCommentInfoTag
requestUrl:contentCommentURL
parameter:dic
delegate:self];
[Remote doJsonAction:getAskInfoTag
requestUrl:contentAskURL
parameter:dic
delegate:self];
[self refreshPageAction];
/**
* bug:5121(新闻中点赞出来后再进入该新闻,点赞数没有增加)
*/
[table setContentOffset:[TPUserDefault instance].lastContentOffset
animated:NO];
}else {
[self remoteAction];
}
}else {
if ([TPUserDefault instance].lastContentID && [[TPUserDefault instance].lastContentID isEqualToString:nodeIDstr]) {
NSDictionary *dic = @{@"c":nodeIDstr};
self.actionFlag = 2;
[Remote doJsonAction:getCommentInfoTag
requestUrl:contentCommentURL
parameter:dic
delegate:self];
[Remote doJsonAction:getAskInfoTag
requestUrl:contentAskURL
parameter:dic
delegate:self];
[table setContentOffset:[TPUserDefault instance].lastContentOffset
animated:NO];
}else {
NSDictionary *dic = @{@"c":nodeIDstr};
self.actionFlag = 2;
[Remote doJsonAction:getCommentInfoTag
requestUrl:contentCommentURL
parameter:dic
delegate:self];
[Remote doJsonAction:getAskInfoTag
requestUrl:contentAskURL
parameter:dic
delegate:self];
}
self.detailContentBO = self.offlineDetailContentBO;
}
}
//操作数据库
-(void) changeDB:(contDetailPageVO *) dataModal{// 新闻详情页: 跟踪和收藏改变状态后,再次进入该页面时,状态没有改变(bug:3925)
if (self.isOffline) {
return;
/**
* bug:5120(离线缓存的新闻无法收藏)
*/
}
if (self.currentDetaialDB) {
[[CoreDataManager shareInstance].managedObjectContext deleteObject:self.currentDetaialDB];
}
self.contentBO = setJsonDicToDataModel(dataModal.content, [contentObjectBO class]);
ContDetailPageDB *coreDataDB = nil;
coreDataDB = [NSEntityDescription insertNewObjectForEntityForName:@"ContDetailPageDB"
inManagedObjectContext:[CoreDataManager shareInstance].managedObjectContext];
coreDataDB = makeRemoteModelToCoreDataModel(dataModal, [contDetailPageVO class],coreDataDB);
coreDataDB.date = getLocalDate();
coreDataDB.contId = self.contentBO.contId;
[[CoreDataManager shareInstance] saveContext];
self.currentDetaialDB = coreDataDB;
}
#pragma mark - remote action
- (void)remoteAction {
self.actionFlag = 3;
NSDictionary *dic = @{@"c":self.nodeID};
[Remote doJsonAction:getPageInfoTag
requestUrl:contentDetailPageURL
parameter:dic
delegate:self];
[Remote doJsonAction:getCommentInfoTag
requestUrl:contentCommentURL
parameter:dic
delegate:self];
[Remote doJsonAction:getAskInfoTag
requestUrl:contentAskURL
parameter:dic
delegate:self];
}
- (void)refreshPageAction {
NSDictionary *dic = @{@"c":self.nodeID};
[Remote doJsonAction:refreshPageTag
requestUrl:contentDetailPageURL
parameter:dic
delegate:self];
}
- (void)trackContent:(void(^)())completion{
if (!self.contentBO) {
return;
}
NSDictionary *dic = @{@"c":self.contentBO.contId};
__weak typeof(self) weakSelf = self;
[Remote doJsonActionWithBlock:trackTag requestUrl:addTrackURL parameter:dic withWaitCursor:YES completion:^(BOOL success, NSString *message, id responseData) {
if (success) {
[MobClick event:@"6"];
NSString *trackKeyWord = weakSelf.contentBO.trackKeyword;
// contDetailPageVO *data = weakSelf.detailContentBO;
// NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:data.content];
// [dict setObject:@"1" forKey:@"isTracked"];
// data.content = dict;
// [weakSelf changeDB:data];
/**
* bug:5049(跟踪,跟踪新闻后回到列表,再次进入,显示未跟踪状态)
*/
ShowTextMessage([NSString stringWithFormat:@"成功跟踪:%@",trackKeyWord]);
if (completion) {
completion();
}
}else {
ShowTextMessage(message);
if ([weakSelf.delegate respondsToSelector:@selector(remoteFail)]) {
[weakSelf.delegate remoteFail:NO];
}
}
}];
}
- (void)collectContent:(void(^)())completion{
if (!self.contentBO) {
return;
}
NSDictionary *dic = @{@"cids":self.contentBO.contId};
__weak typeof(self) weakSelf = self;
[Remote doJsonActionWithBlock:collectTag requestUrl:addFavoriteURL parameter:dic withWaitCursor:YES completion:^(BOOL success, NSString *message, id responseData) {
if (success) {
[MobClick event:@"7"];
ShowMessage(@"收藏成功", YES);
// contDetailPageVO *data = self.detailContentBO;
// NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:data.content];
// [dict setObject:@"1" forKey:@"isFavorited"];
// data.content = dict;
// [self changeDB:data];
if (completion) {
completion();
}
}else {
ShowTextMessage(message);
if ([weakSelf.delegate respondsToSelector:@selector(remoteFail)]) {
[weakSelf.delegate remoteFail:NO];
}
}
}];
}
- (void)cancelTrackContent:(void(^)())completion{
if (!self.contentBO) {
return;
}
NSDictionary *dic = @{@"c":self.contentBO.contId};
__weak typeof(self) weakSelf = self;
[Remote doJsonActionWithBlock:cancelTrackTag requestUrl:cancelTrackURL parameter:dic withWaitCursor:YES completion:^(BOOL success, NSString *message, id responseData) {
if (success) {
NSString *trackKeyWord = weakSelf.contentBO.trackKeyword;
// contDetailPageVO *data = weakSelf.detailContentBO;
// NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:data.content];
// [dict setObject:@"0" forKey:@"isTracked"];
// data.content = dict;
// [weakSelf changeDB:data];
ShowTextMessage([NSString stringWithFormat:@"取消跟踪:%@",trackKeyWord]);
if (completion) {
completion();
}
}else {
ShowTextMessage(message);
if ([weakSelf.delegate respondsToSelector:@selector(remoteFail)]) {
[weakSelf.delegate remoteFail:NO];
}
}
}];
}
- (void)cancelCollect:(void(^)())completion{
if (!self.contentBO) {
return;
}
NSDictionary *dic = @{@"cids":self.contentBO.contId};
__weak typeof(self) weakSelf = self;
[Remote doJsonActionWithBlock:cancelCollectTag requestUrl:deleteFavoriteURL parameter:dic withWaitCursor:YES completion:^(BOOL success, NSString *message, id responseData) {
if (success) {
ShowMessage(@"取消收藏", YES);
// contDetailPageVO *data = weakSelf.detailContentBO;
// NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:data.content];
// [dict setObject:@"0" forKey:@"isFavorited"];
// data.content = dict;
// [weakSelf changeDB:data];
if (completion) {
completion();
}
}else {
ShowTextMessage(message);
if ([weakSelf.delegate respondsToSelector:@selector(remoteFail)]) {
[weakSelf.delegate remoteFail:NO];
}
}
}];
}
- (void)praiseHandler:(UIButton*)btn
completion:(void(^)(BOOL success,NSString *message,id responseData))completion {
if (!self.contentBO) {
return;
}
NSDictionary *dic = @{@"c":self.contentBO.contId};
[Remote doJsonActionWithBlock:2000 requestUrl:contentPraiseURL parameter:dic withWaitCursor:NO completion:^(BOOL success, NSString *message, id responseData) {
//
// contDetailPageVO *data = weakSelf.detailContentBO;
// NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.detailContentBO.content];
// [dict setObject:weakSelf.praiseTimes forKey:@"praiseTimes"];
// data.content = dict;
// [weakSelf changeDB:data];
if (completion) {
completion(success,message,responseData);
}
}];
}
#pragma mark - tools
- (NSMutableAttributedString *)returnContentTextString:(NSString*)str {
NSArray *colorList = [str componentsMatchedByRegex:@"\\<[C]\\:[0-9A-Za-z]{6}>"];
__block NSString *oriStr = str;
[colorList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString* hexStr = [obj stringByMatching:@"[0-9A-Za-z]{6}"];
NSString *replacedStr = [NSString stringWithFormat:@"<color value=\"#%@\">",hexStr];
oriStr = [oriStr stringByReplacingOccurrencesOfRegex:obj withString:replacedStr];
}];
str = oriStr;
str = [str stringByReplacingOccurrencesOfString:@"<N>" withString:@"</>"];
// if (![str isMatchedByRegex:@"/font"]) {//修复bug:4487
// str = [str stringByAppendingString:@"</font>"];
// }
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
// paragraphStyle.lineSpacing = [imageLineSpace floatValue];// 字体的行间距
paragraphStyle.lineSpacing = [ipadLineAndParaSpace liveLineSpace];//(bug:5663)
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
// appFont([TPUserDefault instance].contFontSize, NO), NSFontAttributeName,
paragraphStyle,NSParagraphStyleAttributeName,
// [UIColor colorWithHexString:TextBlack],NSForegroundColorAttributeName,
nil];
NSAttributedString *tempStr = attributedStringWithHtml(str);
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc]initWithAttributedString:tempStr];
NSRange range = NSMakeRange(0, tempStr.length);
[attributeStr addAttributes:attributes range:range];
return attributeStr;
}
- (CGFloat)returnContentExtendHeight:(NSString*)str {
BOOL isHaveDesc = NO;
if (!isBlankString(str)) {
isHaveDesc = YES;
}
if (isHaveDesc) {
CGFloat descHeight = returnTextHeightWithRTLabel(str, imageDescWidth, appFont(TEXT_FOUR_LEVELSIZE, NO), [ipadLineAndParaSpace liveLineSpace]);
return descHeight + [ipadLineAndParaSpace newsColumSpace]+5;
}else {
return [ipadLineAndParaSpace imgLineSpace]/2;//(图片与下面文字间距减小)
}
}
#pragma mark - remote delegate
- (void)startWaitCursor:(int)actionTag {
}
- (void)stopWaitCursor:(int)actionTag {
}
- (void)remoteResponsSuccess:(int)actionTag withResponsData:(id)responsData {
if (actionTag == getPageInfoTag) { //主数据源
self.actionFlag = self.actionFlag -1;
contDetailPageVO* dataModal = setJsonDicToDataModel(responsData, [contDetailPageVO class]);
self.detailContentBO = dataModal?dataModal:nil;
[self changeDB:dataModal];
}else if (actionTag == refreshPageTag) {
contDetailPageVO* dataModal = setJsonDicToDataModel(responsData, [contDetailPageVO class]);
contentObjectBO *content = setJsonDicToDataModel(dataModal.content, [contentBO class]);
if ([self.delegate respondsToSelector:@selector(refreshDetailPage:)]) {
[self.delegate refreshDetailPage:content];
}
}else if (actionTag == getCommentInfoTag) {//评论
self.actionFlag = self.actionFlag -1;
NSMutableArray* commentList = [NSMutableArray array];
NSMutableArray *hotList = [NSMutableArray array];
NSArray *list = responsData[@"commentList"];
NSArray *hotDicList = responsData[@"hotList"];
[list enumerateObjectsUsingBlock:^(NSDictionary* obj, NSUInteger idx, BOOL *stop) {
commentObjectVO *commentBO = setJsonDicToDataModel(obj, [commentObjectVO class]);
commentBO = setStrSpaceForParagraphSpacingWithCommentBO(commentBO);
[commentList addObject:commentBO];
}];
[hotDicList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
commentObjectVO *commentBO = setJsonDicToDataModel(obj, [commentObjectVO class]);
commentBO = setStrSpaceForParagraphSpacingWithCommentBO(commentBO);
[hotList addObject:commentBO];
}];
NSMutableArray *commentDataList = [NSMutableArray array];
if (hotList.count > 0) {
[commentDataList addObject:hotList];
}
[commentDataList addObject:commentList];
if ([self.delegate respondsToSelector:@selector(returnCommentList:nodeId:nextUrl:commentTotalRecord:)]) {
NSMutableArray *array = [NSMutableArray array];
array = [NSMutableArray arrayWithArray:commentDataList];
[self.delegate returnCommentList:array
nodeId:self.nodeID
nextUrl:responsData[@"nextUrl"]
commentTotalRecord:[responsData[@"recordTotal"] integerValue]];
}
}else if (actionTag == getAskInfoTag) {//热追问
self.actionFlag = self.actionFlag -1;
NSMutableDictionary *qaDataDic = [NSMutableDictionary dictionary];
NSArray *hotQaList = responsData[@"hotQaList"];
NSMutableArray *hotQaArray = [NSMutableArray array];
[hotQaList enumerateObjectsUsingBlock:^(NSDictionary* obj, NSUInteger idx, BOOL *stop) {
commentObjectVO *commentBO = setJsonDicToDataModel(obj, [commentObjectVO class]);
commentBO = setStrSpaceForParagraphSpacingWithCommentBO(commentBO);
[hotQaArray addObject:commentBO];
}];
[qaDataDic setValue:hotQaArray forKey:@"hotQaList"];
NSArray *qaTempList = responsData[@"qaList"];
NSMutableArray *qaArray = [NSMutableArray array];
[qaTempList enumerateObjectsUsingBlock:^(NSDictionary* obj, NSUInteger idx, BOOL *stop) {
commentObjectVO *commentBO = setJsonDicToDataModel(obj, [commentObjectVO class]);
commentBO = setStrSpaceForParagraphSpacingWithCommentBO(commentBO);
[qaArray addObject:commentBO];
}];
[qaDataDic setValue:qaArray forKey:@"qaList"];
if ([self.delegate respondsToSelector:@selector(returnHotAskDic:nodeId:nextUrl:askTotalRecord:)]) {
[self.delegate returnHotAskDic:qaDataDic
nodeId:self.nodeID
nextUrl:responsData[@"nextUrl"]
askTotalRecord:[responsData[@"qaNum"] integerValue]];
}
}else if (actionTag == trackTag) {// 新闻详情页: 跟踪和收藏改变状态后,再次进入该页面时,状态没有改变(bug:3925)
if ([self.delegate respondsToSelector:@selector(stopHud)]) {
[self.delegate stopHud];
}
NSString *trackKeyWord = self.contentBO.trackKeyword;
// contDetailPageVO *data = self.detailContentBO;
// NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.detailContentBO.content];
// [dict setObject:@"1" forKey:@"isTracked"];
// data.content = dict;
// [self changeDB:data];
ShowTextMessage([NSString stringWithFormat:@"成功跟踪:%@",trackKeyWord]);
if ([self.delegate respondsToSelector:@selector(trackResult:)]) {
[self.delegate trackResult:YES];
}
}
}
- (void)remoteResponsFailed:(int)actionTag withMessage:(NSString *)message resultCode:(NSString *)code {
if ([code intValue] == 5) {
if ([self.delegate respondsToSelector:@selector(contentHaveOffline)]) {
[self.delegate contentHaveOffline];
}
}else {
BOOL isTimeOut = NO;
if (actionTag == getPageInfoTag && [message isEqualToString:@"请求超时,请稍后重试!"]) {
isTimeOut = YES;
}else {
ShowTextMessage(message);
}
if ([message isEqualToString:noNetworkMessage]) {
isTimeOut = YES;
}
if ([self.delegate respondsToSelector:@selector(remoteFail:)]) {
[self.delegate remoteFail:isTimeOut];
}
}
}
@end
|