//
//  DBDaoMgr.m
//  TaiZhouTobacco_7s
//
//  Created by JianjiYuan on 14-8-27.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "DBDaoMgr.h"
#import <NSString+MD5.h>

@implementation DBDaoMgr

// ================= 通用方法 =================

+ (NSString *)convertArrayToString:(NSArray *)array
{
    BOOL isFirst = YES;
    NSMutableString *strTemp = [NSMutableString string];
    for (NSString *strItem in array) {
        if (isFirst) {
            [strTemp appendFormat:@"%@", strItem];
        }else {
            [strTemp appendFormat:@",%@", strItem];
        }
        isFirst = NO;
    }
    return strTemp;
}

+ (NSString *)getMaxTimeFromTable:(NSString *)table
{
    NSString *sql = [NSString stringWithFormat:@"SELECT MAX(createTime) FROM %@;", table];
    NSArray *results = [[BaseDao getInstance] excuteSelectBySQL:sql];
    DLog(@"results  %@", results);
    if (results.count > 0) {
        NSString *createTime = [[[results firstObject] valueForKey:@"MAX(createTime)"] validDataOfClass:[NSString class]];
        if ([createTime isEqualToString:@""]) {
            return @"1970-01-01 00:00:00";
        }
        return createTime;
    }
    return @"1970-01-01 00:00:00";
}

+ (NSString *)getMaxTimeFromTable:(NSString *)table conditions:(NSDictionary *)conditions
{
    NSMutableString *sql = [NSMutableString stringWithFormat:@"SELECT MAX(createTime) FROM %@", table];
    
    if (conditions && conditions.allKeys.count > 0) {
        [sql appendString:@" WHERE "];
        BOOL isFirst = YES;
        for (NSString *key in conditions.allKeys) {
            if (isFirst) {
                [sql appendFormat:@"%@ == '%@'", key, conditions[key]];
            }else {
                [sql appendFormat:@"AND %@ == '%@'", key, conditions[key]];
            }
            isFirst = NO;
        }

    }
    
    NSArray *results = [[BaseDao getInstance] excuteSelectBySQL:sql];
    if (results.count > 0) {
        NSString *createTime = [[[results firstObject] valueForKey:@"MAX(createTime)"] validDataOfClass:[NSString class]];
        if ([createTime isEqualToString:@""]) {
            return @"1970-01-01 00:00:00";
        }
        return createTime;
    }
    return @"1970-01-01 00:00:00";
}

+ (NSString *)getMaxTimeBySql:(NSString *)sql
{
    NSArray *results = [[BaseDao getInstance] excuteSelectBySQL:sql];
    if (results.count > 0) {
        NSString *createTime = [[[results firstObject] valueForKey:@"MAX(createTime)"] validDataOfClass:[NSString class]];
        if ([createTime isEqualToString:@""]) {
            return @"1970-01-01 00:00:00";
        }
        return createTime;
    }
    return @"1970-01-01 00:00:00";
}
// ================= 通知 =================
+ (BOOL)insertNotice:(NSDictionary *)dic
{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDateFormatter *inputFormatter1 = [[NSDateFormatter alloc] init];
    [inputFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString* dateStr = [inputFormatter stringFromDate:[NSDate date]];
    
    NSString* md5Str = [NSString stringWithFormat:@"%@%@",[inputFormatter1 stringFromDate:[NSDate date]],[DataMgr getInstance].userID];
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_notice (userID, time, type, title, content, id, isRead,noticeId) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@');",[DataMgr getInstance].userID,dateStr,dic[@"type"],dic[@"title"],dic[@"content"],dic[@"id"],@"NO",[md5Str MD5Digest]];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeInsert];
//    return YES;
}

+ (NSArray *)fetchNoticeByUserId:(NSString *)userID
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_notice WHERE userID = '%@' and type != '16006' order by isRead,time desc;",userID];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchUnReadNoticeByUserId:(NSString *)userID
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_notice WHERE userID = '%@' and isRead = 'NO' order by isRead,time desc;",userID];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchBackGroundMusic:(NSString *)userID
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_notice WHERE userID = '%@' and type == '16006' order by isRead,time desc;",userID];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (BOOL)updateNoticeById:(NSString *)nid
{
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_notice SET isRead = 'YES' WHERE noticeId == '%@';", nid];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}

+ (BOOL)deleteNoticeByUserID:(NSString*)userID andNoticeID:(NSString*)noticeID
{
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM t_notice WHERE userID == '%@' and noticeId == '%@';",userID,noticeID];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}
// ================= 指导书信息 =================
+ (BOOL)insertInstructionBookInfo:(NSString *)totalBytesRead andTotalBytesExpectedToRead:(NSString*)totalBytesExpectedToRead andName:(NSString*)name andTaskStartTime:(NSString*)taskStartTime andTaskEndTime:(NSString*)taskEndTime
{
    //taskStartTime taskEndTime creatTime
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_FileInfo (totalBytesRead, totalBytesExpectedToRead, fileName,isDownLoadSuccess,taskStartTime,taskEndTime,creatTime) VALUES ('%@','%@','%@','%@','%@','%@','%@');",totalBytesRead,totalBytesExpectedToRead,name,@"No",taskStartTime,taskEndTime,[NSDate date]];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeInsert];
}

+ (NSArray *)fetchAllInstructionBookInfo
{
    NSString *sql = @"SELECT * FROM t_FileInfo";
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchInstructionBookInfoByName:(NSString *)name
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_FileInfo WHERE fileName = '%@';",name];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (BOOL)updateInstructionBookInfoSize:(NSString*)size ByName:(NSString *)name
{
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_FileInfo SET totalBytesRead = '%@' WHERE fileName == '%@';",size,name];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}

+ (BOOL)updateInstructionBookInfoStatus:(NSString*)status ByName:(NSString *)name
{
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_FileInfo SET isDownLoadSuccess = '%@' WHERE fileName == '%@';",status,name];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}

+ (BOOL)deleteInstructionBookInfoByName:(NSString *)name
{
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM t_FileInfo WHERE fileName == '%@';",name];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}
// ================= 图片 =================

+ (BOOL)insertImages:(NSArray *)images 
{
    NSMutableArray *sqls = [NSMutableArray array];
    for (NSDictionary *imageObj in images) {
        NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM t_image WHERE id == '%@';", [imageObj valueForKey:@"id"]];
        NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
        if (arrResults.count > 0) {
            continue;
        }
        NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_image (id, type, imageURL, imagePath, checkPointId, uploadFlag, createTime) VALUES ('%@','%@','%@','%@','%@','%@','%@');", [imageObj valueForKey:@"id"], [imageObj valueForKey:@"type"], [imageObj valueForKey:@"imageURL"], [imageObj valueForKey:@"imagePath"],[imageObj valueForKey:@"checkPointId"],@"0", [DataMgr stringFromDate:[NSDate date] format:@"yyyy-MM-dd HH:mm:ss"]];
        [sqls addObject:sql];
    }
    return [[BaseDao getInstance] excuteSQLs:sqls operateType:DaoOperateTypeInsert];
}

+ (NSArray *)fetchImagesByIds:(NSArray *)images
{
    BOOL isFirst = YES;
    NSMutableString *strTemp = [NSMutableString string];
    for (NSDictionary *imageObj in images) {
        if (isFirst) {
            [strTemp appendFormat:@"'%@'", [imageObj valueForKey:@"id"]];
        }else {
            [strTemp appendFormat:@",'%@'", [imageObj valueForKey:@"id"]];
        }
        isFirst = NO;
    }
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_image WHERE id IN (%@);", strTemp];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchImagesByType:(NSString *)type checkPointId:(NSString *)checkPointId
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_image WHERE type = '%@' AND checkPointId = '%@' AND uploadFlag = '0';", type, checkPointId];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchUnUploadedImageIdsByType:(NSString *)type
{
    NSString *sql = [NSString stringWithFormat:@"SELECT checkPointId FROM t_image WHERE type = '%@'  AND uploadFlag = '0';", type];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (BOOL)updateImageTagUploaded:(NSString *)uid
{
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_image SET uploadFlag = '1' WHERE id == '%@';", uid];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}

+ (BOOL)updateImagesTagUploaded:(NSArray *)images
{
    BOOL isFirst = YES;
    NSMutableString *strTemp = [NSMutableString string];
    for (NSDictionary *imageObj in images) {
        if (isFirst) {
            [strTemp appendFormat:@"'%@'", [imageObj valueForKey:@"id"]];
        }else {
            [strTemp appendFormat:@",'%@'", [imageObj valueForKey:@"id"]];
        }
        isFirst = NO;
    }
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_image SET uploadFlag = '1' WHERE id IN (%@);", strTemp];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}

// ================= 检查点 =================

+ (BOOL)insertCheckPointInfos:(NSArray *)checkInfos
{
    NSMutableArray *sqls = [NSMutableArray array];
    for (NSDictionary *dictCheck in checkInfos) {
        
        NSString *strId = [NSString stringWithFormat:@"%@%@", [dictCheck valueForKey:@"checkPointId"], [dictCheck valueForKey:@"type"]];
        NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM t_checkpoint WHERE id == '%@';", strId];
        NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
        if (arrResults.count > 0) {
            continue;
        }
        NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_checkpoint (id, checkPointId, type, remark, amount, location, uploadFlag) VALUES ('%@','%@','%@','%@','%@','%@','%@');", strId, [dictCheck valueForKey:@"checkPointId"], [dictCheck valueForKey:@"type"], [dictCheck valueForKey:@"remark"], [dictCheck valueForKey:@"amount"],[dictCheck valueForKey:@"location"], @"0"];
        [sqls addObject:sql];
    }
    return [[BaseDao getInstance] excuteSQLs:sqls operateType:DaoOperateTypeInsert];
}

+ (NSArray *)fetchCheckPointInfosByIds:(NSArray *)checkInfoIds
{
    BOOL isFirst = YES;
    NSMutableString *strTemp = [NSMutableString string];
    for (NSDictionary *dictCheck in checkInfoIds) {
        if (isFirst) {
            [strTemp appendFormat:@"'%@'", [dictCheck valueForKey:@"id"]];
        }else {
            [strTemp appendFormat:@",'%@'", [dictCheck valueForKey:@"id"]];
        }
        isFirst = NO;
    }
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_checkpoint WHERE id IN (%@);", strTemp];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchCheckPointInfoByType:(NSString *)type checkPointId:(NSString *)checkPointId
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_checkpoint WHERE type = '%@' AND checkPointId = '%@' AND uploadFlag = '0';", type, checkPointId];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchUnUploadedCheckPointIdsByType:(NSString *)type
{
    NSString *sql = [NSString stringWithFormat:@"SELECT checkPointId FROM t_checkpoint WHERE type = '%@'  AND uploadFlag = '0';", type];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (BOOL)updateCheckPointTagUploaded:(NSString *)checkId
{
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_checkpoint SET uploadFlag = '1' WHERE id == '%@';", checkId];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}

+ (BOOL)updateCheckPointInfosTagUploaded:(NSArray *)checkPointIds
{
    BOOL isFirst = YES;
    NSMutableString *strTemp = [NSMutableString string];
    for (NSDictionary *dictCheck in checkPointIds) {
        if (isFirst) {
            [strTemp appendFormat:@"'%@'", [dictCheck valueForKey:@"id"]];
        }else {
            [strTemp appendFormat:@",'%@'", [dictCheck valueForKey:@"id"]];
        }
        isFirst = NO;
    }
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_checkpoint SET uploadFlag = '1' WHERE id IN (%@);", strTemp];
    return [[BaseDao getInstance] excuteSQL:sql operateType:DaoOperateTypeUpdate];
}


#if 0
// ================= 检查标准 =================

+ (BOOL)insertTaskCheckStandards:(NSArray *)standards
{
    FMDatabase *db = [DBInstance getInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        for (NSObject *obj in standards) {
            
            NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM T_Task_Standard WHERE standardId == '%@';", [obj valueForKey:@"standardId"]];
            NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
            if (arrResults.count > 0) {
                NSString *sql = [NSString stringWithFormat:@"UPDATE T_Task_Standard SET standardType = '%@',standardContent = '%@',standardDesc = '%@',createTime = '%@' WHERE standardId == '%@';", [obj valueForKey:@"standardType"],[obj valueForKey:@"standardContent"],[obj valueForKey:@"standardDesc"],[obj valueForKey:@"createTime"], [obj valueForKey:@"standardId"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }else {
                NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Task_Standard (standardId, standardType, standardContent, standardDesc, createTime) VALUES ('%@','%@','%@','%@','%@')", [obj valueForKey:@"standardId"], [obj valueForKey:@"standardType"],[obj valueForKey:@"standardContent"],[obj valueForKey:@"standardDesc"],[obj valueForKey:@"createTime"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }
            

        }
	}
	@catch (NSException *exception) {
		DLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

+ (NSArray *)fetchAllTaskCheckStandards
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Task_Standard"];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fetchTaskCheckStandardsByIds:(NSArray *)standardIds
{
    BOOL isFirst = YES;
    NSMutableString *strTemp = [NSMutableString string];
    for (NSString *strItem in standardIds) {
        if (isFirst) {
            [strTemp appendFormat:@"'%@'", strItem];
        }else {
            [strTemp appendFormat:@",'%@'", strItem];
        }
        isFirst = NO;
    }
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Task_Standard WHERE standardId IN (%@);", strTemp];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (BOOL)insertLogisticsStandards:(NSArray *)standards
{
    FMDatabase *db = [DBInstance getInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        for (NSObject *obj in standards) {
            
            NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Standard WHERE uid == '%@';", [obj valueForKey:@"id"]];
            NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
            if (arrResults.count > 0) {
                NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Standard SET creatorId = '%@',createTime = '%@',typeId = '%@',inspectPlace = '%@',inspectMethod = '%@',inspectContent = '%@',remark = '%@',coid = '%@',recordStatus = '%@' WHERE standardId == '%@';", [obj valueForKey:@"creatorId"],[obj valueForKey:@"createTime"],[obj valueForKey:@"typeId"],[obj valueForKey:@"inspectPlace"], [obj valueForKey:@"inspectMethod"], [obj valueForKey:@"inspectContent"], [obj valueForKey:@"remark"], [obj valueForKey:@"coid"], [obj valueForKey:@"recordStatus"], [obj valueForKey:@"id"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }else {
                NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Logistics_Standard (uid, creatorId, createTime, typeId, inspectPlace, inspectMethod, inspectContent, remark, coid, recordStatus) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')", [obj valueForKey:@"id"], [obj valueForKey:@"creatorId"],[obj valueForKey:@"createTime"],[obj valueForKey:@"typeId"], [obj valueForKey:@"inspectPlace"], [obj valueForKey:@"inspectMethod"],[obj valueForKey:@"inspectContent"],[obj valueForKey:@"remark"],[obj valueForKey:@"coid"],[obj valueForKey:@"recordStatus"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }
        }
	}
	@catch (NSException *exception) {
		DLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

+ (NSArray *)fectchLogisticsStandardsByType:(NSString *)equipType
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Standard WHERE typeId == '%@';", equipType];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (NSArray *)fectchLogisticsStandardsByIds:(NSArray *)ids
{
    BOOL isFirst = YES;
    NSMutableString *strTemp = [NSMutableString string];
    for (NSString *strItem in ids) {
        if (isFirst) {
            [strTemp appendFormat:@"'%@'", strItem];
        }else {
            [strTemp appendFormat:@",'%@'", strItem];
        }
        isFirst = NO;
    }
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Standard WHERE uid IN (%@);", strTemp];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

// ================= 主页菜单 =================

+ (NSArray *)fectchAllModules
{
    return [[BaseDao getInstance] selectAllDatasFromTable:kTableName_T_7s_Module];
}

+ (NSArray *)fectchModulesByMenu:(NSString *)menu
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_7s_Module WHERE menuId IN (0,%@);", menu];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

// ================= 任务检查 =================

+ (BOOL)insertTaskChecks:(NSArray *)taskChecks
{
    FMDatabase *db = [DBInstance getInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        for (NSObject *obj in taskChecks) {
            
            NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM T_Task_Check WHERE uid == '%@';", [obj valueForKey:@"id"]];
            NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
            
            NSString *strStandardIds = nil;
            NSObject *standardIds = [obj valueForKey:@"standardIds"];
            if ([standardIds isKindOfClass:[NSArray class]]
                && standardIds != [NSNull null]
                && ((NSArray *)standardIds).count > 0) {
                strStandardIds = [(NSArray *)standardIds componentsJoinedByString:@","];
            }
            
            if (arrResults.count > 0) {
                NSString *sql = [NSString stringWithFormat:@"UPDATE T_Task_Check SET placeCode = '%@',placeDesc = '%@',location = '%@',management = '%@',checkType = '%@',taskingTime = '%@',completionTime = '%@',standardIds = '%@',createTime = '%@',standardIds = '%@', uploadFlag = '%@' WHERE uid == '%@';", [obj valueForKey:@"placeCode"],[obj valueForKey:@"placeDesc"],[obj valueForKey:@"location"],[obj valueForKey:@"management"], [obj valueForKey:@"checkType"], [obj valueForKey:@"taskingTime"], [obj valueForKey:@"completionTime"], [obj valueForKey:@"standardIds"], [obj valueForKey:@"createTime"],strStandardIds, [obj valueForKey:@"recordStatus"], [obj valueForKey:@"id"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }else {
                NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Task_Check (uid, placeCode, placeDesc, location, management, checkType, taskingTime, completionTime, standardIds, createTime, userId, uploadFlag) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",
                                 [obj valueForKey:@"id"], [obj valueForKey:@"placeCode"],[obj valueForKey:@"placeDesc"],
                                 [obj valueForKey:@"location"],[obj valueForKey:@"management"],[obj valueForKey:@"checkType"],
                                 [obj valueForKey:@"taskingTime"],[obj valueForKey:@"completionTime"],strStandardIds,[obj valueForKey:@"createTime"],[DataMgr sharedInstance].userId, [obj valueForKey:@"recordStatus"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }
            
        }
	}
	@catch (NSException *exception) {
		DLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
	return result;
}

+ (NSArray *)fectchAllTaskChecks
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Task_Check WHERE isTempCheck ISNULL AND inventoryStatus ISNULL  AND (uploadFlag == '0' OR uploadFlag ISNULL) AND userId == '%@';", [DataMgr get].userId];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

+ (BOOL)updateTaskCheckById:(NSString *)taskId withStandardIds:(NSArray *)standardIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *status = standardIds.count>0?@"0":@"1";
        NSString *strStandardIds = [self convertArrayToString:standardIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Task_Check SET selectedStdIds = '%@', inventoryTime = '%@', inventoryStatus = '%@' WHERE uid == '%@'", strStandardIds, [[NSDate date] stringFromDateFormat:kDateFormatSecond], status, taskId];
        result = result && [db executeUpdate:sql];
	}
	@catch (NSException *exception) {
		DLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

+ (BOOL)updateTaskCheckById:(NSString *)taskId withImageIds:(NSArray *)imageIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *strimageIds = [self convertArrayToString:imageIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Task_Check SET imageIds = '%@' WHERE uid == '%@'", strimageIds, taskId];
        result = result && [db executeUpdate:sql];
        
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

// ================= 临时检查 =================

+ (BOOL)insertTempCheck:(NSObject *)obj
{
    BOOL result = YES;
    
    FMDatabase *db = [DBMgr sharedInstance].db;
	@try {
		[db beginDeferredTransaction];
    
        NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Task_Check (uid, placeCode, placeDesc, location, management, checkType, taskingTime, completionTime, createTime, isTempCheck, inventoryTime, userId) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",
                         [obj valueForKey:@"uid"], [obj valueForKey:@"placeCode"],[obj valueForKey:@"placeDesc"],
                         [obj valueForKey:@"location"],[obj valueForKey:@"management"],[obj valueForKey:@"checkType"],
                         [obj valueForKey:@"taskingTime"],[obj valueForKey:@"completionTime"],[[NSDate date] stringFromDateFormat:kDateFormatSecond],@"1",[[NSDate date] stringFromDateFormat:kDateFormatSecond],[DataMgr sharedInstance].userId];
        result = result && [db executeUpdate:sql];
        
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

// ================= 历史检查 =================

+ (BOOL)insertHistoryChecks:(NSArray *)historyChecks
{
    return [[BaseDao getInstance] insertDatas:historyChecks key:@"uid" toTable:kTableName_T_History_Check];
}

//历史检查列表
+ (NSArray *)fectchHistoryChecksByPlaceCode:(NSString *)placeCode
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_History_Check WHERE placeCode == '%@'", placeCode];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

// ================= 数据上传 =================

+ (NSArray *)fetchUnUploaded7sDatas
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Task_Check WHERE (uploadFlag == '0' OR uploadFlag ISNULL) AND inventoryTime NOTNULL AND userId == '%@';", [DataMgr sharedInstance].userId];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

//更新未上传7S数据为已上传
+ (BOOL)updateUnUploadedDatasTagUploaded:(NSArray *)taskChecks
{
    BOOL result = YES;
    
    FMDatabase *db = [DBMgr sharedInstance].db;
	@try {
		[db beginDeferredTransaction];
        
        for (NSObject *taskCheck in taskChecks) {
            NSString *sql = [NSString stringWithFormat:@"UPDATE T_Task_Check SET uploadFlag = '1' WHERE uid == '%@'", [taskCheck valueForKey:@"uid"]];
            result = result && [db executeUpdate:sql];
            if (!result) {
                break;
            }
        }
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

// ================= 物流设备 =================
//物流巡检设备类型
+ (BOOL)insertLogisticsEquipType:(NSArray *)equipTypes
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        for (NSObject *obj in equipTypes) {
            
            NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_EquipType WHERE equipmentTypeId == '%@';", [obj valueForKey:@"equipmentTypeId"]];
            NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
            if (arrResults.count > 0) {
                NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_EquipType SET equipmentTypeName = '%@',createTime = '%@' WHERE equipmentTypeId == '%@';", [obj valueForKey:@"equipmentTypeName"],[obj valueForKey:@"createTime"], [obj valueForKey:@"equipmentTypeId"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }else {
                NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Logistics_EquipType (equipmentTypeId, equipmentTypeName, createTime) VALUES ('%@','%@','%@')", [obj valueForKey:@"equipmentTypeId"],[obj valueForKey:@"equipmentTypeName"],[obj valueForKey:@"createTime"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }
    
        }
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

+ (NSArray *)fectchAllLogisticsEquipTypes
{
    return [[BaseDao getInstance] selectAllDatasFromTable:kTableName_T_Logistics_EquipType];
}

//物流巡检设备
+ (BOOL)insertLogisticsEquipments:(NSArray *)equipments
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        for (NSObject *obj in equipments) {
            
            NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Equipment WHERE equipmentId == '%@';", [obj valueForKey:@"equipmentId"]];
            NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
            if (arrResults.count > 0) {
                NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Equipment SET equipmentCode = '%@',equipmentName = '%@',equipmentModel = '%@',equipmentTypeId = '%@',createTime = '%@' WHERE equipmentId == '%@';", [obj valueForKey:@"equipmentCode"],[obj valueForKey:@"equipmentName"],[obj valueForKey:@"equipmentModel"],[obj valueForKey:@"equipmentTypeId"],[obj valueForKey:@"createTime"], [obj valueForKey:@"equipmentId"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }else {
                NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Logistics_Equipment (equipmentId, equipmentCode, equipmentName, equipmentModel, equipmentTypeId, createTime) VALUES ('%@','%@','%@','%@','%@','%@')",
                                 [obj valueForKey:@"equipmentId"], [obj valueForKey:@"equipmentCode"],[obj valueForKey:@"equipmentName"],
                                 [obj valueForKey:@"equipmentModel"],[obj valueForKey:@"equipmentTypeId"],[obj valueForKey:@"createTime"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }
       
        }
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
	return result;
}

+ (NSArray *)fectchLogisticsEquipmentsByTypeId:(NSString *)typeId
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Equipment WHERE equipmentTypeId == '%@';", typeId];
    
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}


/*
// ================= 物流巡检 =================
//Common  热膜，分拣设备，分拣线
+ (BOOL)insertLogisticsCommonChecks:(NSArray *)commonChecks
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        for (NSObject *obj in commonChecks) {
            
            NSString *strStandardIds = nil;
            NSObject *standardIds = [obj valueForKey:@"standardIds"];
            if ([standardIds isKindOfClass:[NSArray class]]
                && standardIds != [NSNull null]
                && ((NSArray *)standardIds).count > 0) {
                strStandardIds = [(NSArray *)standardIds componentsJoinedByString:@","];
            }
            
            NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Logistics_Common (equipmentId, equipmentCode, equipmentName, equipmentModel, equipmentTypeId, checkType, checkDate, standardIds) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@')",
                             [obj valueForKey:@"equipmentId"], [obj valueForKey:@"equipmentCode"],[obj valueForKey:@"equipmentName"],
                             [obj valueForKey:@"equipmentModel"],[obj valueForKey:@"equipmentTypeId"],
                             [obj valueForKey:@"checkType"],[obj valueForKey:@"checkDate"],strStandardIds];
            result = result && [db executeUpdate:sql];
            if (!result) {
                break;
            }
        }
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
	return result;
}

+ (NSArray *)fectchAllLogisticsCommonChecksByTypeId:(NSString *)typeId
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Common WHERE inventoryStatus ISNULL AND equipmentTypeId == '%@';", typeId];
    
    return [[BaseDao sharedInstance] excuteSelectBySQL];
}

+ (BOOL)updateLogisticsCommonCheckByEquipId:(NSString *)equipId withStandardIds:(NSArray *)standardIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *status = standardIds.count>0?@"0":@"1";
        NSString *strStandardIds = [self convertArrayToString:standardIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Common SET selectedStdIds = '%@', inventoryTime = '%@', inventoryStatus = '%@' WHERE equipmentId == '%@'", strStandardIds, [[NSDate date] stringFromDateFormat:kDateFormatSecond], status, equipId];
        result = result && [db executeUpdate:sql];
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

+ (BOOL)updateLogisticsCommonCheckByEquipId:(NSString *)equipId withImageIds:(NSArray *)imageIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *strimageIds = [self convertArrayToString:imageIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Common SET imageIds = '%@' WHERE equipmentId == '%@'", strimageIds, equipId];
        result = result && [db executeUpdate:sql];
        
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

// Lift -- 升降机
+ (BOOL)insertLogisticsLiftChecks:(NSArray *)commonChecks
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        for (NSObject *obj in commonChecks) {
            
            NSString *strStandardIds = nil;
            NSObject *standardIds = [obj valueForKey:@"standardIds"];
            if ([standardIds isKindOfClass:[NSArray class]]
                && standardIds != [NSNull null]
                && ((NSArray *)standardIds).count > 0) {
                strStandardIds = [(NSArray *)standardIds componentsJoinedByString:@","];
            }
            
            NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Logistics_Lift (equipmentId, equipmentCode, equipmentName, equipmentModel, equipmentTypeId, checkDate, appearance, power, operate, hydraulicPressure, clean, function, standardIds) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",
                             [obj valueForKey:@"equipmentId"], [obj valueForKey:@"equipmentCode"],[obj valueForKey:@"equipmentName"],
                             [obj valueForKey:@"equipmentModel"],[obj valueForKey:@"equipmentTypeId"],[obj valueForKey:@"checkDate"],[obj valueForKey:@"appearance"],
                             [obj valueForKey:@"power"],[obj valueForKey:@"operate"],[obj valueForKey:@"hydraulicPressure"],[obj valueForKey:@"clean"],[obj valueForKey:@"function"],strStandardIds];
            result = result && [db executeUpdate:sql];
            if (!result) {
                break;
            }
        }
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
	return result;
}

+ (NSArray *)fectchAllLogisticsLiftChecksByTypeId:(NSString *)typeId
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Lift WHERE inventoryStatus ISNULL AND equipmentTypeId == '%@';", typeId];
    
    return [[BaseDao sharedInstance] excuteSelectBySQL:sql];
}

+ (BOOL)updateLogisticsLiftCheckByEquipId:(NSString *)equipId withStandardIds:(NSArray *)standardIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *status = standardIds.count>0?@"0":@"1";
        NSString *strStandardIds = [self convertArrayToString:standardIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Lift SET selectedStdIds = '%@', inventoryTime = '%@', inventoryStatus = '%@' WHERE equipmentId == '%@'", strStandardIds, [[NSDate date] stringFromDateFormat:kDateFormatSecond], status, equipId];
        result = result && [db executeUpdate:sql];
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

+ (BOOL)updateLogisticsLiftCheckByEquipId:(NSString *)equipId withImageIds:(NSArray *)imageIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *strimageIds = [self convertArrayToString:imageIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Lift SET imageIds = '%@' WHERE equipmentId == '%@'", strimageIds, equipId];
        result = result && [db executeUpdate:sql];
        
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

// Compressor -- 空压机
+ (BOOL)insertLogisticsCompressorChecks:(NSArray *)commonChecks
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        for (NSObject *obj in commonChecks) {
            
            NSString *strStandardIds = nil;
            NSObject *standardIds = [obj valueForKey:@"standardIds"];
            if ([standardIds isKindOfClass:[NSArray class]]
                && standardIds != [NSNull null]
                && ((NSArray *)standardIds).count > 0) {
                strStandardIds = [(NSArray *)standardIds componentsJoinedByString:@","];
            }
            
            NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Logistics_Compressor (equipmentId, equipmentCode, equipmentName, equipmentModel, equipmentTypeId, checkDate, pressureVally, pressurePeak, oilLevel, oilTemperature, startDate, endDate, drain, exceptionRecord, standardIds) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",
                             [obj valueForKey:@"equipmentId"], [obj valueForKey:@"equipmentCode"],[obj valueForKey:@"equipmentName"],
                             [obj valueForKey:@"equipmentModel"],[obj valueForKey:@"equipmentTypeId"],[obj valueForKey:@"checkDate"],[obj valueForKey:@"pressureVally"],
                             [obj valueForKey:@"pressurePeak"],[obj valueForKey:@"oilLevel"],[obj valueForKey:@"oilTemperature"],[obj valueForKey:@"startDate"],[obj valueForKey:@"endDate"],[obj valueForKey:@"drain"],[obj valueForKey:@"exceptionRecord"],strStandardIds];
            result = result && [db executeUpdate:sql];
            if (!result) {
                break;
            }
        }
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
	return result;
}

+ (NSArray *)fectchAllLogisticsCompressorChecksByTypeId:(NSString *)typeId
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Logistics_Compressor WHERE inventoryStatus ISNULL AND equipmentTypeId == '%@';", typeId];
    
    return [[BaseDao sharedInstance] excuteSelectBySQL:sql];
}

+ (BOOL)updateLogisticsCompressorCheckByEquipId:(NSString *)equipId withStandardIds:(NSArray *)standardIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *status = standardIds.count>0?@"0":@"1";
        NSString *strStandardIds = [self convertArrayToString:standardIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Compressor SET selectedStdIds = '%@', inventoryTime = '%@', inventoryStatus = '%@' WHERE equipmentId == '%@'", strStandardIds, [[NSDate date] stringFromDateFormat:kDateFormatSecond], status, equipId];
        result = result && [db executeUpdate:sql];
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

+ (BOOL)updateLogisticsCompressorCheckByEquipId:(NSString *)equipId withImageIds:(NSArray *)imageIds
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        NSString *strimageIds = [self convertArrayToString:imageIds];
        NSString *sql = [NSString stringWithFormat:@"UPDATE T_Logistics_Compressor SET imageIds = '%@' WHERE equipmentId == '%@'", strimageIds, equipId];
        result = result && [db executeUpdate:sql];
        
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
    
	return result;
}

*/

// ================= 机房巡检 =================

+ (BOOL)insertRoomStandards:(NSArray *)roomStandards
{
    FMDatabase *db = [DBMgr sharedInstance].db;
	BOOL result = YES;
	@try {
		[db beginDeferredTransaction];
        
        for (NSObject *obj in roomStandards) {
            
            NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM T_Room_Standard WHERE checkItemId == '%@';", [obj valueForKey:@"checkItemId"]];
            NSArray *arrResults = [[BaseDao getInstance] excuteSelectBySQL:selectSql];
            if (arrResults.count > 0) {
                NSString *sql = [NSString stringWithFormat:@"UPDATE T_Room_Standard SET checkItemName = '%@',checkItemResultId = '%@',checkItemResultName = '%@',equipmentCode = '%@',equipmentId = '%@',equipmentName = '%@',createTime = '%@' WHERE checkItemId == '%@';", [obj valueForKey:@"checkItemName"],[obj valueForKey:@"checkItemResultId"],[obj valueForKey:@"checkItemResultName"],[obj valueForKey:@"equipmentCode"], [obj valueForKey:@"equipmentId"], [obj valueForKey:@"equipmentName"], [obj valueForKey:@"createTime"], [obj valueForKey:@"checkItemId"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }else {
                NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_Room_Standard (checkItemId, checkItemName, checkItemResultId, checkItemResultName, equipmentCode, equipmentId, equipmentName, createTime) VALUES ('%@','%@','%@','%@','%@','%@','%@','%@')",
                                 [obj valueForKey:@"checkItemId"], [obj valueForKey:@"checkItemName"],[obj valueForKey:@"checkItemResultId"],
                                 [obj valueForKey:@"checkItemResultName"],[obj valueForKey:@"equipmentCode"],
                                 [obj valueForKey:@"equipmentId"],[obj valueForKey:@"equipmentName"], [obj valueForKey:@"createTime"]];
                result = result && [db executeUpdate:sql];
                if (!result) {
                    break;
                }
            }
     
        }
	}
	@catch (NSException *exception) {
		NSLog(@"%@", [exception reason]);
	}
	@finally {
		result ? [db commit] : [db rollback];
	}
	return result;
}

+ (NSArray *)fectchAllRoomStandards
{
    return [[BaseDao getInstance] EX:@"SELECT * FROM T_Room_Standard;"];
}

+ (NSArray *)fectchRoomStandardsByIds:(NSArray *)arrStandardIds
{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_Room_Standard WHERE uid IN %@", arrStandardIds];
    return [[BaseDao getInstance] excuteSelectBySQL:sql];
}

#endif

@end
