//
//  MMLocalReportBManager.m
//  SkinMagnifier
//
//  Created by nana on 2020/12/7.
//

#import "SMLocalReportBManager.h"
#import <FMDB/FMDB.h>

@interface SMLocalReportBManager()

@property(nonatomic, strong)FMDatabaseQueue *dbQueue;
@end

@implementation SMLocalReportBManager



+ (instancetype)sharedManager {
    static SMLocalReportBManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[SMLocalReportBManager alloc] init];
    });
    return sharedManager;
}
- (instancetype)init {
    if (self = [super init]) {
        [self setup];
        
    }
    return self;
}
- (void)setup {
    
    NSString *fileName = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject] stringByAppendingPathComponent:@"MMLocalReportBManager.sqlite"];
     NSLog(@"dbPath = %@",fileName);
    //创建数据库
    self.dbQueue =  [FMDatabaseQueue databaseQueueWithPath:fileName];
//    self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:@"/Users/nana/Desktop/wb.db"];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_report (\
         id integer PRIMARY KEY AUTOINCREMENT ,\
         mid TEXT,\
         cid TEXT,\
         cgid TEXT,\
         imageArray TEXT,\
         symptomArray TEXT,\
         productArray TEXT,\
         moisture TEXT,\
         iposition TEXT,\
         createTime TEXT)"];
        
        if (![db columnExists:@"uploadLock" inTableWithName:@"t_report"]){
            NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ TEXT DEFAULT '0'",@"t_report",@"uploadLock"];
            [db executeUpdate:alertStr];
        }
        if (![db columnExists:@"AISymptomArray" inTableWithName:@"t_report"]){
            NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ TEXT DEFAULT '[]'",@"t_report",@"AISymptomArray"];
            [db executeUpdate:alertStr];
        }
        
    }];

    
    
}


-(BOOL)addWithModel:(SMLocalReportModel *)model {

    if (!model) {
        return false;
    }

    NSString *imageArray = @"";
    if (model.imageArray.count) {
        imageArray =[[SMLocalReportImageModel mj_keyValuesArrayWithObjectArray:model.imageArray] mj_JSONString];
    }else {
        imageArray = @"[]";
    }

    NSString *symptomArray = @"";
    if (model.symptomArray.count) {
        symptomArray =[[SMLocalReportSymptomModel mj_keyValuesArrayWithObjectArray:model.symptomArray] mj_JSONString];
    }else {
        symptomArray = @"[]";
    }
    
    NSString *aiSymptomArray = @"";
    if (model.AISymptomArray.count) {
        aiSymptomArray =[[SMLocalReportAIModel mj_keyValuesArrayWithObjectArray:model.AISymptomArray] mj_JSONString];
    }else {
        aiSymptomArray = @"[]";
    }
    
    NSString *productArray = @"";
    if (model.productArray.count) {
        productArray = [[SMLocalReportProductModel mj_keyValuesArrayWithObjectArray:model.productArray] mj_JSONString];
    }else {
        productArray = @"[]";
    }

    NSString *moisture = [model.moisture mj_JSONString];

    __block BOOL insertState = NO;
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
           insertState = [db executeUpdateWithFormat:@"insert into t_report\
                          (mid,cid,cgid,imageArray,symptomArray,AISymptomArray,productArray,moisture,iposition,createTime)\
                          values(%@,%@,%@,%@,%@,%@,%@,%@,%@,%@)",
                          model.mid,model.cid,model.cgid,imageArray,symptomArray,aiSymptomArray,productArray,moisture,model.iposition,model.createTime];

    }];

    return insertState;
}
-(BOOL)updateWithModel:(SMLocalReportModel *)model cgid:(NSString *)cgid {
    
    if (!model) {
        return false;
    }
    NSMutableDictionary *dict = [model mj_keyValues];
    NSMutableArray *StringArray = [[NSMutableArray alloc] init];
    for (NSString *key in [dict allKeys]) {
        if ([[key uppercaseString] containsString:@"ID"]) {
            continue; 
        }
    
        if (dict[key]) {
            NSString *value = dict[key];
            if ([key isEqualToString:@"symptomArray"]) {
                value =[[SMLocalReportSymptomModel mj_keyValuesArrayWithObjectArray:dict[key]] mj_JSONString];
            }else if ([key isEqualToString:@"AISymptomArray"]) {
                value =[[SMLocalReportAIModel mj_keyValuesArrayWithObjectArray:dict[key]] mj_JSONString];
            }else if ([key isEqualToString:@"imageArray"]) {
                value =[[SMLocalReportImageModel mj_keyValuesArrayWithObjectArray:dict[key]] mj_JSONString];
            }else if ([key isEqualToString:@"productArray"]) {
                value =[[SMLocalReportProductModel mj_keyValuesArrayWithObjectArray:dict[key]] mj_JSONString];
            }else if ([key isEqualToString:@"moisture"]) {
                NSError *error;
                NSDictionary *mDict = dict[key];
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mDict options:NSJSONWritingPrettyPrinted error:&error];
                value = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            }
            NSString *sqlT = [NSString stringWithFormat:@"%@ = '%@'",key,value];
            [ StringArray addObject:sqlT];
        }

    }
    NSString  *string = [StringArray componentsJoinedByString:@","];

    NSString *sql = [NSString stringWithFormat:@"UPDATE t_report SET  %@ WHERE cgid = %@",string,cgid];
    __block BOOL insertState = NO;
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
           insertState = [db executeUpdate:sql];

    }];
    return insertState;
}
-(BOOL)deleteWitCgid:(NSString *)cgid {

    NSString *sql = [NSString stringWithFormat:@"DELETE FROM t_report  WHERE cgid = %@",cgid];
    __block BOOL insertState = NO;
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
           insertState = [db executeUpdate:sql];
    }];
    return insertState;
}

/// 根据Cid 查询数据
-(NSMutableArray *)selectWithCid:(NSString *)cid  from:(NSInteger )from{
    NSMutableArray *rArray = [[NSMutableArray alloc] init];
    if (!cid && cid.length == 0 ) {
        return rArray;
    }
    
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        FMResultSet *set = [db executeQueryWithFormat:@"SELECT * FROM t_report WHERE cid = %@ ORDER BY createTime DESC LIMIT %d,%d",cid,from,KPageSize];
        [rArray addObjectsFromArray:[self arrayFromSet:set]];
    }];
    
    return rArray;
}
/// 根据Cgid 查询数据
-(NSMutableArray *)selectWithCgid:(NSString *)cgid{
    NSMutableArray *rArray = [[NSMutableArray alloc] init];
    if (!cgid && cgid.length == 0 ) {
        return rArray;
    }
    
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        FMResultSet *set = [db executeQueryWithFormat:@"SELECT * FROM t_report WHERE cgid = %@ ORDER BY createTime DESC",cgid];
        [rArray addObjectsFromArray:[self arrayFromSet:set]];
    }];
    
    return rArray;
}

/// 根据Cid 查询数据
-(NSMutableArray *)selectFristWithMid:(NSString *)Mid{
    NSMutableArray *rArray = [[NSMutableArray alloc] init];
    if (!Mid && Mid.length == 0 ) {
        return rArray;
    }
    
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        FMResultSet *set = [db executeQueryWithFormat:@"SELECT * FROM t_report WHERE mid = %@ ORDER BY createTime ASC LIMIT 0,1",Mid];
        [rArray addObjectsFromArray:[self arrayFromSet:set]];
    }];
    
    return rArray;;
}

//-(BOOL)updateWithCgid:(NSString *)cgid key:(NSString *)key value:(NSString *)value {
//    __block BOOL insertState = NO;
//    NSString *sql = [NSString stringWithFormat:@"UPDATE t_report SET %@ = '%@'  WHERE cgid = %@",key,value,cgid];
//    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
//           insertState = [db executeUpdate:sql];
//    }];
//    return insertState;
//}


-(BOOL)updateWithSetKey:(NSString *)setKey  setValue:(NSString *)setValue whereKey:(NSString *)whereKey whereValue:(NSString *)whereValue {
    __block BOOL insertState = NO;
    NSString *sql = [NSString stringWithFormat:@"UPDATE t_report SET %@ = '%@' WHERE %@ = '%@'",setKey,setValue,whereKey,whereValue];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
           insertState = [db executeUpdate:sql];
    }];
    return insertState;
}

- (NSMutableArray *)arrayFromSet:(FMResultSet *)set {
      
    NSMutableArray *rArray = [[NSMutableArray alloc] init];
    while (set.next) {
        SMLocalReportModel *model = [[SMLocalReportModel alloc] init];
        model.mid =  [set stringForColumn:@"mid"];
        model.cid = [set stringForColumn:@"cid"];
        model.cgid = [set stringForColumn:@"cgid"];
        model.iposition =  [set stringForColumn:@"iposition"];
        model.uploadLock =  [set stringForColumn:@"uploadLock"];
 
        model.createTime = [set stringForColumn:@"createTime"];
        NSString *moisture = [set stringForColumn:@"moisture"];
        if (moisture) {
            NSDictionary *mDict = [NSJSONSerialization JSONObjectWithData:[moisture dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];
            model.moisture = [SMLocalReportOilModel mj_objectWithKeyValues:mDict];
        }
        
        NSString *imageArray = [set stringForColumn:@"imageArray"];
        if (imageArray.length) {
            NSArray *xx = [NSJSONSerialization JSONObjectWithData:[imageArray dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];;
            model.imageArray = [SMLocalReportImageModel mj_objectArrayWithKeyValuesArray:xx];
        }
        
        NSString *AISymptomArray = [set stringForColumn:@"AISymptomArray"];
        if (AISymptomArray.length) {
            NSArray *xx = [NSJSONSerialization JSONObjectWithData:[AISymptomArray dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];;
            model.AISymptomArray = [SMLocalReportAIModel mj_objectArrayWithKeyValuesArray:xx];
        }
        
        

         
        NSString *symptomArray = [set stringForColumn:@"symptomArray"];
        
        if (symptomArray.length) {
            NSArray *xx = [NSJSONSerialization JSONObjectWithData:[symptomArray dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];;
            model.symptomArray = [SMLocalReportSymptomModel mj_objectArrayWithKeyValuesArray:xx];
        }
        
        NSString *productArray = [set stringForColumn:@"productArray"];
        if (productArray.length) {
            NSArray *xx = [NSJSONSerialization JSONObjectWithData:[productArray dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingFragmentsAllowed error:nil];;
            model.productArray = [SMLocalReportProductModel mj_objectArrayWithKeyValuesArray:xx];
        }
        [rArray addObject:model];
    }
    
    return  rArray;
}


@end
/*
 @property(nonatomic, assign)NSInteger ID;
 /// 用户ID
 @property(nonatomic, strong)NSString *mid;
 /// 顾客ID
 @property(nonatomic, strong)NSString *cid;
 /// 案例组ID
 @property(nonatomic, strong)NSString *cgid;
 /// 部位
 @property(nonatomic, strong)NSString *iposition;
 /// 水份
 @property(nonatomic, strong)NSString *moisture;
 /// 图片数组
 @property(nonatomic, strong)NSMutableArray *imageArray;
 /// 症状数组
 @property(nonatomic, strong)NSMutableArray *symptomArray;
 /// 产品数组
 @property(nonatomic, strong)NSMutableArray *productArray;
 /// 水份
 @property(nonatomic, strong)NSString *createTime;
 **/
