IMAMsg.m 51.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
//
//  IMAMsg.m
//  CNLiveNewIMAManagerKit
//
//  Created by AlexiChen on 16/1/29.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "IMAMsg.h"

#import "CustomElemCmd.h"

@interface IMAMsg ()

@property (nonatomic, strong) NSMutableDictionary *affixParams;
@property (nonatomic, assign) NSInteger  status;

@end

@implementation IMAMsg

- (instancetype)initWith:(TIMMessage *)msg type:(IMAMSGType)type
{
    if (self = [super init])
    {
        _msg = msg;
        _type = type;
        _status = EIMAMsg_Init;
        
        TIMElem *elem = [msg getElem:0];
        
        /**判断是否是自定义消息*/
        if ([elem isKindOfClass:[TIMCustomElem class]]) {
            
            //解析自定义消息,并把解析后的数据赋值给 _customMsgData
            TIMCustomElem *cusElem = (TIMCustomElem *)elem;
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:cusElem.data
                                                                options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
                                                                  error:&err];
            
            _customMsgData = dic;
        }
    }
    return self;
}

+ (instancetype)msgWithText:(NSString *)text
{
    TIMTextElem *elem = [[TIMTextElem alloc] init];
    elem.text = text;
    TIMMessage *msg = [[TIMMessage alloc] init];
    [msg addElem:elem];
    
    return [[IMAMsg alloc] initWith:msg type:EIMAMSG_Text];
}

+ (instancetype)msgWithImage:(UIImage *)image isOrignal:(BOOL)origal conversationId:(NSString *)conversationId
{
    TIMMessage *msg = [[TIMMessage alloc] init];
    CGFloat scale = 1;
    scale = MIN(kChatPicThumbMaxHeight/image.size.height, kChatPicThumbMaxWidth/image.size.width);
    
    CGFloat picHeight = image.size.height;
    CGFloat picWidth = image.size.width;
    NSInteger picThumbHeight = (NSInteger) (picHeight * scale + 1);
    NSInteger picThumbWidth = (NSInteger) (picWidth * scale + 1);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *fileName = [NSString stringWithFormat:@"%f_%d_image_file", [[NSDate date] timeIntervalSince1970],arc4random() % 100000];
    NSString *filePath = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:fileName];
    NSLog(@"filePath == %@",filePath);
    BOOL isDirectory = NO;
    NSError *err = nil;
    
    // 当前sdk仅支持文件路径上传图片,将图片存在本地
    if ([fileManager fileExistsAtPath:filePath isDirectory:&isDirectory])
    {
        if (![fileManager removeItemAtPath:[CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:fileName] error:&err])
        {
            DebugLog(@"Upload Image Failed: same upload filename: %@", err);
            return nil;
        }
    }
    if ([image.isGif integerValue] == 1) {
        if (![fileManager createFileAtPath:filePath contents:image.imageData attributes:nil])
        {
            DebugLog(@"Upload Image Failed: fail to create uploadfile: %@", err);
            return nil;
        }
    }
    else
        if (![fileManager createFileAtPath:filePath contents:UIImageJPEGRepresentation(image, 1) attributes:nil])
        {
            DebugLog(@"Upload Image Failed: fail to create uploadfile: %@", err);
            return nil;
        }
    
    
    NSString *thumbName = [NSString stringWithFormat:@"%@_thumb",fileName];

    NSString *thumbPath = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:thumbName];
    
    UIImage *thumbImage = [image thumbnailWithSize:CGSizeMake(picThumbWidth, picThumbHeight)];
    
    if ([image.isGif integerValue] == 1) {
        if (![fileManager createFileAtPath:thumbPath contents:image.imageData attributes:nil])
        {
            DebugLog(@"Upload Image Failed: fail to create uploadfile: %@", err);
            return nil;
        }
    }
    else
        if (![fileManager createFileAtPath:thumbPath contents:UIImageJPEGRepresentation(thumbImage, 1) attributes:nil])
        {
            DebugLog(@"Upload Image Failed: fail to create uploadfile: %@", err);
            return nil;
        }
    
    //判断图片是否成功写入本地
    if ([fileManager fileExistsAtPath:filePath isDirectory:&isDirectory])
    {
        NSData *fileData = [[NSData alloc] initWithContentsOfFile:filePath];
        NSLog(@"输出 fileData == %ld",fileData.length);
        if (fileData.length == 0) {
            NSLog(@"写入失败了");
            return nil;
        }
    }
    else
    {
        NSLog(@"写入失败了");
        return nil;
    }
    
    //判断缩略图是否成功写入本地
    if ([fileManager fileExistsAtPath:thumbPath isDirectory:&isDirectory])
    {
        NSData *thumbData = [[NSData alloc] initWithContentsOfFile:thumbPath];
        NSLog(@"输出 thumbData == %ld",thumbData.length);
        if (thumbData.length == 0) {
            NSLog(@"写入失败了");
            return nil;
        }
    }
    else
    {
        NSLog(@"写入失败了");
        return nil;
    }
    
    
    TIMImageElem *elem = [[TIMImageElem alloc] init];
    elem.path = filePath;

    if (origal) {
        elem.level = TIM_IMAGE_COMPRESS_ORIGIN;
    } else {
        elem.level = TIM_IMAGE_COMPRESS_HIGH;
    }
    
   
    if ([msg addElem:elem] != 0) {
        //添加失败
        return nil;
    }
    IMAMsg *imamsg = [[IMAMsg alloc] initWith:msg type:EIMAMSG_Image];
    
    [imamsg addInteger:picThumbHeight forKey:kIMAMSG_Image_ThumbHeight];
    [imamsg addInteger:picThumbWidth forKey:kIMAMSG_Image_ThumbWidth];
    [imamsg addString:filePath forKey:kIMAMSG_Image_OrignalPath];
    [imamsg addString:thumbPath forKey:kIMAMSG_Image_ThumbPath];
    
    return imamsg;
}
+ (NSString *)contentTypeForImageData:(NSData *)data{
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}
+ (instancetype)msgWithFailMsg:(IMAMsg *)msg conversationId:(NSString *)conversationId{
    
    TIMImageElem *elem = (TIMImageElem *)[msg.msg getElem:0];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    //之前旧逻辑是以msgId命名文件名的,新的逻辑以uniqueId 命名文件名,以防以后版本msgId又发生改变
    //先取已msgId命名的文件是否存在
    NSString *imageName = [NSString stringWithFormat:@"%@_image_file", msg.msg.msgId];
    NSString *filePath = [CNLiveBusinessTools chatImagePathByConversationId:conversationId imageName:imageName isRead:YES isThumb:NO imageElem_path_lastPathComponent:elem.path.lastPathComponent];
    if ([NSString isEmpty:filePath]) {
        //以msgId命名的文件不存在, 再取以 uniqueId 命名的文件
        imageName = [NSString stringWithFormat:@"%llu_image_file", msg.msg.uniqueId];
        filePath = [CNLiveBusinessTools chatImagePathByConversationId:conversationId imageName:imageName isRead:YES isThumb:NO imageElem_path_lastPathComponent:elem.path.lastPathComponent];
    }
    BOOL isDirectory = NO;
    
    if ([fileManager fileExistsAtPath:filePath isDirectory:&isDirectory]) {
       
        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
        CGFloat scale = 1;
        scale = MIN(kChatPicThumbMaxHeight/image.size.height, kChatPicThumbMaxWidth/image.size.width);
        
        CGFloat picHeight = image.size.height;
        CGFloat picWidth = image.size.width;
        NSInteger picThumbHeight = (NSInteger) (picHeight * scale + 1);
        NSInteger picThumbWidth = (NSInteger) (picWidth * scale + 1);
                
        TIMMessage *nemTMsg = [[TIMMessage alloc] init];

        NSString *snapshotName = [NSString stringWithFormat:@"%3.f_%d_video_file", [[NSDate date] timeIntervalSince1970],arc4random() % 100000];
        NSString *thumbPath = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:snapshotName];
        
        UIImage *thumbImage = [image thumbnailWithSize:CGSizeMake(picThumbWidth, picThumbHeight)];
        
        if ([CNLiveBusinessTools isGifWithImageData:[NSData dataWithContentsOfFile:filePath]]) {
            if (![fileManager createFileAtPath:thumbPath contents:[NSData dataWithContentsOfFile:filePath] attributes:nil])
            {
                DebugLog(@"Upload Image Failed: fail to create uploadfile");
                return nil;
            }
        }
        else
            if (![fileManager createFileAtPath:thumbPath contents:UIImageJPEGRepresentation(thumbImage, 1) attributes:nil])
            {
                DebugLog(@"Upload Image Failed: fail to create uploadfile");
                return nil;
            }
        
        TIMImageElem *newElem = [[TIMImageElem alloc] init];
        elem.path = filePath;
        newElem.level = elem.level;
        
        [nemTMsg addElem:elem];
        IMAMsg *newMsg = [[IMAMsg alloc] initWith:nemTMsg type:EIMAMSG_Image];
        
        [newMsg addInteger:picThumbHeight forKey:kIMAMSG_Image_ThumbHeight];
        [newMsg addInteger:picThumbWidth forKey:kIMAMSG_Image_ThumbWidth];
        [newMsg addString:filePath forKey:kIMAMSG_Image_OrignalPath];
        [newMsg addString:thumbPath forKey:kIMAMSG_Image_ThumbPath];
        
        return newMsg;
    }
    
    return nil;
    
}

+ (instancetype)msgWithDate:(NSDate *)timetip
{
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    [elem setFollowTime:timetip];
    
    TIMMessage *msg = [[TIMMessage alloc] init];
    [msg addElem:elem];
    IMAMsg *imamsg = [[IMAMsg alloc] initWith:msg type:EIMAMSG_TimeTip];
    return imamsg;
}

+ (instancetype)msgWithFilePath:(NSURL *)filePath
{
    if (!filePath)
    {
        return nil;
    }
    
    TIMFileElem *elem = [[TIMFileElem alloc] init];
    elem.path = filePath.path;
    NSData *dataFile = [NSData dataWithContentsOfURL:filePath];
    elem.fileSize = (int)dataFile.length;
    
    NSArray *array = [[filePath absoluteString] componentsSeparatedByString:@"/"];
    NSString *fileName = [array lastObject];
    fileName = [fileName stringByRemovingPercentEncoding];

    elem.filename = fileName;
    
    TIMMessage *msg = [[TIMMessage alloc] init];
    [msg addElem:elem];
    
    return [[IMAMsg alloc] initWith:msg type:EIMAMSG_File];
}

+ (instancetype)msgWithSound:(NSString *)filePath duration:(NSInteger)dur message:(TIMMessage *)msg
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        return nil;
    }
    TIMSoundElem *elem = [[TIMSoundElem alloc] init];
    elem.path = filePath;
    elem.second = dur;
    
    [msg addElem:elem];
    
    return [[IMAMsg alloc] initWith:msg type:EIMAMSG_Sound];
}

+ (instancetype)msgWithEmptySound
{
    TIMSoundElem *elem = [[TIMSoundElem alloc] init];
    
    TIMMessage *msg = [[TIMMessage alloc] init];
    [msg addElem:elem];
    
    return [[IMAMsg alloc] initWith:msg type:EIMAMSG_Sound];
}

+ (instancetype)msgWithCustom:(NSInteger)command
{
    return [IMAMsg msgWithCustom:command param:nil];
}

+ (instancetype)msgWithCustom:(NSInteger)command param:(NSString *)param
{
    CustomElemCmd *cmd = [[CustomElemCmd alloc] initWith:command param:param];
    
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    elem.data = [cmd packToSendData];
    elem.desc = param;
    TIMMessage *customMsg = [[TIMMessage alloc] init];
    [customMsg addElem:elem];
    
    return [[IMAMsg alloc] initWith:customMsg type:command];
}

//zl_自定义订单消息
+ (instancetype)msgWithCustomDic:(NSDictionary *)dic desc:(NSString *)cusdDesc type:(IMAMSGType)type {
    
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    elem.data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    elem.desc = cusdDesc;
    
    TIMMessage *customMsg = [[TIMMessage alloc] init];
    [customMsg addElem:elem];
    
    return [[IMAMsg alloc] initWith:customMsg type:type];
}

#pragma mark - TODO:音视频
+ (instancetype)msgWithAudioOrVedioCustomDic:(NSDictionary *)dic desc:(NSString *)cusdDesc type:(IMAMSGType)type {
    
    
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    elem.data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    elem.desc = cusdDesc;
    TIMMessage *customMsg = [[TIMMessage alloc] init];
    TIMOfflinePushInfo *pushInfo = [[TIMOfflinePushInfo alloc]init];
    pushInfo.desc = cusdDesc;
    pushInfo.ext = [dic jsonStringEncoded];
    pushInfo.pushFlag = TIM_OFFLINE_PUSH_NO_PUSH;
    TIMIOSOfflinePushConfig *pushConfig = [[TIMIOSOfflinePushConfig alloc]init];
    pushConfig.ignoreBadge = YES;//忽略badge计数
    [customMsg setOfflinePushInfo:pushInfo];
    [customMsg addElem:elem];
    
    return [[IMAMsg alloc] initWith:customMsg type:type];
    
}



+ (instancetype)msgWith:(TIMMessage *)msg
{
    //    EIMAMSG_Text,               // 文本
    //    EIMAMSG_Image,              // 图片
    //    EIMAMSG_File,               // 文件
    //    EIMAMSG_Sound,              // 语音
    //    EIMAMSG_Face,               // 表情
    //    EIMAMSG_Location,           // 定位
    //    EIMAMSG_Video,              // 视频消息
    //    EIMAMSG_Custom,             // 自定义
    //    EIMAMSG_GroupTips,          // 群提醒
    //    EIMAMSG_GroupSystem,        // 群系统消息
    //    EIMAMSG_SNSSystem,          // 关系链消息
    //    EIMAMSG_ProfileSystem,      // 资料变更消息
    
    if (msg.elemCount == 0)
    {
        return nil;
    }
    
    IMAMSGType type = EIMAMSG_Unknown;
#if kTestChatAttachment
    if (msg.elemCount > 1)
    {
        // TODO:后期使用富文本显示
        type = EIMAMSG_Multi;
        
        for (int i = 0; i < msg.elemCount ; i ++) {
            TIMElem *fileElem = [msg getElem:i];
            if ([fileElem isKindOfClass:[TIMFileElem class]]) {
#pragma mark 兼容 3.0 升级 4.0 获取历史文件
                type = EIMAMSG_File;
            }
        }
    }
    else
#endif
    {
        TIMElem *elem = [msg getElem:0];
        Class eleCls = [elem class];
        if (eleCls == [TIMTextElem class])
        {
            type = EIMAMSG_Text;
        }
        else if (eleCls == [TIMImageElem class])
        {
            type = EIMAMSG_Image;
        }
        else if (eleCls == [TIMFileElem class])
        {
            type = EIMAMSG_File;
        }
        else if (eleCls == [TIMFaceElem class])
        {
            type = EIMAMSG_Face;
        }
        else if (eleCls == [TIMLocationElem class])
        {
            type = EIMAMSG_Location;
        }
        else if (eleCls == [TIMSoundElem class])
        {
            type = EIMAMSG_Sound;
        }
        else if (eleCls == [TIMVideoElem class])
        {
            type = EIMAMSG_Video;
        }
        else if (eleCls == [TIMCustomElem class])
        {
            TIMCustomElem *cusElem = (TIMCustomElem *)elem;
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:cusElem.data
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            if ([dic[@"type"] integerValue] == 1001) {
                //核对订单
                type = EIMAMSG_OrderConfirm;
            } else if ([dic[@"type"] integerValue] == CustomMsgTypeCnee) {
                //收获地址
                type = EIMAMSG_OrderCnee;
            } else if ([dic[@"type"] integerValue] == CustomMsgTypeOrderStatus) {
                //订单操作
                type = EIMAMSG_OrderStatus;
            } else if ([dic[@"type"] integerValue] == CustomMsgTypeFriendshipVerify) {
                //好友验证
                type = EIMAMSG_FriendshipVerify;
            } else if ([dic[@"type"] integerValue] == CustomMsgTypeAddFriend) {
                //添加好友
                type = EIMAMSG_AddFriend;
            } else if ([dic[@"type"] integerValue] == CustomMsgTypeAddFriendSucc) {
                //添加好友成功
                type = EIMAMSG_AgreeApply;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeSendAddFriendInvitation)
            {
                type = EIMAMSG_SendAddFriendInvitation;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeAite) {
                type = EIMAMSG_AiteStatus;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeDissolveGroup) {
                if ([IMAPlatform sharedInstance].platformType == IMPlatformTypeB) {
                    type = EIMAMSG_OrederPaySuccess;
                }
                else
                    type = EIMAMSG_DissolveGroup;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypePayment) {
                if ([IMAPlatform sharedInstance].platformType == IMPlatformTypeB) {
                    type = EIMAMSG_OrederRepast;
                }
                else
                    type = EIMAMSG_Payment;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeReceipt) {
                
                if ([IMAPlatform sharedInstance].platformType == IMPlatformTypeB) {
                    type = EIMAMSG_OrederRepastReceipt;
                }
                else
                    type = EIMAMSG_Receipt;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeApplyForRefund) {
                type = EIMAMSG_OrederApplyForRefund;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeReminder)
            {
                type = EIMAMSG_OrederReminder;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeGroupPaySuccess) {
                type = EIMAMSG_GroupPaySuccess;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeLiveOneLineCount) {  //聊天室人数
                type = EIMAMSG_LivePeopleNumStatus;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeLiveStatus) { //聊天室直播状态
                type = EIMAMSG_LivePlayerStatus;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeBlackTip)
            {
                type = EIMAMSG_BlackTip;
                
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeShareLink)
            {
                type = EIMAMSG_ShareLink;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeCustomFace)
            {
                type = EIMAMSG_CustomFace;
            }else if([dic[@"type"] integerValue] == CustomMsgTypeSendCurrentLocation)
            {
                type = EIMAMSG_SendCurrentlocation;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeSendCard || [dic[@"type"] integerValue] == CustomMsgTypeSendDarenCard)
            {
                type = EIMAMSG_SendCard;

            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeTransferBalance)
            {
                type = EIMAMSG_TransferBalance;

            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeTransferExpired)
            {
                type = EIMAMSG_TransferExpired;

            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeShareGoods)
            {
                type = EIMAMSG_ShareGoods;
            }
            else if([dic[@"type"] integerValue] == CustomMsgTypeShopOrderDetail)
            {
                type = EIMAMSG_ShopOrderDetail;
            }
            else if([dic[@"type"] integerValue] == CustomMsgTypeShopGoodsInfo)
            {
                type = EIMAMSG_ShopGoodsInfo;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeShareGift)
            {
                type = EIMAMSG_ShareGift;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeSendGiftSuccess)
            {
                type = EIMAMSG_SendGiftSuccess;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeReceiveGiftSuccess)
            {
                type = EIMAMSG_ReceviedGiftSuccess;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeLiveBookingCount)
            {
                type = EIMAMSG_LiveBookingCount;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeLiveDisableSendMsg)
            {
                type = EIMAMSG_LiveDisableSendMsg;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeUGCLivePlayEnd)
            {
                type = EIMAMSG_UGCLivePlayEnd;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeUGCLivePlayShare)
            {
                type = EIMAMSG_UGCLivePlayShare;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeSenderInvitationReceiver)
            {
                type = EIMAMSG_SenderInvitationReceiver;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeSendOrReceiverSwitchAudio)
            {
                type = EIMAMSG_SwitchAudio;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeSendOrReceiverOutRoom)
            {
                type = EIMAMSG_OutRoom;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeReceiveE_BusinessOrder)
            {
                type = EIMAMSG_ReceiveE_BusinessOrder;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeE_BusinessOrderPaySuceess)
            {
                type = EIMAMSG_E_BusinessOrderPaySuceess;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeShareSubGroup)
            {
                type = EIMAMSG_ShareSubGroup;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeTopicTip)
            {
                type = EIMAMSG_TopicTip;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeNewLiveVideo)
            {
                type = EIMAMSG_NewLiveVideo;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeFamilyHealthyStep)
            {
                type = EIMAMSG_FamilyHealthyStep;
            }
            else if ([dic[@"type"] integerValue] == CustomMsgTypeHaveCoupon)
            {
                type = EIMAMSG_HaveCoupon;
            }
            else {
                type = EIMAMSG_Unknown;
            }
            
        }
        else if (eleCls == [TIMGroupTipsElem class])
        {
            
            type = EIMAMSG_GroupTips;
        }
        else if (eleCls == [TIMGroupSystemElem class])
        {
            type = EIMAMSG_GroupSystem;
        }
        else if (eleCls == [TIMProfileSystemElem class])
        {
            type = EIMAMSG_ProfileSystem;
        }
        else if (eleCls == [TIMSNSSystemElem class])
        {
            type = EIMAMSG_SNSSystem;
        }
        else
            type = EIMAMSG_Unknown;
    }
    
    //    if (type == EIMAMSG_Unknown)
    //    {
    //        DebugLog(@"不支持的消息类型");
    //        return ni;
    //    }
    
    IMAMsg *imamsg = [[IMAMsg alloc] initWith:msg type:type];
    [imamsg changeTo:(NSInteger)msg.status needRefresh:NO];
    return imamsg;
    
}

+ (instancetype)msgWithVideoPath:(NSString *)videoPath conversationId:(NSString *)conversationId
{
    if (!videoPath)
    {
        return nil;
    }
   TIMMessage* msg = [[TIMMessage alloc] init];
    //视频截图
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoPath] options:nil];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];
    imageGenerator.appliesPreferredTrackTransform = YES;    // 截图的时候调整到正确的方向
    CMTime time = CMTimeMakeWithSeconds(0.0, 30);   // 1.0为截取视频1.0秒处的图片,30为每秒30帧
    CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:nil error:nil];
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    UIGraphicsEndImageContext();
    NSData *snapshotData = UIImageJPEGRepresentation(image, 0.75);
    
//    int num = (arc4random() % 10000);

    //保存截图到临时目录
    NSString *snapshotName = [NSString stringWithFormat:@"%3.f_%d_video_file", [[NSDate date] timeIntervalSince1970],arc4random() % 100000];
    NSString *snapshotPath = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:snapshotName];
    
    NSError *err;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    if (![fileMgr createFileAtPath:snapshotPath contents:snapshotData attributes:nil])
    {
        DebugLog(@"Upload Image Failed: fail to create uploadfile: %@", err);
        return nil;
    }
    
    //创建 TIMVideoElem
    TIMVideoElem* elem = [[TIMVideoElem alloc] init];
    TIMVideo* video = [[TIMVideo alloc] init];
    TIMSnapshot* snapshot = [[TIMSnapshot alloc] init];
    elem.video = video;
    elem.snapshot = snapshot;
    elem.videoPath = videoPath;
    elem.snapshotPath = snapshotPath;
    
    video.type = @"mp4";
    video.duration = (int)(urlAsset.duration.value * 100.00/(urlAsset.duration.timescale * 100.00) +0.5);
    snapshot.type = @"kTypeSnapshot";//截图类型,用户自定义
    snapshot.width = image.size.width;
    snapshot.height = image.size.height;
    
    
     if ([msg addElem:elem] != 0) {
           //添加失败
         return nil;
       }
    
//    NSLog(@"IMAMsg---------elem:%@", elem);
    
    IMAMsg *videoMsg = [[IMAMsg alloc] initWith:msg type:EIMAMSG_Video];
    
    return videoMsg;
}

+ (void)convertToMP4:(AVURLAsset*)avAsset videoPath:(NSString*)videoPath succ:(void (^)())succ fail:(void (^)())fail
{
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality])
    {
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
        
        exportSession.outputURL = [NSURL fileURLWithPath:videoPath];
        
        exportSession.outputFileType = AVFileTypeMPEG4;
        
        CMTime start = CMTimeMakeWithSeconds(0, avAsset.duration.timescale);
        
        CMTime duration = avAsset.duration;
        
        CMTimeRange range = CMTimeRangeMake(start, duration);
        
        exportSession.timeRange = range;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status])
            {
                case AVAssetExportSessionStatusFailed:
                    NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                    fail();
                    break;
                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"Export canceled");
                    fail();
                    break;
                default:
                    succ();
                    break;
            }
        }];
    }
}

- (NSString *)msgTime
{
    NSDate *date = [_msg timestamp];
    
    NSString *time = [date shortTimeTextOfDate];
    return time;
}

- (NSInteger)status
{
    if (_status == EIMAMsg_Init || _status == EIMAMsg_WillSending || _status == TIM_MSG_STATUS_SEND_SUCC)
    {
        return _status;
    }
    else
    {
        return [_msg status];
    }
}

- (IMAUser *)getSender
{
    if ([[_msg getConversation] getType] == TIM_C2C)
    {
        NSString *sender = [_msg sender];
        IMAUser *user = [[IMAPlatform sharedInstance].contactMgr getUserByUserId:sender];
        if (user) {
            return user;
        } else {
            __block IMAUser *stranger = nil;
            [_msg getSenderProfile:^(TIMUserProfile *profile) {
               stranger = [[IMAUser alloc] initWithUserInfo:profile];
            }];
            return stranger;
        }
    }
    else if ([[_msg getConversation] getType] == TIM_GROUP)
    {
        IMAGroupMember *member = [[IMAGroupMember alloc] initWithMemberInfo:[_msg getSenderGroupMemberProfile]];
        member.nickName = [_msg getSenderNickname];
        if (member)
        {
            __block IMAUser *user = nil;
            [_msg getSenderProfile:^(TIMUserProfile *profile) {
                user = [[IMAUser alloc] initWithUserInfo:profile];
            }];
            
            if ([[IMAPlatform sharedInstance].contactMgr isMyFriend:user]) {
                
                IMAUser *myFriendUser = [[IMAPlatform sharedInstance].contactMgr getUserByUserId:user.userId];
                member.nickName = myFriendUser.nickName;
                member.remark = myFriendUser.remark;
                member.icon = myFriendUser.icon;
//                return myFriendUser;
            }
            
            [member setIcon:user.icon];
             //1111
            if (member.memberInfo.nameCard.length <= 0)
            {
                __block TIMUserProfile *pro = nil;
                [_msg getSenderProfile:^(TIMUserProfile *profile) {
                    pro = profile;
                    if (![NSString isEmpty:profile.nickname])
                    {
                        [member setNickName:profile.nickname];
                    }
                    else
                        [member setNickName:profile.identifier];
                }];
            }
        }
        return member;
    }
    return nil;
}

- (NSAttributedString *)attributeMsgTip {
    
    
    NSMutableAttributedString *muAtt = [[NSMutableAttributedString alloc] initWithAttributedString:[self senderName]];
    [muAtt appendAttributedString:[self lastMsgContent]];
    
    return muAtt;
    
}
- (NSString *)messageTip
{
    TIMConversation *conv = [_msg getConversation];
    TIMConversationType type = [conv getType];
    
    TIMElem *elem = (TIMElem *)[_msg getElem:0];
    if (elem)
    {
        if (type == TIM_C2C)
        {
            return [elem showDescriptionOf:self];
        }
        else if (type == TIM_GROUP)
        {
            if ([_msg isSelf])
            {
                return [elem showDescriptionOf:self];
            }
            else
            {
                if (self.type == EIMAMSG_GroupTips)
                {
                    return [elem showDescriptionOf:self];
                }
                else
                {
                    TIMGroupMemberInfo *profile = [_msg getSenderGroupMemberProfile];
                    if (profile)
                    {
                        return [NSString stringWithFormat:@"%@:%@", [profile showTitle], [elem showDescriptionOf:self]];
                    }
                    else
                    {
                        IMAUser *sender = [self getSender];
                        if (sender)
                        {
                            return [NSString stringWithFormat:@"%@:%@", [sender showTitle], [elem showDescriptionOf:self]];
                        }
                        else
                        {
                            return [NSString stringWithFormat:@"%@:%@", [_msg sender], [elem showDescriptionOf:self]];
                        }
                        
                    }
                }
                
            }
            
        }
        else if (type == TIM_SYSTEM)
        {
            return [NSString stringWithFormat:@"%@:%@", @"系统消息", [elem showDescriptionOf:self]];
        }
    }
    
    return nil;
}

- (NSAttributedString *)lastMsgContent {
    
    TIMConversation *conv = [_msg getConversation];
    TIMConversationType type = [conv getType];
    
    
    TIMElem *elem = (TIMElem *)[_msg getElem:0];
    
    if (elem) {
        
        if (type == TIM_SYSTEM) {
            
            NSString *str = [NSString stringWithFormat:@"%@:%@", @"系统消息", [elem showDescriptionOf:self]];
            
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
            
            return  attStr;
            
        } else {
            
            
            if ([self isWithdrawMsg]) {
                //如果为撤回消息
                NSString *lastStr = @"";
                if([self isMineMsg])
                {
                    lastStr = @"你撤回了一条消息";
                }
                else
                {
                    NSString *senderId = [NSString stringWithFormat:@"%@ 撤回了一条消息",[self getSender].nickName];
                    lastStr = senderId;
                }
                NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:lastStr attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
                
                return attStr;
            }
            NSMutableAttributedString *attStr = nil;
            if ([elem isKindOfClass:[TIMSoundElem class]]) {
                // 语音消息单独处理xxxx
                attStr = [[NSMutableAttributedString alloc] initWithString:[elem showDescriptionOf:self] attributes:@{NSFontAttributeName :UIFontCNMake(14), NSForegroundColorAttributeName : [self tipTextColor]}];
            }
            else if(self.type == EIMAMSG_TransferBalance)
            {
                //对转余额消息进行特殊处理
                attStr = [[NSMutableAttributedString alloc] initWithString:[elem showDescriptionOf:self] attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
                /**对打款方收到对方已收款或者已退还消息,会话列表对“【转余额】” 文字颜色改为红色*/
                NSDictionary *transferBalanceData = self.customMsgData[@"transferBalanceData"];
                /**type  1:待收款, 2:已收款, 3:被退还*/
                NSString *type = [NSString stringWithFormat:@"%@",transferBalanceData[@"type"]];
                NSString *fromId = transferBalanceData[@"fromId"];
                if ([fromId isEqualToString:CNUserShareModel.uid] && ![self.msg isReaded]) {
                    switch ([type intValue]) {
                        case 2:
                        case 3:
                        {
                            [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 5)];
                        }
                            break;
                        default:
                            break;
                    }
                }
            }
            else
                attStr = [[NSMutableAttributedString alloc] initWithString:[elem showDescriptionOf:self] attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
            
            return attStr;
            
        }
    }
    
    return  [[NSMutableAttributedString alloc] initWithString:@" "];
}
- (UIColor *)tipTextColor
{
    if (![self isVioceReaded] && ![self isMineMsg]) {
        return kRedColor;
    }
    return [self isMineMsg] ? self.status == EIMAMsg_SendSucc ? KGray101Color : kRedColor : KGray101Color;
}
- (NSAttributedString *)senderName {
    
    return [self newSenderName];
    
}
/// senderName 的 新方法
- (NSAttributedString *)newSenderName{
    
    //初始化 totalAtt, 最终的 totalAtt 由aiteAttStr,tipAtt,unReadMsgNumAtt,nameAtt 四部分构成
    NSMutableAttributedString *totalAtt = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];

    NSAttributedString *aiteAttStr = [self aiteAttStr];
    NSAttributedString *tipAtt = [self tipAtt];
    NSAttributedString *unReadMsgNumAtt = [self unReadMsgNumAtt];
    NSAttributedString *nameAtt = [self nameAtt];
    
    [totalAtt appendAttributedString:aiteAttStr];
    [totalAtt appendAttributedString:tipAtt];
    [totalAtt appendAttributedString:unReadMsgNumAtt];
    [totalAtt appendAttributedString:nameAtt];
    
    return totalAtt;
}

/// 返回@ 标识,群聊才有可能有值
- (NSAttributedString *)aiteAttStr
{
    TIMConversation *conv = [_msg getConversation];
    TIMConversationType type = [conv getType];
    NSMutableAttributedString *aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
    if (type == TIM_GROUP) {
        
        NSString *currentGroupId = [conv getReceiver];
        
        /**关于旧版本@标识和新版本@标识区别,旧逻辑本地只存了一个最新有人@我的群ID,不支持同时有多个群@我。 新版本会对每个群进行@标识存储*/

        /**旧版本 获取有人@我的群ID, 这个是为了兼容老版本*/
        NSString *oldgGroupId = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"IMAiteRemind_%@",CNUserShareModel.uid]];
        
        /**新版本,获取有人@我的群ID*/
        NSString *groupId = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"IMAiteRemind_%@_%@",CNUserShareModel.uid,currentGroupId]];
        
        if ([groupId isEqualToString:currentGroupId] || [oldgGroupId isEqualToString:currentGroupId])
        {
            
            if ([self isWithdrawMsg]) {
                //如果撤销消息 不显示 @我 信息
                aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
            }
            else
                aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"[有人@我]" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
                
            
        } else {
            if (self.type == EIMAMSG_AiteStatus && ![_msg isReaded]) {
                
                NSDictionary *dic = self.customMsgData;
                
                NSDictionary *groupAitDic = dic[@"groupAit"];
                
                NSArray *idArray = groupAitDic[@"ids"];
                
                if (idArray.count == 0) {
                    if ([groupAitDic.allKeys containsObject:@"isAitAll"]) {
                        if ([[groupAitDic objectForKey:@"isAitAll"] integerValue] == 1) {
                            //@所有人
                            if (![_msg isReaded]) {
//                                [[NSUserDefaults standardUserDefaults] setObject:currentGroupId forKey:[NSString stringWithFormat:@"IMAiteRemind_%@",CNUserShareModel.uid]];
//                                [[NSUserDefaults standardUserDefaults] synchronize];
                                
                                [[NSUserDefaults standardUserDefaults] setObject:currentGroupId forKey:[NSString stringWithFormat:@"IMAiteRemind_%@_%@",CNUserShareModel.uid,currentGroupId]];
                                [[NSUserDefaults standardUserDefaults] synchronize];
                            }
                            
                            if ([self isWithdrawMsg]) {
                                //如果撤销消息 不显示 @我 信息
                                aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
                            }
                            else
                                aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"[有人@我]" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
                        }
                    }
                    else if ([dic.allKeys containsObject:@"isAitAll"])
                    {
                        //兼容老版本
                        if ([[dic objectForKey:@"isAitAll"] integerValue] == 1) {
                            //@所有人
                            if (![_msg isReaded]) {
//                                [[NSUserDefaults standardUserDefaults] setObject:currentGroupId forKey:[NSString stringWithFormat:@"IMAiteRemind_%@",CNUserShareModel.uid]];
//                                [[NSUserDefaults standardUserDefaults] synchronize];
                                
                                [[NSUserDefaults standardUserDefaults] setObject:currentGroupId forKey:[NSString stringWithFormat:@"IMAiteRemind_%@_%@",CNUserShareModel.uid,currentGroupId]];
                                [[NSUserDefaults standardUserDefaults] synchronize];
                            }
                            
                            if ([self isWithdrawMsg]) {
                                //如果撤销消息 不显示 @我 信息
                                aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
                            }
                            else
                                aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"[有人@我]" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
                        }
                    }
                }
                else if (idArray.count > 0){
                    if ([idArray containsObject:CNUserShareModel.uid]) {
                        
                        if (![_msg isReaded]) {
//                            [[NSUserDefaults standardUserDefaults] setObject:currentGroupId forKey:[NSString stringWithFormat:@"IMAiteRemind_%@",CNUserShareModel.uid]];
//                            [[NSUserDefaults standardUserDefaults] synchronize];
                            [[NSUserDefaults standardUserDefaults] setObject:currentGroupId forKey:[NSString stringWithFormat:@"IMAiteRemind_%@_%@",CNUserShareModel.uid,currentGroupId]];
                            [[NSUserDefaults standardUserDefaults] synchronize];
                        }
                        
                        if ([self isWithdrawMsg]) {
                            //如果撤销消息 不显示 @我 信息
                            aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
                        }
                        else
                            aiteAttStr = [[NSMutableAttributedString alloc] initWithString:@"[有人@我]" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : kRedColor}];
                    }
                }
                
            }
            
        }
    }
    return aiteAttStr;
}

/// 返回发送人昵称,单聊不需要显示昵称,群聊如果不是自己发送的才显示昵称
- (NSAttributedString *)nameAtt
{
    TIMConversation *conv = [_msg getConversation];
    TIMConversationType type = [conv getType];
    NSMutableAttributedString *nameAtt = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
    if (type == TIM_GROUP && self.type != EIMAMSG_GroupTips) {
        
        if (![_msg isSelf]) {
            if (![self isWithdrawMsg]) {
                IMAUser *sender = [self getSender];
                if (sender) {
                    [nameAtt appendString:[NSString stringWithFormat:@"%@: ",[sender showTitle]]];
                } else {
                    [nameAtt appendString:[NSString stringWithFormat:@"%@: ",[_msg sender]]];
                }
                if ([nameAtt.string hasPrefix:@"admin"]) {
                    //处理 是APP管理员发送的消息
                    nameAtt = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];

                }
                if (self.type == EIMAMSG_ShareLink)
                {
                    nameAtt = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
                }
                
            }
        }
    }
    
    return nameAtt;
    
}

/// 返回未读数,群聊开启消息免打扰了才需要显示
- (NSAttributedString *)unReadMsgNumAtt
{
    TIMConversation *conv = [_msg getConversation];
    TIMConversationType type = [conv getType];
    NSMutableAttributedString *unReadMsgNumAtt = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
    
    if (type == TIM_GROUP)
    {
        
        IMAGroup *group = [[IMAPlatform sharedInstance].contactMgr getUserByGroupId:[conv getReceiver]];
        
        /**如果该群是消息免打扰状态,需要拼接上消息未读数*/
        if ([[group receiveMessageOpt] isEqualToString:@"接收但不提醒"])
        {
            if ([conv getUnReadMessageNum] > 1)
            {
                [unReadMsgNumAtt appendString:[NSString stringWithFormat:@"[%d条]",[conv getUnReadMessageNum]]];
            }
        }
    }
    
    return unReadMsgNumAtt;
}

/// 对一些特殊的消息返回 红色标签提醒
- (NSAttributedString *)tipAtt
{
    NSMutableAttributedString *tipAtt = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : UIFontCNMake(14), NSForegroundColorAttributeName : KGray101Color}];
    if (self.type == EIMAMSG_SendGiftSuccess) {
        //送礼填写地址成功 送礼者 红字提醒
        NSString *redTipStr = @"Ta填写礼包地址 ";
        [tipAtt appendString:redTipStr];
        [tipAtt addAttribute:NSForegroundColorAttributeName value:[UIColor qmui_colorWithHexString:@"#FC1541"] range:NSMakeRange(0, redTipStr.length)];
    }
    else if (self.type == EIMAMSG_ReceviedGiftSuccess) {
        //送礼填写地址成功 收礼者 红字提醒
        NSString *redTipStr = @"已填写礼包地址 ";
        [tipAtt appendString:redTipStr];
        [tipAtt addAttribute:NSForegroundColorAttributeName value:[UIColor qmui_colorWithHexString:@"#FC1541"] range:NSMakeRange(0, redTipStr.length)];
        
    }
    else if (self.type == EIMAMSG_ShareGift)
    {
        NSString *redTipStr = @"";

        NSDictionary *giftInfoData = self.customMsgData[@"giftInfoData"];
        if ([giftInfoData[@"toType"] integerValue] == 1) {
            if (![self isWithdrawMsg]) {
                //发送礼物
                if ([self isMineMsg]) {
                    //发送方
                    redTipStr = @"给Ta送礼 ";
                }
                else //接受方
                    redTipStr = @"有礼物 ";
            }
        }
        else if ([giftInfoData[@"toType"] integerValue] == 2)
        {
            //收礼物
            if ([giftInfoData[@"giftType"] integerValue] == 1) {
                // 对方已收礼
                redTipStr = @"Ta已收礼 ";
                
            }
            else if ([giftInfoData[@"giftType"] integerValue] == 2) {
                // 自己已收礼
                redTipStr = @"已收礼 ";
            }
        }
        [tipAtt appendString:redTipStr];
        [tipAtt addAttribute:NSForegroundColorAttributeName value:[UIColor qmui_colorWithHexString:@"#FC1541"] range:NSMakeRange(0, redTipStr.length)];
    }
    else if (self.type == EIMAMSG_HaveCoupon && ![_msg isReaded])
    {
        //有未领取的优惠券
        NSString *redTipStr = @"[有红包]";
        [tipAtt appendString:redTipStr];
        [tipAtt addAttribute:NSForegroundColorAttributeName value:[UIColor qmui_colorWithHexString:@"#FC1541"] range:NSMakeRange(0, redTipStr.length)];
        
    }
    
    TIMConversation *conv = [_msg getConversation];
    TIMConversationType type = [conv getType];
    if (type == TIM_C2C) {
        /**未领取的转账数据*/
        NSArray *unreceivedTransferBalanceArray = [[CNTransferBalanceUnreceivedCache cache] objectForKey:[NSString stringWithFormat:@"key_%@_%@",CNUserShareModel.uid,[conv getReceiver]]];
        if (unreceivedTransferBalanceArray && unreceivedTransferBalanceArray.count > 0) {
            NSString *redTipStr = @"[转余额]";
            [tipAtt appendString:redTipStr];
            [tipAtt addAttribute:NSForegroundColorAttributeName value:[UIColor qmui_colorWithHexString:@"#FC1541"] range:NSMakeRange(0, redTipStr.length)];
        }
    }
    return tipAtt;
}
- (void)remove
{
    if (self.type == EIMAMSG_TimeTip || self.type == EIMAMSG_SaftyTip)
    {
        // 属于自定义的类型,不在IMSDK数据库里面,不能调remove接口
        return;
    }
    
    BOOL succ = [_msg remove];
    DebugLog(@"删除成功:%d", succ);
}

- (void)changeTo:(IMAMsgStatus)status needRefresh:(BOOL)need
{
    if (_status != status)
    {
        if (need)
        {
            self.status = status;
        }
        else
        {
            _status = status;
        }
    }
}

- (BOOL)isMineMsg
{
    return [_msg isSelf];
}

- (BOOL)isC2CMsg
{
    return [[self.msg getConversation] getType] == TIM_C2C;
}
- (BOOL)isGroupMsg
{
    return [[self.msg getConversation] getType] == TIM_GROUP;
}

- (BOOL)isSystemMsg
{
    return self.type == TIM_SYSTEM;
}

- (BOOL)isVailedType
{
    return self.type != EIMAMSG_TimeTip && self.type != EIMAMSG_SaftyTip;
}

- (BOOL)isMultiMsg
{
    return _type == EIMAMSG_Face || _msg.elemCount > 1;
}

- (NSMutableDictionary *)affixParams
{
    if (!_affixParams)
    {
        _affixParams = [NSMutableDictionary dictionary];
    }
    return _affixParams;
}


- (void)addString:(NSString *)aValue forKey:(id<NSCopying>)aKey
{
    [self.affixParams addString:aValue forKey:aKey];
}

- (void)addInteger:(NSInteger)aValue forKey:(id<NSCopying>)aKey
{
    [self.affixParams addInteger:aValue forKey:aKey];
}

- (void)addCGFloat:(CGFloat)aValue forKey:(id<NSCopying>)aKey
{
    [self.affixParams addCGFloat:aValue forKey:aKey];
}

- (void)addBOOL:(BOOL)aValue forKey:(id<NSCopying>)aKey
{
    [self.affixParams addBOOL:aValue forKey:aKey];
}

- (NSString *)stringForKey:(id<NSCopying>)key
{
    return [self.affixParams stringForKey:key];
}
- (NSInteger)integerForKey:(id<NSCopying>)key
{
    return [self.affixParams integerForKey:key];
}
- (BOOL)boolForKey:(id<NSCopying>)key
{
    return [self.affixParams boolForKey:key];
}
- (CGFloat)floatForKey:(id<NSCopying>)key
{
    return [self.affixParams floatForKey:key];
}

- (BOOL)isEqual:(id)object
{
    BOOL isEqual = [super isEqual:object];
    if (!isEqual)
    {
        if ([object isKindOfClass:[IMAMsg class]])
        {
            IMAMsg *msg = (IMAMsg *)object;
            isEqual = [self.msg.msgId isEqualToString:msg.msg.msgId];
        }
    }
    
    return isEqual;
}
- (BOOL)isVioceReaded
{
    if ([self.msg customInt] == kReadedVoice || [self isMineMsg]) {
        return YES;
    }
    else
        return NO;
}
- (BOOL)isWithdrawMsg
{
    if (self.msg.status == TIM_MSG_STATUS_LOCAL_REVOKED ) {
        return YES;
    }
    else
        return NO;
//    NSString *string = [[NSString alloc] initWithData:[self.msg customData] encoding:NSUTF8StringEncoding];
//    if ([string isEqualToString:kWithDrawMessageType]) {
//        return YES;
//    }
//    else
//        return NO;
}
- (void)updateMsg:(TIMMessage *)msg
{
    _msg = msg;
}
@end