IMAConversationManager.m 76.1 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 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
//
//  IMAConversationManager.m
//  CNLiveNewIMAManagerKit
//
//  Created by AlexiChen on 16/2/18.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "IMAConversationManager.h"
#import "CNGroupListInfoModel.h"
#import "CNGroupListAvaterUtil.h"
#import "CNUserProfileFMDBManager.h"

@implementation IMAConversationChangedNotifyItem

- (instancetype)initWith:(IMAConversationChangedNotifyType)type
{
    if (self = [super init])
    {
        _type = type;
    }
    return self;
}

- (NSNotification *)changedNotification
{
    NSNotification *notify = [NSNotification notificationWithName:[self notificationName] object:self];
    return notify;
}
- (NSString *)notificationName
{
    return [NSString stringWithFormat:@"IMAConversationChangedNotification_%d", (int)_type];
}

@end

@interface IMAConversationManager ()
{
    NSInteger _index;
    NSInteger _toIndex;
    
    //查询撤销消息相关
    NSTimer *_timer;
    IMAConversation *_myconversation;
    TIMMessage *_lastmsg;
    NSString *_uniqid;
    
    BOOL _isDaren;
    BOOL _isMoment;
}

@end
@implementation IMAConversationManager


- (instancetype)init
{
    if (self = [super init])
    {
        _conversationList = [[CLSafeSetArray alloc] init];
    }
    return self;
}

- (void)releaseChattingConversation
{
    [_chattingConversation releaseConversation];
    _chattingConversation = nil;
}

- (void)asyncUpdateConversationListComplete
{
    [self updateOnLocalMsgComplete];
}

/**
 这是新的方法
 */
-(void)asyncSationList
{
    CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
    _toIndex = 0;
    NSMutableArray * conversationList = [[NSMutableArray alloc] init];
    NSLog(@"covname == 开始遍历 %lu",(unsigned long)[[TIMManager sharedInstance] getConversationList].count);
    
    for (TIMConversation *conv in [[TIMManager sharedInstance] getConversationList]) {

        if (conv.getType == TIM_GROUP) {
            if (![[IMAPlatform sharedInstance].contactMgr.groupIdsList containsObject:conv.getReceiver] && conv.getUnReadMessageNum && ![conv.getReceiver hasPrefix:@"AVCR"])
            {
                //获取新群的群资料,并缓存到内存中
                [self getGroupInfo:conv.getReceiver];
                if (![IMAPlatform sharedInstance].didConnectSuccess) {
                     [conversationList addObject:conv];
                }
            }
            else
            {
                if ([[IMAPlatform sharedInstance].contactMgr.groupIdsList containsObject:conv.getReceiver]) {
                    [conversationList addObject:conv];
                }
                else
                {
                    if (![IMAPlatform sharedInstance].didConnectSuccess) {
                         [conversationList addObject:conv];
                    }
                }
            }

        }
        else
            [conversationList addObject:conv];

    }
    
    NSMutableArray * tempArray = [[NSMutableArray alloc] init];
    
    for (id conversationId in conversationList) {
        
        if ([conversationId isKindOfClass:[TIMConversation class]]) {
            
            TIMConversation *conversation = (TIMConversation * )conversationId;
            
            //如果是未知的 后台消息,直接 跳出循环ƒ
            if ([conversation.getReceiver hasPrefix:@"sys"]) {
                if ([conversation.getReceiver isEqualToString:CNLifeHaoUserId] ||  [conversation.getReceiver isEqualToString:CNFirendMomentVideoUploadFinishUserId] || [conversation.getReceiver isEqualToString:CNWithdrawMessage] || [conversation.getReceiver isEqualToString:CNJoinFeatureGroupInvitation] || [conversation.getReceiver isEqualToString:CNWithNews] || [conversation.getReceiver isEqualToString:CNWithLive] || [conversation.getReceiver isEqualToString:CNWithVideo]|| [conversation.getReceiver isEqualToString:CNWithRepastPay]|| [conversation.getReceiver isEqualToString:CNWithReceipt]
                    || [conversation.getReceiver isEqualToString:CNWithRepastVerify])
                {
//                    NSLog(@"已知后台消息");
                }else{
                    NSLog(@"未知后台消息不添加到会话列表");
                    continue;
                }
            }
            if ([conversation.getReceiver hasPrefix:@"admin"]) continue;
            
            __block IMAConversation *conv = nil;
            if ([conversation getType] == TIM_SYSTEM) {
                // 可能返回空
                conv = [[IMACustomConversation alloc] initWith:conversation];
                conv.convTime = [self getLastDisplayDate:conversation];
                if (conv)
                {
                    if(![[[conv conversation] getReceiver] isEqualToString:@""])
//                        [_conversationList addObject:conv];
                        [tempArray addObject:conv];
                }
                continue;
            }else{
                
                NSString *receiver = [conversation getReceiver];

                if ([receiver isEqualToString:CNWithdrawMessage] || [receiver isEqualToString:CNFirendMomentUserId] || [receiver isEqualToString:CNFirendMomentVideoUploadFinishUserId]  || [receiver hasPrefix:@"AVCR"] || [receiver isEqualToString:CNWithSystemMessage]) continue;
                
                if (![receiver isEqualToString:CNWithdrawMessage] && ![receiver isEqualToString:CNFirendMomentUserId]  && ![receiver isEqualToString:CNFirendMomentVideoUploadFinishUserId] && ![receiver hasPrefix:@"AVCR"] ) {
                    
                    conv = [[IMAConversation alloc] initWith:conversation];
                    conv.convTime = [self getLastDisplayDate:conversation];
                    if (conv) {
                        
                        if(![[[conv conversation] getReceiver] isEqualToString:@""])
//                            [_conversationList addObject:conv];
                            [tempArray addObject:conv];
                    }
                }
            }
            
            if (_chattingConversation && [_chattingConversation isEqual:conv])
            {
                [conv copyConversationInfo:_chattingConversation];
                // 防止因中途在聊天时,出现onrefresh回调
                _chattingConversation = conv;
            }
        }
    }
    //根据时间排序
    [tempArray sortWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(IMAConversation * obj1, IMAConversation *obj2) {
        return [obj2.convTime compare:obj1.convTime];
    }];
    //_conversationList 更新所有会话
    [_conversationList removeAllObjects];
    [_conversationList addObjectsFromArray:tempArray];
    
    switch ([IMAPlatform sharedInstance].platformType) {
        case IMPlatformTypeC:
        {
            /**是否有创建亲情群入口,默认有,如果被删了,就不存在了*/
            BOOL hasCreateFamily = YES;
            NSString *deletedCreateFamily = [[NSUserDefaults standardUserDefaults] objectForKey:CNDeletedCreateFamily];
            if ([deletedCreateFamily isEqualToString:@"1"]) {
                //首页会话已经删除情亲群入口
                hasCreateFamily = NO;
            }
            if (hasCreateFamily) {
                /**创建亲情群会话并插入会话列表第一个位置*/
                CNCreateFamilyGroupConversation *familyGroupConversation = [[CNCreateFamilyGroupConversation alloc] init];
                [_conversationList insertObject:familyGroupConversation atIndex:0];
            }
            
            if (self.isPlay) {
                IMAPlayMusicConversation *tempCon = [[IMAPlayMusicConversation alloc] init];
                tempCon.receiver = [NSString stringWithFormat:@"正在播放  %@",self.audioModelDic[@"title"]];
                [_conversationList insertObject:tempCon atIndex:0];//!_isDisconnect ? 0: 1
            }
        }
            break;
            
        default:
            break;
    }
   
    CFAbsoluteTime endTime = (CFAbsoluteTimeGetCurrent() - startTime);
    NSLog(@"asyncUpdateConversationList Complete方法耗时: %f ms", endTime * 1000.0);
    
    [self asyncUpdateConversationListComplete];
    
}
/// 获取会话最后一条消息的时间
/// @param conv 会话
- (NSDate *)getLastDisplayDate:(TIMConversation *)conv
{
    TIMMessageDraft *draft = [conv getDraft];
    if(draft){
        return draft.timestamp;
    }
    TIMMessage *msg = [conv getLastMsg];
    if (msg) {
        return msg.timestamp;
    }
    
    /**消息被清空, 拿本地保存的最后一条消息时间*/
    CNUserProfile *profile = [[CNUserProfileFMDBManager manager] searchProfile:[conv getReceiver]];
    if (profile.date) {
        return profile.date;
    }
    
    return [NSDate distantPast];
}
- (void)asyncUpdateConversationList
{
    [self asyncSationList];
}
 
- (void)asyncConversationList
{
    DebugLog(@"==========>>>>>>>>>asyncConversationList");
//    zl__监听新消息之前,查看是否是首次打开应用,如果是就删除之前所有已读会话,删除后修改本地标识为YES, 区分用户
    NSArray *conversationList = [[TIMManager sharedInstance] getConversationList];
    NSString *key = [NSString stringWithFormat:@"DisableRecentContact_%@", CNUserShareModel.uid];
    BOOL ret = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (ret == NO) {
        for (TIMConversation *timConv in conversationList) {
            if ([timConv getUnReadMessageNum] <=  0) {
                [[TIMManager sharedInstance] deleteConversationAndMessages:[timConv getType] receiver:[timConv getReceiver]];
                [[CNUserProfileFMDBManager manager] deleteProfileById:[timConv getReceiver]];
            }
        }
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    }
    [self asyncUpdateConversationList];
}

- (void)addConversationChangedObserver:(id)observer handler:(SEL)selector forEvent:(NSUInteger)eventID
{
    NSUInteger op = EIMAContact_AddNewSubGroup;
    do
    {
        if (op & eventID)
        {
            NSString *notification = [NSString stringWithFormat:@"IMAConversationChangedNotification_%d", (int)op];
            [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:notification object:nil];
            eventID -= op;
        }
        op = op << 1;
        
    } while (eventID > 0);
}

- (void)removeConversationChangedObser:(id)observer
{
    [[NSNotificationCenter defaultCenter] removeObserver:observer];
}

- (void)deleteConversation:(IMAConversation *)conv needUIRefresh:(BOOL)need
{
    NSInteger index = [_conversationList indexOfObject:conv];
    if (index >= 0 && index < [_conversationList count])
    {
        [conv setReadAllMsg];
//        self.unReadMessageCount -= [conv unReadCount];
        [_conversationList removeObject:conv];
        
        if ([conv type] == TIM_C2C)
        {
//            [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
            if ([[conv receiver] isEqualToString:CNDarenHaoUserId])
            {
                [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
                
            }else if ([[conv receiver] isEqualToString:CNLifeHaoUserId])
            {
                [[TIMManager sharedInstance] deleteConversationAndMessages:[conv type] receiver:[conv receiver]];

            }else if ([[conv receiver] isEqualToString:CNFirendMomentUserId])
            {
                
            }else{
                //zl__删除回话,改为删除回话和消息
                [[TIMManager sharedInstance] deleteConversationAndMessages:[conv type] receiver:[conv receiver]];
                [conv cleanMsgCache];
                //删除会话时删除本地数据
                [[CNUserProfileFMDBManager manager] deleteProfileById:[conv receiver]];
                
                //删除本地聊天下载数据
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager removeItemAtPath:[CNLiveBusinessTools getChatImageFile:conv.receiver] error:NULL])
                {
                    NSLog(@"Removed ChatImageFile successfully");
                }
                if ([fileManager removeItemAtPath:[CNLiveBusinessTools getChatVideoFile:conv.receiver] error:NULL])
                {
                    NSLog(@"Removed ChatVideoFile successfully");
                }
                if ([fileManager removeItemAtPath:[CNLiveBusinessTools audioChatFilePathByUserId:conv.receiver] error:NULL])
                {
                    NSLog(@"Removed audioChatFile successfully");
                }
                if ([fileManager removeItemAtPath:[CNLiveBusinessTools getChatFilesPathByUserId:conv.receiver] error:NULL])
                {
                    NSLog(@"Removed audioChatFile successfully");
                }
                [CNLivePhotoBrowserCache delectTableWithTableName:conv.receiver];

            }
        }
        else if ([conv type] == TIM_GROUP)
        {
            [[TIMManager sharedInstance] deleteConversationAndMessages:[conv type] receiver:[conv receiver]];
            [[CNUserProfileFMDBManager manager] deleteProfileById:[conv receiver]];
            [conv cleanMsgCache];
        }
        
        if (need)
        {
            //zx
            [self updateOnDelete:conv atIndex:index];
        }
    }
}

- (IMAConversation *)chatWith:(IMAUser *)user
{
    TIMConversation *conv = nil;
    if ([user isC2CType])
    {
        conv = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:[user userId]];
    }
    else if([user isGroupType])
    {
        conv = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:[user userId]];
    }
    else if ([user isSystemType])
    {
        // 暂不支持System消息
        return nil;
    }
    
//    self.unReadMessageCount -= [conv getUnReadMessageNum];

//    [conv setReadMessage:nil succ:nil fail:nil];
    
    if (conv)
    {
        IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
        
        NSInteger index = [_conversationList indexOfObject:temp];
        if (index >= 0 && index < _conversationList.count)
        {
            IMAConversation *ret = [_conversationList objectAtIndex:index];
            _chattingConversation = ret;
            _chattingConversation.lastMessage = _chattingConversation.lastMessage;
            return ret;
        }
        
        _chattingConversation = temp;
        return temp;
    }
    return nil;
}
- (IMAConversation *)chatRoomWith:(IMAUser *)user
{
    TIMConversation *conv = nil;
    if ([user isC2CType])
    {
        conv = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:[user userId]];
    }
    else if([user isGroupType])
    {
        conv = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:[user userId]];
    }
    else if ([user isSystemType])
    {
        // 暂不支持System消息
        return nil;
    }
    
//        self.unReadMessageCount -= [conv getUnReadMessageNum];
    
    [conv setReadMessage:nil succ:nil fail:nil];
    
    if (conv)
    {
        IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
        
        NSInteger index = [_conversationList indexOfObject:temp];
        if (index >= 0 && index < _conversationList.count)
        {
            IMAConversation *ret = [_conversationList objectAtIndex:index];
//            _chattingConversation = ret;
//            _chattingConversation.lastMessage = _chattingConversation.lastMessage;
            return ret;
        }
        
        return temp;
    }
    return nil;
}
// 主用要于自定义类型
- (IMAConversation *)queryConversationWithType:(IMAConType)user
{
    //    for (NSInteger i = 0; i < [_conversationList count]; i++)
    //    {
    //        IMAConversation *conv = [_conversationList objectAtIndex:i];
    //        if ([conv isChatWith:user])
    //        {
    //            return conv;
    //        }
    //    }
    return nil;
}

- (IMAConversation *)queryConversationWith:(IMAUser *)user
{
    if (user)
    {
    for (NSInteger i = 0; i < [_conversationList count]; i++)
    {
        IMAConversation *conv = [_conversationList objectAtIndex:i];
        if ([conv isChatWith:user])
        {
            return conv;
        }
    }
    }
    return nil;
}
//删除会话并删除本地聊天记录
- (void)removeConversationWith:(IMAUser *)user
{
    //chatRoomWith 设置为当前被删除的会话为正在聊天会话
    IMAConversation *deleteConv = [[IMAPlatform sharedInstance].conversationMgr chatRoomWith:user];
    if (![_conversationList containsObject:deleteConv]) {
        UITabBarController *tabVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        if ([tabVc isKindOfClass:[UITabBarController class]]) {
            UINavigationController *navVC = tabVc.selectedViewController;
            
            BOOL isHasChat = NO; //导航 栈里是否有聊天控制器
            NSInteger idx = 0; // 记录聊天 上一个控制器的在导航 栈里的位置
            
            if ([navVC isKindOfClass:[UINavigationController class]]) {
                for (int i =0 ; i < navVC.viewControllers.count; i++) {
                    UIViewController *VC = [navVC.viewControllers objectAtIndex:i];
                    if ([VC isKindOfClass:[NSClassFromString(@"CNChatViewController") class]])
                    {
                        isHasChat = YES;
                        if ((i - 2) > 0) {
                            idx = i -2;
                        }
                    }
                }
            }
            
            if (isHasChat) {
                //如果存在聊天控制器才跳转
                if (idx >= 0) {
                    if ([[deleteConv.conversation getReceiver] hasPrefix:@"AVCR"] || [user.userId isEqualToString:[IMAPlatform sharedInstance].host.userId]) {
                        
                        // 聊天室 不返回
                        
                    }
                    else
                    {
                        if ([user.userId isEqualToString:_chattingConversation.receiver]) {
                            //被删的是当前聊天的才返回到首页
                            UIViewController *toVC = [navVC.viewControllers objectAtIndex:idx];
                            [[self navigationViewController] popToViewController:toVC animated:YES];
                        }
                    }
                  
                }
            }
        }
        [[CNUserProfileFMDBManager manager] deleteProfileById:[deleteConv receiver]];
        //删除本地记录
        [deleteConv.conversation deleteLocalMessage:^{
        } fail:^(int code, NSString *msg) {
        }];
        [deleteConv cleanMsgCache];
        return ;
    }
    
    for (NSInteger i = 0; i < [_conversationList count]; i++)
    {
        IMAConversation *conv = [_conversationList objectAtIndex:i];
       
        if ([conv isChatWith:user])
        {
            if (conv == _chattingConversation)
            {
//                // TODO:通知界面
                if ([[deleteConv.conversation getReceiver] hasPrefix:@"AVCR"] || [user.userId isEqualToString:[IMAPlatform sharedInstance].host.userId]) {
                    //聊天室 不返回
                    
                }
                else
                {
                    //导航栈里是否有播放器
                    BOOL isHasPlayer = NO;
                    UITabBarController *tabVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                    if ([tabVc isKindOfClass:[UITabBarController class]]) {
                        UINavigationController *navVC = tabVc.selectedViewController;
                        if ([navVC isKindOfClass:[UINavigationController class]]) {
                            for (int i = navVC.viewControllers.count; i > 0; i--) {
                                UIViewController *VC = [navVC.viewControllers objectAtIndex:i - 1];
                                if ([VC isKindOfClass:[NSClassFromString(@"LVCLivePlayerController") class]])
                                {
                                    isHasPlayer = YES;
                                    break ;
                                }
                                else if ([VC isKindOfClass:[NSClassFromString(@"CNPlayDetailViewController") class]])
                                {
                                    isHasPlayer = YES;
                                    break ;
                                }
                            }
                        }
                        
                        
                        if (isHasPlayer) {
                            // 上个界面如果有直播或者点播 不返还到首页
                            
//                            UIViewController *toVC = [navVC.viewControllers objectAtIndex:idx];
//                            [[IMAAppDelegate sharedAppDelegate] popToViewController:toVC];
                        }
                        else
                        {
                            if ([user.userId isEqualToString:_chattingConversation.receiver]) {
                                NSLog(@"user.userId = %@  _chattingConversation = %@",user.userId,_chattingConversation.receiver );
                                //被删的是当前聊天的才返回到首页
                                [[self navigationViewController] popToRootViewControllerAnimated:YES];
                            }
                        }
                    }
                }
              
            }
            [_conversationList removeObjectAtIndex:i];
            [conv setReadAllMsg];
//            self.unReadMessageCount -= [conv unReadCount];
            
            if ([conv type] == TIM_C2C)
            {
                [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
            }
            else if ([conv type] == TIM_GROUP)
            {
                [[TIMManager sharedInstance] deleteConversationAndMessages:[conv type] receiver:[conv receiver]];
                [[CNUserProfileFMDBManager manager] deleteProfileById:[conv receiver]];
            }
            
            
            //zl 删除本地记录
            [conv.conversation deleteLocalMessage:^{
            } fail:^(int code, NSString *msg) {
            }];
            [conv cleanMsgCache];
            
            
            [self updateOnDelete:conv atIndex:i];
            break;
        }
    }
}
//删除会话不删除本地聊天记录
- (void)removeOnlyConversationWith:(IMAUser *)user
{
    for (NSInteger i = 0; i < [_conversationList count]; i++)
    {
        IMAConversation *conv = [_conversationList objectAtIndex:i];
        if ([conv isChatWith:user])
        {
            if (conv == _chattingConversation)
            {
                // TODO:通知界面
                [[self navigationViewController] popToRootViewControllerAnimated:YES];
            }
            [_conversationList removeObjectAtIndex:i];
            [conv setReadAllMsg];
            
            if ([conv type] == TIM_C2C)
            {
                [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
            }
            else if ([conv type] == TIM_GROUP)
            {
                [[TIMManager sharedInstance] deleteConversationAndMessages:[conv type] receiver:[conv receiver]];
                [[CNUserProfileFMDBManager manager] deleteProfileById:[conv receiver]];
            }
            
            [self updateOnDelete:conv atIndex:i];
            break;
        }
    }
}
//- (void)removeConversationWithConv:(IMAConversation *)conv
//{
//    if (conv == nil)
//    {
//        return;
//    }
//    [[TIMManager sharedInstance] deleteConversation:[conv type] receiver:[conv receiver]];
//}

- (void)updateConversationWith:(IMAUser *)user
{
    IMAConversation *conv = [self queryConversationWith:user];
    if (conv)
    {
        [self updateOnConversationChanged:conv];
    }
}

- (NSInteger)insertPosition
{
    IMAPlatform *mp = [IMAPlatform sharedInstance];
    
    switch (mp.platformType) {
        case IMPlatformTypeC:
        {
            /**是否有创建亲情群入口,默认有,如果被删了,就不存在了*/
            BOOL hasCreateFamily = YES;

            NSString *deletedCreateFamily = [[NSUserDefaults standardUserDefaults] objectForKey:CNDeletedCreateFamily];
            if ([deletedCreateFamily isEqualToString:@"1"]) {
                //首页会话已经删除情亲群入口
                hasCreateFamily = NO;
            }
            
            if (!mp.isConnected && self.isPlay)
            {
                if (hasCreateFamily) {
                    //没联网&听见中国在播放&有情亲群
                    return 3 + _toIndex;
                }
                //没联网&听见中国在播放
                return 2 + _toIndex;
            }
            if (!mp.isConnected || self.isPlay) {
                
                if (hasCreateFamily) {
                    //听见中国或者网络其中一个 & 有情亲群
                    return 2 + _toIndex;
                }
                //听见中国或者网络其中一个
                return 1 + _toIndex;
                
            }
            
            if (hasCreateFamily) {
                //联网 & 有情亲群
                return 1 + _toIndex;
            }
        }
            break;
        case IMPlatformTypeB:
        {
            if (!mp.isConnected) {
                //显示断网
                return 1 + _toIndex;
                
            }
        }
        default:
            break;
    }
    //联网
    return _toIndex;
}
/**
 *  新消息通知
 *
 *  @param msgs 新消息列表,TIMMessage 类型数组
 */
- (void)onNewMessage:(NSArray *)msgs
{
    NSLog(@"onNewMessage:%@",msgs);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kIMAMSG_OnNewMessageNotification" object:msgs];
    
    for (TIMMessage *msg in msgs)
    {
        IMAMsg *imamsg = [IMAMsg msgWith:msg];
        if (imamsg == nil) {
            //收到的消息有问题
            break ;
        }
        TIMConversation *conv = [msg getConversation];
        NSLog(@"getReceiver =========== %@",conv.getReceiver);
        if ([conv.getReceiver hasPrefix:@"family_"]) {
            //家园新消息
            NSInteger unReadMessageNum = [conv getUnReadMessageNum];
            [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_FamilyNewMessageNotification object:nil userInfo:@{
                @"groupId" : conv.getReceiver,
                @"unReadMessageNum" : @(unReadMessageNum)}
            ];

        }
        if ([[imamsg.msg getElem:0] isKindOfClass:[TIMCustomElem class]]) {
            /**处理所有收到的自定义消息*/
            BOOL isBreak = [self handleCustomMsg:imamsg conv:conv];
            if(isBreak)break;
        }
        
        //如果是未知的 后台会话,直接 跳出循环ƒ
        if ([conv.getReceiver hasPrefix:@"sys"]) {
            
            if ([conv.getReceiver isEqualToString:CNDarenHaoUserId]
                ||[conv.getReceiver isEqualToString:CNLifeHaoUserId]
                || [conv.getReceiver isEqualToString:CNFirendMomentUserId]
                || [conv.getReceiver isEqualToString:CNFirendMomentVideoUploadFinishUserId]
                || [conv.getReceiver isEqualToString:CNWithdrawMessage]
                || [conv.getReceiver isEqualToString:CNJoinFeatureGroupInvitation]
                || [conv.getReceiver isEqualToString:CNWithSubscri]
                || [conv.getReceiver isEqualToString:CNWithNews]
                || [conv.getReceiver isEqualToString:CNWithLive]
                || [conv.getReceiver isEqualToString:CNWithVideo]
                || [conv.getReceiver isEqualToString:CNWithRepastPay]
                || [conv.getReceiver isEqualToString:CNWithReceipt]
                || [conv.getReceiver isEqualToString:CNWithRepastVerify])
            {
                NSLog(@"已知后台消息");
            }
            else
            {
                NSLog(@"未知后台消息不添加到会话列表");
                break ;
            }
        }
        
        BOOL isSystemMsg = [conv getType] == TIM_SYSTEM;
        if (isSystemMsg)
        {
            /**处理收到的IM系统消息*/
            BOOL isContinue = [self handleSysMsg:msg];
            if (isContinue) {
                continue ;
            }
        }else{
            /**对非系统消息进行手机震动提示*/
            [self playMsgSound:conv];
        }
    /**收到新消息后,先从聊天会话列表里找是否存在这个会话,如果存在,找个这个会话并更新。如果不存在,说明是一个新的会话,把这个会话加入到会话列表中*/
        
        // updateSucc 为yes就说明找到了要刷新的会话
        BOOL updateSucc = [self findConvFromConversationList:conv isSystemMsg:isSystemMsg imamsg:imamsg];
        
        if (!updateSucc )
        {
            //没找到说明是新的会话
            BOOL isBreak = [self newConv:conv isSystemMsg:isSystemMsg imamsg:imamsg];
            if (isBreak)break;
        }
    }
}

/// 处理所有收到的自定义消息,返回bool值,用来告诉 for 循环是否执行break, YES:break
/// @param imamsg 收到的消息
/// @param conv   消息的会话
- (BOOL)handleCustomMsg:(IMAMsg *)imamsg conv:(TIMConversation *)conv
{
    BOOL isBreak = NO;
    TIMCustomElem *roomElem = (TIMCustomElem *)[imamsg.msg getElem:0];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:roomElem.data
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:&err];
    NSLog(@"所有自定义消息 ==  %@",dic);
    if([[dic objectForKey:@"type"] integerValue] == CustomMsgTypeLiveStatus)
    {
        NSLog(@"dic直播状态 ==  %@",dic);
        // 收到 直播状态消息
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_LiveStatusNotification object:dic];
        isBreak = YES ;
    }
    else if ([[dic objectForKey:@"type"] integerValue] == CustomMsgTypeLiveOneLineCount)
    {
         NSLog(@"dic直播聊天室人数 ==  %@",dic);
        // 聊天室人数变化
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_LiveOnlineCountNotification object:dic];
        
        isBreak = YES;
    }
    else if ([[dic objectForKey:@"type"] integerValue] == CustomMsgTypeBlackStatusChange)
    {
        //添加或移除黑名单消息
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_BlackListNotification object:dic userInfo:@{@"notifyBlackListData" : dic[@"notifyBlackListData"]}];
        
        isBreak = YES;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeSenderInvitationReceiver)
    {
        //发送方向接收方发起音视频邀请
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_SenderInvitationReceiver object:nil userInfo:dic];
        isBreak = YES ;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeDeleteGroupMember)
    {
        NSLog(@"有群成员退出 %@",dic);
        NSDictionary *deleteGroupMemberData = [dic objectForKey:@"deleteGroupMemberData"];
        IMAGroup *temp = [[IMAGroup alloc] initWith:[deleteGroupMemberData objectForKey:@"groupId"]];
        IMAGroup *group = (IMAGroup *)[[IMAPlatform sharedInstance].contactMgr isContainUser:temp];
        group.groupInfo.memberNum -= 1;
        [[IMAPlatform sharedInstance].contactMgr upadateLocalGroupInfo:[deleteGroupMemberData objectForKey:@"groupId"] complete:^(BOOL succ) {
            if (succ) {
                [[CNGroupListAvaterUtil sharedCNGroupListAvaterUtil] requestTIMGroupInfoForChangeType:CNLiveGroupMemberChangeTypeReduceMember GroupID:[deleteGroupMemberData objectForKey:@"groupId"]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
                {
                    [[CNGroupListAvaterUtil sharedCNGroupListAvaterUtil] requestLocalGroupIconViewWithGroupId:[deleteGroupMemberData objectForKey:@"groupId"] CompleterBlock:^(UIImage *avater)
                    {
                        for (IMAConversation *conv in [IMAPlatform sharedInstance].conversationMgr.conversationList.safeArray)
                        {
                            if ([[conv receiver] isEqualToString:[deleteGroupMemberData objectForKey:@"groupId"]])
                            {
                                conv.groupAvator = avater;
                                break ;
                            }
                        }
                        dispatch_async(dispatch_get_main_queue(), ^
                        {
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"onNewMessage" object:nil];
                        });
                    }];
                });
            }
        }];
                        
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_GroupMemberDeleteNotification object:[dic objectForKey:@"deleteGroupMemberData"] userInfo:dic];
        
        /**标识是否是管理员退出了群聊*/
        BOOL isExitAdmin = NO;
        /**退出成员的id*/
        NSString *memberId = deleteGroupMemberData[@"toSid"];
        
        for (int i = 0; i < group.adminArray.count; i++) {
            TIMGroupMemberInfo *adminMemberInfo = group.adminArray[i];
            if ([memberId isEqualToString:adminMemberInfo.member]) {
                //说明退出群聊的是管理员
                isExitAdmin = YES;
                [group.adminArray removeObject:adminMemberInfo];
                break;
            }
        }
        
        if (isExitAdmin) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_updataAdmin object:nil];
            //同步数据库数据
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSMutableArray *array = [[NSMutableArray alloc] init];
                //把所有管理员id保存到h数据库
                for (TIMGroupMemberInfo *memberInfo in group.adminArray) {
                    [array addObject:memberInfo.member];
                }
                CNAdiminFMDBManager *manger = [CNAdiminFMDBManager manager];
                if ([manger searchById:group.groupId]) {
                    //数据库存在去更新
                    CNAdiminObject *obj = [[CNAdiminObject alloc] initWith:group.groupId adiminArray:array];
                    [manger updateObject:obj];
                }
                else
                {
                    //数据库不存在 插入新数据
                    CNAdiminObject *obj = [[CNAdiminObject alloc] initWith:group.groupId adiminArray:array];
                    [manger insterObject:obj];
                }
            });
        }
        
        isBreak = YES;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeOrderStatus)
    {
        if ([conv getType] == TIM_GROUP) {
            [self getGroupInfo:[conv getReceiver]];
        }
        
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeBind)
    {
        //绑定情亲音响
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_Bind object:dic];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeUnbind)
    {
        //解绑情亲音响
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_UnBind object:dic];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeDeleteDevice)
    {
        //解绑设备
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_DeleteDevice object:dic];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeTopicTip)
    {
        //新话题提醒
        NSDictionary *topicData = [dic objectForKey:@"topicData"];
        NSDictionary *hasNewTopic = @{@"homeId" : topicData[@"homeId"] ? topicData[@"homeId"] : @"" ,
                                      @"ts" : topicData[@"ts"] ? topicData[@"ts"] : @"",
                                      @"isRead" : @"0"
        };
        [[NSUserDefaults standardUserDefaults] setObject:hasNewTopic forKey:CNHasNewTopicTip];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [IMAPlatform sharedInstance].unReadTopicMsg = imamsg.msg;
        
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeMutualTopic_CommentMsg)
    {
        //互助话题 有新的评论或回复消息
        NSDictionary *topicData = [dic objectForKey:@"topicData"];
        NSDictionary *hasNewTopic = @{@"homeId" : topicData[@"homeId"] ? topicData[@"homeId"] : @"" ,
                                      @"ts" : topicData[@"ts"] ? topicData[@"ts"] : @"",
                                      @"isRead" : @"0"
        };
        [[NSUserDefaults standardUserDefaults] setObject:hasNewTopic forKey:CNMutualTopicCommentMsg];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_MutualTopicHasNewMsg object:nil];
        
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeMutualTopic_SysMsg)
    {
        //互助话题 有新的系统消息
        NSDictionary *topicData = [dic objectForKey:@"topicData"];
        NSDictionary *hasNewTopic = @{@"homeId" : topicData[@"homeId"] ? topicData[@"homeId"] : @"" ,
                                      @"ts" : topicData[@"ts"] ? topicData[@"ts"] : @"",
                                      @"isRead" : @"0"
        };
        [[NSUserDefaults standardUserDefaults] setObject:hasNewTopic forKey:CNMutualTopicSysMsg];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_MutualTopicHasNewMsg object:nil];
        
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeMutualTopic_AuditMsg)
    {
        //互助话题 有新的 话题审核 消息
        NSDictionary *topicData = [dic objectForKey:@"topicData"];
        NSDictionary *hasNewTopic = @{@"homeId" : topicData[@"homeId"] ? topicData[@"homeId"] : @"" ,
                                      @"ts" : topicData[@"ts"] ? topicData[@"ts"] : @"",
                                      @"isRead" : @"0"
        };
        [[NSUserDefaults standardUserDefaults] setObject:hasNewTopic forKey:CNMutualTopicAuditMsg];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_MutualTopicHasNewMsg object:nil];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeLtyRegistrationSuccess)
    {
        NSDictionary *ltyRegistrationSuccessData = [dic objectForKey:@"ltyRegistrationSuccessData"];
        //领头雁报名成功,更新昵称
        [[IMAPlatform sharedInstance].host asyncProfile];
        NSString *nickname = [ltyRegistrationSuccessData objectForKey:@"nickname"];
        if (![NSString isEmpty:nickname])CNUserShareModel.nickname = nickname;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeFamilyGroupCoupon)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_FamilyGroupCoupon object:dic[@"alertMsg"]];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeAite)
    {
        NSDictionary *groupAitDic = dic[@"groupAit"];
        if ([groupAitDic.allKeys containsObject:@"isAitAll"])
        {
            if (groupAitDic[@"isAitAll"])
            {
                 TIMCustomElem *elem = (TIMCustomElem *)[imamsg.msg getElem:0];
                [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_UpdateGroupInfoNotification object:elem.desc userInfo:dic];
            }
        }
        else if ([dic.allKeys containsObject:@"isAitAll"])
        {
            //兼容老版本
            if (dic[@"isAitAll"])
            {
                TIMCustomElem *elem = (TIMCustomElem *)[imamsg.msg getElem:0];
                [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_UpdateGroupInfoNotification object:elem.desc userInfo:dic];
            }
        }
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeGroupPaySuccess) {
        NSLog(@"群组收款支付成功%@",dic);
        [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveContentSweepPaymentNotification object:@{@"payType":@"1",@"payInfo":dic}];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeOrderStatus) {
        NSLog(@"订单支付显示%@",dic);
        [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveContentSweepPaymentNotification object:@{@"payType":@"2",@"payInfo":dic}];
    }
    else if ([dic[@"type"] integerValue] == 5001)
    {
        //扫描支付消息
        [[NSNotificationCenter defaultCenter] postNotificationName:CNLiveContentSweepPaymentNotification object:@{@"payType":@"0",@"payInfo":dic}];
        isBreak = YES;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeRefreshFriendCircle) {
        //刷新朋友圈
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_FriendCircleNotification object:nil userInfo:dic];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeFriendSendSucc) {
        //朋友圈上传发布成功
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_FriendCircleSendNotification object:nil userInfo:dic];
        isBreak = YES;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeShareGift)
    {
        NSDictionary *giftInfoData = dic[@"giftInfoData"];
        if ([giftInfoData[@"toType"] integerValue] == 2 && [giftInfoData[@"giftType"] integerValue] == 1) {
            //对方收礼成功,更新待补运费数
            [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_UpdateUnPayFreightGiftOrderNum object:nil userInfo:dic];
        }
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeUpdateUnpayFreightGiftOrderNum)
    {
        //更新待补运费数
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_UpdateUnPayFreightGiftOrderNum object:nil userInfo:dic];
        isBreak = YES;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeShareGift)
    {
        NSDictionary *giftInfoData = [dic objectForKey:@"giftInfoData"];
        if ([giftInfoData[@"toType"] intValue] == 2  && [giftInfoData[@"giftType"] intValue] == 1) {
            //对方已收礼
            [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_ReceivingGiftsNotification object:nil userInfo:dic];
        }
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeTransferExpired)
    {
        NSDictionary *transferBalanceExpiredData = [dic objectForKey:@"transferBalanceExpiredData"];
       
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CNTransferBalanceExpiredSuccessNotification" object:nil userInfo:transferBalanceExpiredData];
        
        /**把该未领取余额记录从 未领取缓存中清除,如果该会话对应的表中没有待领取的余额,该会话首页最后一条消息【转余额】红色提醒就会被清除*/
        [[CNTransferBalanceUnreceivedCache cache] removeOneElement:@{@"sourceId" : transferBalanceExpiredData[@"sourceId"]} forKey:[NSString stringWithFormat:@"key_%@_%@",CNUserShareModel.uid,[conv getReceiver]]];
        isBreak = YES;

    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeTransferBalance)
    {
        NSDictionary *transferBalanceData = [dic objectForKey:@"transferBalanceData"];
        NSString *type = [NSString stringWithFormat:@"%@",transferBalanceData[@"type"]];
        if ([transferBalanceData[@"toId"] isEqualToString:CNUserShareModel.uid] && [type isEqualToString:@"1"]) {
            //收款方,待领取状态,设置会话列表最后一条消息提示【转余额】
            [[CNTransferBalanceUnreceivedCache cache] addOneElement:transferBalanceData forKey:[NSString stringWithFormat:@"key_%@_%@",CNUserShareModel.uid,[conv getReceiver]]];
        }
    }
    else if([dic[@"type"] integerValue] == CustomMsgTypePhotoFixSuccess)
    {
        //照片修复成功
        NSDictionary *topicData = dic[@"topicData"];
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_PhotoFixSuccessNotification object:nil userInfo:topicData];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeApplyForRefund) {
        //商家版申请退款消息
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_ApplyForRefundNotification object:nil userInfo:dic];
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeCommunityPaySuccess)
    {
        //社区支付成功
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_CommunityPaySuccessNotification object:nil userInfo:dic];
        isBreak = YES;
    }
    else if ([dic[@"type"] integerValue] == CustomMsgTypeScanPaySuccess)
    {
        //扫码支付成功
        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_ScanPaySuccessNotification object:nil userInfo:dic];
        isBreak = YES;
    }
    return isBreak;
}

/// 处理IM发送的系统消息,返回bool值,用来判断外部for循环是否执行 continue 语句,Yes执行continue, NO 不执行
/// @param msg IM消息
- (BOOL)handleSysMsg:(TIMMessage *)msg
{
    BOOL isAddGroupReq = NO;
    BOOL isAddFriendReq = NO;
    BOOL isContinue = NO;
    int elemCount = [msg elemCount];
    for (int i = 0; i < elemCount; i++)
    {
        TIMElem* elem = [msg getElem:i];
        if ([elem isKindOfClass:[TIMGroupSystemElem class]])
        {
            TIMGroupSystemElem *gse = (TIMGroupSystemElem *)elem;
            if (gse.type == TIM_GROUP_SYSTEM_ADD_GROUP_REQUEST_TYPE || gse.type == TIM_GROUP_SYSTEM_INVITED_TO_GROUP_TYPE || gse.type == TIM_GROUP_SYSTEM_INVITE_TO_GROUP_REQUEST_TYPE)
            {
                isContinue = NO;
                isAddGroupReq = YES;
            }else if (gse.type == TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE)
            {
                
                IMAGroup *group =[[IMAPlatform sharedInstance].contactMgr getUserByGroupId:gse.group];
                [[IMAPlatform sharedInstance].contactMgr removeUser:group];
                //删除本地群组信息
                [[IMAPlatform sharedInstance].contactMgr deleteLocalGroupInfo:gse.group];
                //群被解散
                [[CNGroupListAvaterUtil sharedCNGroupListAvaterUtil] requestTIMGroupInfoForChangeType:CNLiveGroupMemberChangeTypeExitGroup GroupID:gse.group];
                [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_QuitedGroupNotification object:nil];
            }
            else if (gse.type == TIM_GROUP_SYSTEM_KICK_OFF_FROM_GROUP_TYPE)
            {
                //被管理员移除群
                //删除本地群组信息
                [[IMAPlatform sharedInstance].contactMgr deleteLocalGroupInfo:gse.group];
               
                IMAGroup *group =[[IMAPlatform sharedInstance].contactMgr getUserByGroupId:gse.group];
                [[IMAPlatform sharedInstance].contactMgr removeUser:group];
                //更新本地群组头像
                [[CNGroupListAvaterUtil sharedCNGroupListAvaterUtil] requestTIMGroupInfoForChangeType:CNLiveGroupMemberChangeTypeExitGroup GroupID:gse.group];
                [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_QuitedGroupNotification object:gse.group];
            }
            else if (gse.type == TIM_GROUP_SYSTEM_QUIT_GROUP_TYPE)
            {
                //删除本地群组信息
                [[IMAPlatform sharedInstance].contactMgr deleteLocalGroupInfo:gse.group];
                //主动退群
                [[CNGroupListAvaterUtil sharedCNGroupListAvaterUtil] requestTIMGroupInfoForChangeType:CNLiveGroupMemberChangeTypeExitGroup GroupID:gse.group];
               
            }
            else if (gse.type == TIM_GROUP_SYSTEM_CREATE_GROUP_TYPE)
            {
                //自己创建新群
                //把新建的群缓存到本地
                [[IMAPlatform sharedInstance].contactMgr addLocalGroupInfo:gse.group];
                //把新建的群缓存到APP内存
                [self getGroupInfo:gse.group];
            }
            
        }
        else if ([elem isKindOfClass:[TIMSNSSystemElem class]])
        {
            TIM_SNS_SYSTEM_TYPE type = ((TIMSNSSystemElem *)elem).type;
            if (type == TIM_SNS_SYSTEM_ADD_FRIEND_REQ) {    //增加好友申请,不在会话列表显示,以小红点的方式显示
                if (!msg.isSelf)
                {
                    isContinue = NO;
                    isAddFriendReq = YES;
                }
            }
        }else if ([elem isKindOfClass:[TIMProfileSystemElem class]]) {
            isContinue = NO;
            isAddFriendReq = YES;
        }
       
    }
    return isContinue;
}

/// 对收到的单聊消息或群聊消息进行 手机震动提醒
/// @param conv IM会话
- (void)playMsgSound:(TIMConversation *)conv
{
    NSLog(@"systemSoundID_Vibrate");
    switch ([conv getType]) {
        case TIM_C2C:
        {
            if ([[conv getReceiver] isEqualToString:CNDarenHaoUserId])
            {
                
            }else if ([[conv getReceiver] isEqualToString:CNLifeHaoUserId])
            {
            }else if ([[conv getReceiver] isEqualToString:CNFirendMomentUserId])
            {
            }else
            {
                UIApplicationState state = [UIApplication sharedApplication].applicationState;
                if (state == UIApplicationStateActive){
                    NSLog(@"前台");
                    BOOL isLivePlaying = [BHConfig boolValue:@"CNLivePlaying"];
                    if (!isLivePlaying) {
                        if (@available(iOS 9.0, *)) {//应用内收到消息震动
                            AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, ^{
                            });
                        }
                    }
                }

            }
        }
            break;
        case TIM_GROUP:
        {
            IMAGroup *group = (IMAGroup *)[[IMAPlatform sharedInstance].contactMgr getUserByGroupId:[conv getReceiver]];
            if ([group.groupInfo.groupType isEqualToString:@"Private"] || [group.groupInfo.groupType isEqualToString:@"Public"]) {
                //私有群 和 公开群,消息未打扰时开启新消息震动
                if ([[group receiveMessageOpt] isEqualToString:@"接收消息"]) {
                    UIApplicationState state = [UIApplication sharedApplication].applicationState;
                    if (state == UIApplicationStateActive){
                        NSLog(@"前台");
                        BOOL isLivePlaying = [BHConfig boolValue:@"CNLivePlaying"];
                        if (!isLivePlaying) {
                            if (@available(iOS 9.0, *)) {//应用内收到消息震动
                                AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, ^{
                                });
                            }
                        }
                    }
                    
                }
            }
            else if ([group.groupInfo.groupType isEqualToString:@"ChatRoom"])
            {
                //普通聊天室
            }
            else if ([group.groupInfo.groupType isEqualToString:@"AVChatRoom"])
            {
                //直播聊天室
            }
            
        }
            break;
        default:
            break;
    }
}

/// 从当前会话列表找是否存在新消息的会话,如果找到了,就返回yes,否则返回No
/// @param conv 要找的会话
/// @param isSystemMsg 新消息是否是系统消息
/// @param imamsg 收到的新消息 imamsg是对TIMessage 对象进行了一层封装
- (BOOL)findConvFromConversationList:(TIMConversation *)conv isSystemMsg:(BOOL)isSystemMsg imamsg:(IMAMsg *)imamsg
{
    /**updateSucc 为Yes 代表找到了该会话 */
    BOOL updateSucc = NO;
    
    /**获取原始的IM消息*/
    TIMMessage *msg = imamsg.msg;
    
    for (int i = 0; i < [_conversationList count]; i++)
    {
        IMAConversation *imaconv = [_conversationList objectAtIndex:i];
        NSString *imaconvReceiver = [imaconv receiver];
        NSLog(@"imaconvReceiver ===  %@\n  [conv getReceiver] == %@\n IMACustomConversation == %@\n",imaconvReceiver,[conv getReceiver],[IMACustomConversation getCustomConversationID:imamsg]);
        if (imaconv.type == [conv getType] && ([imaconvReceiver isEqualToString:[conv getReceiver]] || [imaconvReceiver isEqualToString:[IMACustomConversation getCustomConversationID:imamsg]]))
        {
            if ([imaconv.receiver isEqualToString:_chattingConversation.receiver])
            {
                //如果是c2c会话,则更新“对方正在输入...”状态
                BOOL isInputStatus = NO;
                /*注销下面代码, 不对消息进行是否是自己发送进行判断, 因为后台有时会以自己的身份进行发送消息*/
                //                    if (!msg.isSelf || imamsg.type == EIMAMSG_GroupPaySuccess || imamsg.type == EIMAMSG_ShareGift)
                //                    {
                if ([_chattingConversation imaType] == TIM_C2C)
                {
                    int elemCount = [imamsg.msg elemCount];
                    for (int i = 0; i < elemCount; i++)
                    {
                        TIMElem* elem = [msg getElem:i];
                        
                        //自定义消息的判断,
                        CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                        
                        if (elemCmd)
                        {
                            isInputStatus = YES;
//                            [[NSNotificationCenter defaultCenter] postNotificationName:kUserInputStatus object:elemCmd];
                        }
                    }
                }
                
                if (!isInputStatus)
                {
                    [imaconv setReadAllMsg];
                    if ([[conv getReceiver] hasPrefix:@"AVCR"])
                    {
                        break ;
                    }
                    [self updateOnLastMessageChanged:imaconv];
                    [_chattingConversation onReceiveNewMessage:imamsg];
                    imaconv.lastMessage = imamsg;
                }
            }
            else
            {
                //不是正在聊的消息
                TIMElem* elem = [msg getElem:0];
                CustomElemCmd *elemCmd = [self isOnlineMsg:elem];
                if (!elemCmd)
                {//非自定义消息
                    imaconv.lastMessage = imamsg;
                    if (isSystemMsg)
                    {
                        __weak IMAConversationManager *ws = self;
                        // 系统消息
                        IMACustomConversation *customConv = (IMACustomConversation *)imaconv;
                        [customConv saveMessage:imamsg succ:^(int newUnRead) {
                            ws.unReadMessageCount += newUnRead;
                            [ws updateOnChat:imaconv moveFromIndex:i];
                        }];
                    }
                    else
                    {
                        //如果是自己发出去的消息,一定是已读(这里判断主要是用在多终端登录的情况下)
                        if (![imamsg isMineMsg])
                        {
                            if ([imaconv.receiver hasPrefix:@"sys_"]) {
                                switch ([IMAPlatform sharedInstance].platformType) {
                                    case IMPlatformTypeB:
                                    {
                                        if (![imaconv.receiver isEqualToString:CNWithSystemMessage])
                                        {
                                            self.unReadMessageCount++;
                                        }
                                    }
                                        break;
                                    case IMPlatformTypeC:
                                    {
                                        //自己后台发的系统通知未读数不加
                                    }
                                        break;
                                    default:
                                        break;
                                }
                            }
                            else
                            {
                                if (imaconv.type == TIM_GROUP)
                                {
                                    if (![NSString isEmpty:imaconv.receiveMessageOpt])
                                    {
                                        //先取会话的receiveMessageOpt进行判断
                                        if ([imaconv.receiveMessageOpt isEqualToString:@"接收消息"])
                                        {
                                            TIMElem* elem = [imamsg.msg getElem:0];
                                            if ([elem isKindOfClass:[TIMGroupSystemElem class]])
                                            {
                                                TIMGroupSystemElem *gse = (TIMGroupSystemElem *)elem;
                                                if (gse.type != TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE && gse.type != TIM_GROUP_SYSTEM_KICK_OFF_FROM_GROUP_TYPE) {
                                                    self.unReadMessageCount++;
                                                    
                                                }
                                            }
                                            else
                                            {
                                                self.unReadMessageCount++;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        IMAGroup *group = (IMAGroup *)[[IMAPlatform sharedInstance].contactMgr getUserByGroupId:imaconv.receiver];
                                        if ([[group receiveMessageOpt] isEqualToString:@"接收消息"])
                                        {
                                            TIMElem* elem = [imamsg.msg getElem:0];
                                            if ([elem isKindOfClass:[TIMGroupSystemElem class]])
                                            {
                                                TIMGroupSystemElem *gse = (TIMGroupSystemElem *)elem;
                                                if (gse.type != TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE && gse.type != TIM_GROUP_SYSTEM_KICK_OFF_FROM_GROUP_TYPE) {
                                                    self.unReadMessageCount++;
                                                }
                                            }
                                            else
                                            {
                                                self.unReadMessageCount++;
                                            }
                                        }
                                    }
                                }
                                else
                                    self.unReadMessageCount++;
                            }
                        }
                        if ([[imaconv receiver] isEqualToString:CNFirendMomentUserId])
                        {
                            [self updateOnChat:imaconv moveFromIndex:0 toIndex:0];
                        }else
                        {
                            [self updateOnChat:imaconv moveFromIndex:i];
                        }
                    }
                }
            }
            updateSucc = YES;
            break;
        }
    }
    
    /**处理会话列表上没有此会话,但是用户进入了聊天界面*/
    if (!updateSucc && _chattingConversation && !isSystemMsg && [_chattingConversation.receiver isEqualToString:conv.getReceiver]) {
        [_chattingConversation onReceiveNewMessage:imamsg];
    }
    
    return updateSucc;
}

/// 这个conv是个新会话,不存在于首页会话列表中,进行相关逻辑处理。
/// 该方法返回bool值,告诉外部for循环是否结束本次循环,yes 为结束
/// @param conv 新的会话
/// @param isSystemMsg 是否是IM系统消息
/// @param imamsg 收到的新消息
- (BOOL)newConv:(TIMConversation *)conv isSystemMsg:(BOOL)isSystemMsg imamsg:(IMAMsg *)imamsg
{
    BOOL isBreak = NO;
    if (isSystemMsg)
    {
        NSString *receiverid = [IMACustomConversation getCustomConversationID:imamsg];
        
        //zl__新朋友会话列表不提示
        if (![receiverid isEqualToString:@"新朋友"] && ![receiverid isEqualToString:@"群系统消息"] )
        {
            TIMConversation *imconv = [[TIMManager sharedInstance] getConversation:TIM_SYSTEM receiver:receiverid];
            [imconv setReadMessage:nil succ:nil fail:nil];
            // 说明会话列表中没有该会话,新生建会话,并更新到
            IMACustomConversation *temp = [[IMACustomConversation alloc] initWith:imconv andMsg:imamsg];
            if (temp)
            {
                __weak IMAConversationManager *ws = self;
                [temp saveMessage:imamsg succ:^(int newUnRead)
                {
                    ws.unReadMessageCount += newUnRead;
                }];
                [_conversationList insertObject:temp atIndex:[self insertPosition]];
                [self updateOnNewConversation:temp];
            }
        }
        
    }
    else
    {
        
        // 说明会话列表中没有该会话,新生建会话,并更新到
        __block IMAConversation *temp = [[IMAConversation alloc] initWith:conv];
        NSString *groupIds = [temp receiver];
        //zx 被邀请进入新群,并且群有新消息,保存群成员列表信息到本地
        if ([temp imaType] == IMA_Group) {
            if([groupIds isEqualToString:@""])
            {
                /**群id为空,直接结束本次循环*/
                isBreak = YES;
                return isBreak;
            }
        }
        temp.lastMessage = imamsg;
        if ([[conv getReceiver] hasPrefix:@"AVCR"])
        {
            /**会话为聊天室,直接结束本次循环*/
            isBreak = YES;
            return isBreak;
        }
        if ([[conv getReceiver] isEqualToString:CNWithSubscri] || [[conv getReceiver] isEqualToString:CNFirendMomentUserId] || [[conv getReceiver] isEqualToString:CNDarenHaoUserId])
        {
            //订阅号 和 朋友圈 不添加到会话列表里
            [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_UpdateHomePageHeaderNotification object:[conv getReceiver]];
            isBreak = YES;
            return isBreak;
        }
        
        [_conversationList insertObject:temp atIndex:[self insertPosition]];
        
        /**非后台创建的公共号,未读消息数才 + 1 */
        if (![temp.receiver hasPrefix:@"sys_"])self.unReadMessageCount++;
        
        [self updateOnNewConversation:temp];
    }
    
    return isBreak;
}
/// 获取群详情
/// @param groupId 群ID
- (void)getGroupInfo:(NSString *)groupId
{
    [[IMAPlatform sharedInstance].contactMgr syncGroupInfojoinGroup:groupId succ:^(TIMGroupInfo *groupInfo, BOOL succ) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            IMAGroup *group = (IMAGroup *) [[IMAPlatform sharedInstance].contactMgr getUserByGroupId:groupId];
            if (!group && groupInfo)
            {
                IMAGroup *gr = [[IMAGroup alloc] initWithInfo:groupInfo callBlock:nil];
                [[IMAPlatform sharedInstance].contactMgr onAddGroup:gr];
                IMAConversation *gc = [self queryConversationWith:gr];
                if (gc)
                {
                    //重新设置一下lastMessage就可以更新整个会话了(lastmessage有kvo监听)
                    gc.lastMessage = gc.lastMessage;
                    
                }
            }
            else if(groupInfo)
            {
                //更新禁言状态
                group.groupInfo.allShutup = groupInfo.allShutup;
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_UpdateAllShutupNotification object:group];
            }
        });
    }];
}
- (CustomElemCmd *)isOnlineMsg:(TIMElem *) elem
{
    if ([elem isKindOfClass:[TIMCustomElem class]])
    {
        CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
        if (elemCmd)
        {
            return elemCmd;
        }
    }
    return nil;
}

- (void)onAddFreindRequest:(TIMSNSSystemElem *)elem
{
}

- (void)getExceptSysUnReadCount:(void (^)(NSInteger))complete
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __block NSInteger unReadCount = 0;
        NSArray *conversationArray = _conversationList.safeArray.copy;
        for (int i = 0; i < conversationArray.count; i ++) {
            IMAConversation *conv = [conversationArray objectAtIndex:i];
            NSString *receiver = [conv receiver];
            if (receiver.length > 4) {
                NSString *prex = [receiver substringToIndex:4];
                if ([prex isEqualToString:@"sys_"]) {
                    //是系统大号,达人号...
                    if ([receiver isEqualToString:CNDarenHaoUserId])
                    {//达人号
                        
                    }else if ([receiver isEqualToString:CNLifeHaoUserId])
                    {//生活号
                        
                    }else if ([receiver isEqualToString:CNFirendMomentUserId])
                    {//朋友圈
                        
                    }else
                    {
                        
                    }
                }else
                {//其他消息
                    if ([conv imaType] == TIM_GROUP) {
                        if (![NSString isEmpty:conv.receiveMessageOpt]) {
                            //先取会话的receiveMessageOpt进行判断
                           if ([conv.receiveMessageOpt isEqualToString:@"接收消息"]) {
                                unReadCount += [conv unReadCount];
                            }
                        }
                        else
                        {
                            IMAGroup *group = (IMAGroup *)[[IMAPlatform sharedInstance].contactMgr getUserByGroupId:receiver];
                            if ([[group receiveMessageOpt] isEqualToString:@"接收消息"]) {
                                unReadCount += [conv unReadCount];
                            }
                        }
                           
                    }
                    else
                        unReadCount += [conv unReadCount];
                }
            }
            else
            {//其他消息
                unReadCount += [conv unReadCount];
            }
           
        }
        [IMAPlatform sharedInstance].conversationMgr.unReadMessageCount = unReadCount;
        if (complete) {
            complete(unReadCount);
        }
    });
    
}
- (IMAConversation *)getChattingConversation
{
    return _chattingConversation;
}
- (UINavigationController *)navigationViewController
{
    
    if ([[UIApplication sharedApplication].keyWindow.rootViewController isKindOfClass:[UINavigationController class]])
    {
        return (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    else if ([[UIApplication sharedApplication].keyWindow.rootViewController isKindOfClass:[UITabBarController class]])
    {
        UIViewController *selectVc = [((UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController) selectedViewController];
        if ([selectVc isKindOfClass:[UINavigationController class]])
        {
            return (UINavigationController *)selectVc;
        }
    }
    return nil;
}
@end


@implementation IMAConversationManager (Protected)

- (void)onConnect
{
    // 删除
    IMAConnectConversation *conv = [[IMAConnectConversation alloc] init];
    NSInteger index = [_conversationList indexOfObject:conv];
    if (index >= 0 && index < [_conversationList count])
    {
        [_conversationList removeObject:conv];
        [self updateOnDelete:conv atIndex:index];
    }
}
- (void)onDisConnect
{
    
    // 插入一个网络断开的fake conversation
    IMAConnectConversation *conv = [[IMAConnectConversation alloc] init];
    NSInteger index = [_conversationList indexOfObject:conv];
    
    if (!(index >= 0 && index < [_conversationList count]))
    {
        [_conversationList insertObject:conv atIndex:0];
        [self updateDisConnectedChanged:conv];
    }
}

- (void)onPlayMusicConnect:(NSInteger)status CNLiveAlbumAudioListModel:(NSDictionary *)audioModelDic
{
    self.audioModelDic = audioModelDic;
    BOOL isDisconnect = NO, _isPlayMusic = NO;;
    for (IMAConversation *con in _conversationList.safeArray) {
        if ([con isKindOfClass:[IMAConnectConversation class]]) {
            isDisconnect = YES;
            continue;
        }
        if ([con isKindOfClass:[IMAPlayMusicConversation class]]) {
            _isPlayMusic = YES;
            continue;
        }
    }
    _isDisconnect = isDisconnect;
    __weak typeof(self) weakSelf = self;
    if (status == 1) {
        self.isPlay = YES;
        IMAPlayMusicConversation *tempCon = [[IMAPlayMusicConversation alloc] init];
        tempCon.receiver = [NSString stringWithFormat:@"正在播放  %@",audioModelDic[@"title"]];
        if (!_isPlayMusic) [_conversationList insertObject:tempCon atIndex:!isDisconnect ? 0 : 1];
        [self updateOnNewConversation:tempCon];
    }else{
        self.isPlay = NO;
        [_conversationList.safeArray enumerateObjectsUsingBlock:^(IMAConversation * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[IMAPlayMusicConversation class]]) {
                [_conversationList removeObject:obj];
                [weakSelf updateOnDelete:obj atIndex:idx];
                *stop = YES;
            }
        }];
    }
    
}


- (void)updateOnChat:(IMAConversation *)conv moveFromIndex:(NSUInteger)index
{
    NSInteger toindex = [self insertPosition];
    NSString *sender = [conv receiver];
//    if ([sender isEqualToString:CNDarenHaoUserId])
//    {
//        toindex = 0;
//    }else
        if ([sender isEqualToString:CNFirendMomentUserId])
    {
        toindex = 0;
    }
//    else if ([sender isEqualToString:CNLifeHaoUserId])
//    {
//        toindex = 2;
//    }
    
    [_conversationList removeObjectAtIndex:index];
    
    [_conversationList insertObject:conv atIndex:toindex];

    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_BecomeActiveTop];
    item.conversation = conv;
    item.index = index;
    item.toIndex = toindex;
    
    [self updateIconWithConversationByConv:item.conversation item:item];

}

- (void)updateOnDelete:(IMAConversation *)conv atIndex:(NSUInteger)index
{
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_DeleteConversation];
    item.conversation = conv;
    item.index = index;
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
}

- (void)updateOnAsyncLoadContactComplete
{
    // 通知更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_SyncLocalConversation];
    [self updateIconWithConversationByConv:item.conversation item:item];

}

- (void)updateOnLocalMsgComplete
{
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_SyncLocalConversation];
    [self updateIconWithConversationByConv:item.conversation item:item];
}


- (void)updateOnLastMessageChanged:(IMAConversation *)conv
{
//    if ([_chattingConversation isEqual:conv])
//    {
        NSInteger index = [_conversationList indexOfObject:conv];
        NSInteger toindex = [self insertPosition];
        if (index == _toIndex) {
            // 防止获取的 toindex 越界
            toindex = _toIndex;
        }
        if (index > 0 && index < [_conversationList count])
        {
            [_conversationList removeObject:conv];
            [_conversationList insertObject:conv atIndex:toindex];
            [self updateOnChat:conv moveFromIndex:index toIndex:toindex];
        }
        else if (index < 0 || index > [_conversationList count])
        {
            if (toindex > _conversationList.count ) {
                //解决 index 3 beyond bounds [0 .. 1]
                toindex = _conversationList.count;
            }
            [_conversationList insertObject:conv atIndex:[self insertPosition]];
            [self updateOnNewConversation:conv];
        }
        else
        {
            // index == 0 不作处理
        }
//    }
}

- (void)updateOnChat:(IMAConversation *)conv moveFromIndex:(NSUInteger)index toIndex:(NSInteger)toIdx
{
    
    NSInteger toindex = toIdx;
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_BecomeActiveTop];
    item.conversation = conv;
    item.index = index;
    item.toIndex = toindex;

    //更新会话并更新头像
    [self updateIconWithConversationByConv:conv item:item];
}

- (void)updateOnNewConversation:(IMAConversation *)conv
{
    // 更新界面
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:_conversationList.count<=3 ? EIMAConversation_SyncLocalConversation : EIMAConversation_NewConversation];
    item.conversation = conv;
    
    item.index = [_conversationList indexOfObject:conv];
    //更新会话并更新头像
    [self updateIconWithConversationByConv:conv item:item];
    
}
- (void)updateDisConnectedChanged:(IMAConversation *)conv;
{
    
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_DisConnected];
    item.conversation = conv;
    item.index = [_conversationList indexOfObject:conv];
    //更新会话并更新头像
    [self updateIconWithConversationByConv:conv item:item];
}
- (void)updateOnConversationChanged:(IMAConversation *)conv
{
    IMAConversationChangedNotifyItem *item = [[IMAConversationChangedNotifyItem alloc] initWith:EIMAConversation_ConversationChanged];
    item.conversation = conv;
    item.index = [_conversationList indexOfObject:conv];
    
    [self updateIconWithConversationByConv:item.conversation item:item];

}

#pragma mark -
#pragma mark - zl--判断是否为好友,如果是好友直接更新会话列表,否则重新获取用户信息,返回结果后更新会话列表
- (void)updateIconWithConversationByConv:(IMAConversation *)conv item:(IMAConversationChangedNotifyItem *)item {
    
    if (_conversationChangedCompletion)
    {
        _conversationChangedCompletion(item);
    }
    
    [[NSNotificationQueue defaultQueue] enqueueNotification:[item changedNotification] postingStyle:NSPostWhenIdle];
    
    //zl_判断是否为好友, 如果是好友直接更新会话列表,否则重新获取用户信息,返回结果后更新会话列表
    IMAUser *user = [[IMAPlatform sharedInstance].contactMgr getUserByUserId:[conv.conversation getReceiver]];
    //&& [[conv receiver] hasPrefix:@"daren_"]
    if (!user && [conv imaType] == IMA_C2C ) {
        
        [[IMAPlatform sharedInstance] asyncGetStrangerInfo:[conv.conversation getReceiver] succ:^(IMAUser *auser) {
            
            CNUserProfile *profile = [[CNUserProfile alloc] init];
            profile.receiver = auser.userId;
            profile.showName = [auser showTitle];
            profile.icon = auser.icon;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[CNUserProfileFMDBManager manager] updateProfile:profile succ:nil fail:nil];
                conv.updateDarenInfo = !conv.updateDarenInfo;
            });
           
            
        } fail:^(int code, NSString *msg) {
            
            NSLog(@"获取陌生人信息fail-----");

        }];
        
    }

    
}


@end