IVTKSYLiveShowViewController.m 88.4 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 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
//
//  IVTKSYLiveShowViewController.m
//  IVTMeLiveTwo
//
//  Created by xrg on 16/8/18.
//  Copyright © 2016年 QLQ. All rights reserved.
//

#import "IVTKSYLiveShowViewController.h"
#import "IVTKSYPushLiveShowObj.h"
#import "IVTChatRoomCell.h"
#import "GrounderSuperView.h"
#import "HPGrowingTextView.h"
#import "IVTBarrageModel.h"
#import "IVTMeMineUserView.h"
#import "IVTMeUserView.h"
#import "IVTMeLiveAllUserCollectionViewCell.h"
#import "IVTMeGiftViewController.h"
#import "IVTMyChatListViewController.h"
#import "ShareView.h"
#import "IVTMeRedPacketView.h"
#import "IVTMeUnGrabView.h"
#import "IVTGetRedPackedModel.h"
#import "MitangViewController.h"
#import "MyWalletViewController.h"
#import "DBManager.h"
#import "IVTMeUnGrabListView.h"
#import "IVTEndLiveViewController.h"
#import "IVTMyChatContentListViewController.h"
#import "informReportViewController.h"
#import "AppDelegate.h"
#import "IVTHotAndFollowVideoModel.h"
static NSString *cellReuseIdentifier = @"cellReuseIdentifier";

@interface IVTKSYLiveShowViewController ()<XMPPManagerDelegate,HPGrowingTextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,IVTMeGiftViewControllerDelegate,IVTMeRedPacketDelegate,DoHongBaoDelegate,IVTMeUserDelegate>
{
    //.. 弹幕
    GrounderSuperView *barrageView;
    //  红包
    IVTMeRedPacketView *redPacketView;
    
    IVTMeUnGrabView *unGrab;

    // 私信
    IVTMyChatListViewController *myChatListVC;
    //  红包相关
    NSString *redPacketId;
    /**
     *  上部UI
     */
    // 屏幕上部
    // 主播头像背景
    UIImageView *_headBackGroundImg;
    // 主播头像
    UIButton *_headImg;
    //  直播label
    UILabel *_liveLabel;
    //  人数label
    UILabel *_viewCount;
    //  关注按钮
    UIButton *_attentionImg;
    
    
    // 蜜糖背景
    UIButton *_mitangBackGroundImg;
    //  蜜糖更多按钮
    UIImageView *_mitangMoreImg;
    // 蜜糖数
    UILabel *_mitangCountLabel;
    // 观众滚动视图
    UIView *_viewersView;
    
    UILabel *userIdLabel;
    
    /**
     *  中部UI
     */

    HPGrowingTextView *textView;
    UITextField *textField;
    UIView *backgroundImg;
    UIView *backGround;
    UIButton *danmuSwitch;
    UIButton *sendBtn;
    
    
    /**
     *  下部UI
     */
    // 聊天按钮
    UIButton *_chatBtn;
    //  消息按钮
    UIButton *_msgBtn;
    
    // 分享按钮
    UIButton *_shareBtn;
    
    // 礼物按钮
    UIButton *_presentBtn;
    IVTMeGiftViewController *gift;
    //  红包按钮
    UIButton  *_redPacket;
    //  关闭直播按钮
    UIButton *_closeBtn;
    //  分享页面
//    CustomShareView *_customShareView;

    NSInteger miTangTotalNumberForZhuBo;

    
    //    /*
    //     判断是否被禁言
    //     */
    BOOL isEstoppel;
    BOOL isDanmu;
    UIImageView *dot;
    int _followCount;
    int    _danmuCount;

    NSDictionary *zhuBoInfo;
    /*
     管理员的tag:3001
     非管理的tag:4001
     */
    BOOL adminTag;
    
    NSMutableArray *managersArray;
    BOOL currentPopUserIsBan;
    
    // 礼物
    AnimOperationManager *manager;
    NSTimer *lianChengTimer;
    NSMutableArray *giftQueueArray;
    PresentView *gift1;
    PresentView *gift2;
    
    NSInteger personNum;
    
    NSMutableArray *PeopleRepacktedList;

    IVTMeUserView * user;
}

/**
 *  直播内tableview
 */
@property (nonatomic, strong) UITableView *chatRoomTableView;
// 数据源数组
@property (nonatomic, strong) NSMutableArray *messages;
@end

@implementation IVTKSYLiveShowViewController

- (void)initData
{
    _danmuCount = 2001;
    adminTag = NO;
    isEstoppel = NO;
    
    _messages = [[NSMutableArray alloc] init];
    
    _usersInfoArray = [[NSMutableArray alloc]initWithCapacity:10];
    
    giftQueueArray = [[NSMutableArray alloc]initWithCapacity:10];
    
    managersArray = [[NSMutableArray alloc]initWithCapacity:10];
    
    PeopleRepacktedList = [[NSMutableArray alloc] initWithCapacity:10];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    NSLog(@"IVTKSYLiveShowViewController5555 创建了");
    
    [self initData];
    [self initObserver];

    //  请求主播信息
    [self requestZhuBoInfo];
    
    [self initXmppStreamFunc];
    
    [self initUI];
    
    [self KSY_StartLiveShowFunc];
    
    [self estoppelForRequest];
    
    [[XMPPManager sharedInstance] getManagersList];
    
    manager = [[AnimOperationManager alloc] init];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    NSDictionary *messageDict =@{@"giftId":@"0",@"giftPic":@"nil",@"msgTime":[IVTThirdFuncTool timeStamp],@"msgBody":@"我们提倡绿色直播,封面和直播内容含吸烟、饮酒、低俗、诱惑、暴露等都将会被长期封账号,网警24小时在线巡查哦!",@"msgType" : @"3",@"giftPrice":@"0.000000",@"giftNumber":@"0",@"userInfo":@{@"userName":@"系统消息"}};
    [self.messages addObject:messageDict];
}

- (void)estoppelForRequest
{
    //  询问是否被禁言]
    NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setObject:[IVTAccountTool getUserId] forKey:@"userId"];
    [paramDict setObject:self.liveId forKey:@"liveId"];
    [[IVTNetworkAPIClient sharedClient] boolOfaddOrCanncel:paramDict success:^(NSDictionary *successData) {
        NSInteger state = [[successData objectForKey:@"state"] integerValue];
        if (state == 1) {
            isEstoppel = YES;
            NSLog(@"已经被禁言过了");
        }else{
            isEstoppel = NO;
            NSLog(@"还没被禁言");
        }
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        
    }];
}

- (void)didGetManagersList:(NSArray *)list{
    for (NSInteger i=0; i<list.count; i++) {
        DDXMLElement *element = [list objectAtIndex:i];
        DDXMLNode *node = [element attributeForName:@"jid"];
        NSString *currentJid = node.stringValue;
        NSRange range = [currentJid rangeOfString:@"@"];
        NSString *currentUserId = [currentJid substringToIndex:range.location];
        [managersArray addObject:currentUserId];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    user.hidden = NO;


}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBarHidden = NO;

}

- (void)initObserver
{
    [self setupObservers];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendRedPacket:) name:@"redPacket" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendPrivateRedPacket:) name:@"privateRedPacket" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDot) name:kPrivateMessageDidChange object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeGuanzhu:) name:@"followedChangedByUserView" object:nil];

}

#pragma mark - 添加通知
- (void)setupObservers
{
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handlePlayerNotify:)
                                                name:(MPMediaPlaybackIsPreparedToPlayDidChangeNotification)
                                              object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handlePlayerNotify:)
                                                name:(MPMoviePlayerPlaybackStateDidChangeNotification)
                                              object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handlePlayerNotify:)
                                                name:(MPMoviePlayerPlaybackDidFinishNotification)
                                              object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handlePlayerNotify:)
                                                name:(MPMoviePlayerLoadStateDidChangeNotification)
                                              object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handlePlayerNotify:)
                                                name:(MPMovieNaturalSizeAvailableNotification)
                                              object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handlePlayerNotify:)
                                                name:(MPMoviePlayerFirstVideoFrameRenderedNotification)
                                              object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handlePlayerNotify:)
                                                name:(MPMoviePlayerFirstAudioFrameRenderedNotification)
                                              object:nil];
}


#pragma mark - 移除通知
- (void)releaseObservers
{
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:MPMoviePlayerPlaybackStateDidChangeNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:MPMoviePlayerPlaybackDidFinishNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:MPMoviePlayerLoadStateDidChangeNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:MPMovieNaturalSizeAvailableNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:MPMoviePlayerFirstVideoFrameRenderedNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:MPMoviePlayerFirstAudioFrameRenderedNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)dealloc
{
    [self releaseObservers];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"followedChangedByUserView" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"redPacket" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"privateRedPacket" object:nil];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 *  UI
 *
 *  @return 创建TableView & collectionView
 */
#pragma mark - UI
- (void)initUI
{
    __unsafe_unretained typeof (self) wself = self;
    
    _videoView = [[UIView alloc] init];
    _videoView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    _videoView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_videoView];
    
    // 添加头部背景(主播介绍)
    _headBackGroundImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"headBackGroundImg"]];
    [self.view addSubview:_headBackGroundImg];
    _headBackGroundImg.userInteractionEnabled = YES;
    [_headBackGroundImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wself.view).offset(8);
        make.top.equalTo(wself.view).offset(30);
        make.size.mas_equalTo(CGSizeMake(140, 40));
    }];
    _headBackGroundImg.backgroundColor = [UIColor clearColor];
    _headBackGroundImg.layer.masksToBounds = YES;
    
    
    // 添加主播头像
    _headImg = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headImg sd_setImageWithURL:[NSURL URLWithString:self.zhuBoAvatarUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"占位头像"]];
    _headImg.layer.cornerRadius = 37 / 2;
    _headImg.layer.masksToBounds = YES;
    [_headBackGroundImg addSubview:_headImg];
    [_headImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headBackGroundImg).offset(3);
        make.top.equalTo(_headBackGroundImg).offset(1.5);
        make.size.mas_equalTo(CGSizeMake(37, 37));
    }];
    _headImg.backgroundColor = [UIColor clearColor];
    _headImg.layer.masksToBounds = YES;
    [_headImg addTarget:self action:@selector(imageClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    //  添加直播Label
    _liveLabel  = [[UILabel alloc] init];
    [_headBackGroundImg addSubview:_liveLabel];
    [_liveLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headBackGroundImg).offset(45);
        make.top.equalTo(_headBackGroundImg).offset(8);
        make.size.mas_equalTo(CGSizeMake(40, 10));
    }];
    _liveLabel.textAlignment = 1;
    _liveLabel.text = @"直播Live";
    _liveLabel.textColor = [UIColor colorWithRed:255 / 255 green:255 / 255 blue:255 / 255 alpha:1.0f];
    _liveLabel.font = [UIFont fontWithName:@"Helvetica" size:10];
    
    // 添加观看人数
    _viewCount = [[UILabel alloc] init];
    _viewCount.textAlignment = 1;
    _viewCount.font = [UIFont fontWithName:@"Helvetica" size:10];
    _viewCount.textColor = [UIColor colorWithRed:255 / 255 green:255 / 255 blue:255 / 255 alpha:1.0f];
    _viewCount.text = [NSString stringWithFormat:@"%ld",(long)self.personNumber];
    [_headBackGroundImg addSubview:_viewCount];
    [_viewCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headBackGroundImg).offset(48);
        make.top.equalTo(_headBackGroundImg).offset(25);
        make.size.mas_equalTo(CGSizeMake(40, 10));
    }];
    
    //
    //  添加关注
    _attentionImg  =[UIButton buttonWithType:UIButtonTypeCustom];
    [_attentionImg setBackgroundImage:[UIImage imageNamed:@"attention"] forState:UIControlStateNormal];
    _followCount = 99;
    NSArray *followedListArray = [[NSUserDefaults standardUserDefaults] valueForKey:@"followListArray"];
    for (NSInteger i=0; i<followedListArray.count; i++) {
        NSDictionary *followdDic =[followedListArray objectAtIndex:i];
        if ([_userIDTolive integerValue] == [[followdDic valueForKey:@"id"] integerValue]) {
            [_attentionImg setBackgroundImage:[UIImage imageNamed:@"已关注"] forState:UIControlStateNormal];
            _followCount = 100;
            break;
        }
    }
    [_headBackGroundImg addSubview:_attentionImg];
    [_attentionImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headBackGroundImg).offset(-10);
        make.top.equalTo(_headBackGroundImg).offset(10);
        make.size.mas_equalTo(CGSizeMake(40, 20));
    }];
    
    _attentionImg.backgroundColor = [UIColor clearColor];
    _attentionImg.layer.masksToBounds = YES;
    [_attentionImg addTarget:self action:@selector(attentionClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 添加蜜糖背景(主播蜜糖数)
    _mitangBackGroundImg = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mitangBackGroundImg setBackgroundImage:[UIImage imageNamed:@"metangBackGroundImg"] forState:UIControlStateNormal];//
    [self.view addSubview:_mitangBackGroundImg];
    [_mitangBackGroundImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wself.view).offset(0);
        make.top.equalTo(_headBackGroundImg).offset(60);
        make.size.mas_equalTo(CGSizeMake(50, 23));
    }];
    [_mitangBackGroundImg addTarget:self action:@selector(mitang:) forControlEvents:UIControlEventTouchUpInside];
    
    //  添加蜜糖数label
    UILabel *miTangNameLabel  = [[UILabel alloc] init];
    miTangNameLabel.textAlignment = 1;
    miTangNameLabel.textColor = [UIColor redColor];
    miTangNameLabel.font = [UIFont fontWithName:@"Helvetica" size:15];
    miTangNameLabel.text = @"蜜糖";
    [_mitangBackGroundImg addSubview:miTangNameLabel];
    [miTangNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_mitangBackGroundImg.mas_left).offset(10);
        make.top.equalTo(_mitangBackGroundImg.mas_top);
        make.bottom.equalTo(_mitangBackGroundImg.mas_bottom);
        make.width.mas_equalTo(30);
    }];
    
    //  添加蜜糖数label
    _mitangCountLabel  = [[UILabel alloc] init];
    _mitangCountLabel.textAlignment = 1;
    _mitangCountLabel.textColor = [UIColor colorWithRed:255 / 255 green:255 / 255 blue:255 / 255 alpha:1.0f];
    _mitangCountLabel.font = [UIFont systemFontOfSize:15];
    [_mitangBackGroundImg addSubview:_mitangCountLabel];
    [_mitangCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(miTangNameLabel.mas_right).offset(5);
        make.top.equalTo(_mitangBackGroundImg).offset(4);
        make.size.mas_equalTo(CGSizeMake(0, 15));
    }];
    
    _mitangMoreImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mitangMore"]];
    [_mitangBackGroundImg addSubview:_mitangMoreImg];
    [_mitangMoreImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_mitangCountLabel.mas_right).offset(5);
        make.top.equalTo(_mitangBackGroundImg).offset(4);
        make.size.mas_equalTo(CGSizeMake(15, 15));
    }];
    _mitangMoreImg.backgroundColor = [UIColor clearColor];
    _mitangMoreImg.layer.masksToBounds = YES;
    
    userIdLabel = [[UILabel alloc] init];
    userIdLabel.textColor = [UIColor whiteColor];
    userIdLabel.alpha = 0.3f;
    userIdLabel.font = [UIFont YXFontOfSize:13.0f];
    userIdLabel.textAlignment = NSTextAlignmentRight;
    userIdLabel.text = [NSString stringWithFormat:@"主播ID:%@",self.userIDTolive];
    [self.view addSubview:userIdLabel];
    [userIdLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_mitangBackGroundImg).offset(- 3);
        make.right.equalTo(wself.view.mas_right).offset(- 10);
        make.size.mas_equalTo(CGSizeMake(150, 30));
    }];
    
    UILabel *dateLabel = [[UILabel alloc] init];
    dateLabel.textColor = [UIColor whiteColor];
    NSString *str = [IVTThirdFuncTool timeStamp];
    //    NSString * str = @"1423189125874";
    NSTimeInterval _interval=[str doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyy.MM.dd"];
//    NSLog(@"%@", [objDateformat stringFromDate: date]);
    dateLabel.text = [objDateformat stringFromDate: date];
    dateLabel.alpha = 0.3f;
    dateLabel.font = [UIFont YXFontOfSize:13.0f];
    dateLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:dateLabel];
    [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(userIdLabel).offset(15);
        make.right.equalTo(wself.view.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(150, 30));
    }];
    

    /*
     弹幕
     */
    
    barrageView = [[GrounderSuperView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 360, kScreenWidth, 330)];
    barrageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:barrageView];
    
    barrageView.userInteractionEnabled = NO;//用户不可交互
    
    [barrageView setBackgroundColor:[UIColor clearColor]];
    
    [self createTabViewFunc];

    [self createBottomView];

    [self creatSendButton];
    

}

- (void)changeGuanzhu:(NSNotification *)text
{
    if ([zhuBoInfo[@"id"] integerValue]== [text.userInfo[@"id"] integerValue]) {
        if (_followCount == 99) {
            [_attentionImg setBackgroundImage:[UIImage imageNamed:@"已关注"] forState:UIControlStateNormal];
            _followCount = 100;
        }else if(_followCount == 100){
            [_attentionImg setBackgroundImage:[UIImage imageNamed:@"attention"]  forState:UIControlStateNormal];
            _followCount =99;
        }
    }
}


#pragma mark - 点击关注
-(void)attentionClick:(id)sender
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:[IVTAccountTool getUserName] forKey:@"username"];
    [dict setObject:[IVTAccountTool getPassword]forKey:@"captcha"];
    [dict setObject:_userIDTolive forKey:@"followerid"];
    
    if (_followCount== 99) {
        NSMutableDictionary *dict1 = [[NSMutableDictionary alloc]init];
        [dict1 setObject:[IVTAccountTool getUserName] forKey:@"username"];
        [dict1 setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
        [dict1 setObject:_userIDTolive forKey:@"userid"];
        
        [[IVTNetworkAPIClient sharedClient] getUserInfoForUserId:_userIDTolive success:^(NSDictionary *successData) {
            NSDictionary *userInfo = [successData objectForKey:@"data"];
            
            [[IVTNetworkAPIClient sharedClient] doFollowUser:_userIDTolive success:^(NSDictionary *successData) {
                NSMutableArray *followedListArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"followListArray"] mutableCopy];
                if (followedListArray) {
                    [followedListArray addObject:userInfo];
                }
                else{
                    followedListArray = [NSMutableArray arrayWithObject:userInfo];
                }
                [[NSUserDefaults standardUserDefaults] setObject:[followedListArray copy] forKey:@"followListArray"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [_attentionImg setBackgroundImage:[UIImage imageNamed:@"已关注"] forState:UIControlStateNormal];
                _followCount = 100;
                [SVProgressHUD setMinimumDismissTimeInterval:2];
                [SVProgressHUD showSuccessWithStatus:@"关注成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"followedChanged" object:nil userInfo:nil];

            } error:^(NSDictionary *successData) {
                
            } failure:^(NSError *failureError) {
                
            }];
            
        } error:^(NSDictionary *successData) {
            
        } failure:^(NSError *failureError) {
            
        }];
    }else if(_followCount == 100){
        
        [[IVTNetworkAPIClient sharedClient] doCancelFollowUser:_userIDTolive success:^(NSDictionary *successData) {
            NSMutableArray *followedListArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"followListArray"] mutableCopy];
            for (NSInteger i=0; i<followedListArray.count; i++) {
                if ([[[followedListArray objectAtIndex:i] valueForKey:@"id"] integerValue] == [_userIDTolive integerValue]) {
                    [followedListArray removeObjectAtIndex:i];
                    [[NSUserDefaults standardUserDefaults] setObject:[followedListArray copy] forKey:@"followListArray"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    break;
                }
            }
            
            [_attentionImg setBackgroundImage:[UIImage imageNamed:@"attention"]  forState:UIControlStateNormal];
            _followCount = 99;

            [SVProgressHUD setMinimumDismissTimeInterval:2];
            [SVProgressHUD showSuccessWithStatus:@"取消关注"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"followedChanged" object:nil userInfo:nil];

        } error:^(NSDictionary *successData) {
            
        } failure:^(NSError *failureError) {
            
        }];
 }
}


#pragma mark - 键盘事件
- (void)creatSendButton
{
    // 输入框的背景
    backGround= [[UIView alloc]init];
    [self.view bringSubviewToFront:backGround];
    [self.view addSubview:backGround];
    backGround.backgroundColor = [UIColor clearColor];
    __unsafe_unretained typeof (self) wself = self;
    [backGround mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(wself.view.mas_bottom);
        make.height.mas_equalTo(46);
        make.left.equalTo(wself.view.mas_left);
        make.right.equalTo(wself.view.mas_right);
    }];
    backGround.hidden = YES;
    
    
    
    //  弹幕开关
    danmuSwitch = [UIButton buttonWithType:UIButtonTypeCustom];
    [danmuSwitch addTarget:self action:@selector(switchDanmuSwitch:) forControlEvents:UIControlEventTouchUpInside];
    [danmuSwitch setBackgroundImage:[UIImage imageNamed:@"弹幕关"] forState:UIControlStateNormal];
    
    
    [backGround addSubview:danmuSwitch];
    [danmuSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backGround.mas_top).with.offset(8);
        make.left.equalTo(backGround).offset(5);
        make.size.mas_equalTo(CGSizeMake(65, 35));
    }];
    
    
    //输入框
    textView = [[HPGrowingTextView alloc]init];
    textView.backgroundColor = [UIColor whiteColor];
    textView.alpha = 0.7;
    textView.minNumberOfLines = 1;
    textView.maxNumberOfLines = 2;
    textView.returnKeyType = UIReturnKeySend;
    textView.enablesReturnKeyAutomatically = YES;
    textView.font = [UIFont YXFontOfSize:14];
    textView.textColor = [UIColor blackColor];
    textView.placeholder = @"想和大家说点什么";
    textView.delegate = self;
    
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsZero;
    textView.internalTextView.backgroundColor = [UIColor clearColor];
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [backGround addSubview: textView];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(danmuSwitch).offset(70);
        make.right.equalTo(backGround).offset(-75);
        make.top.equalTo(backGround.mas_top).with.offset(8);
        make.height.mas_equalTo(35);
    }];
    
    
    
    // 发送按钮
   sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
   sendBtn.titleLabel.text = @"发送";
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"弹幕-发送框"] forState:UIControlStateNormal];
    [sendBtn setTitle: @"发送" forState: UIControlStateNormal];
    
    [backGround addSubview:sendBtn];
    [sendBtn addTarget:self action:@selector(sendMsgFunc:) forControlEvents:UIControlEventTouchUpInside];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backGround.mas_top).with.offset(8);
        make.right.equalTo(backGround).offset(-5);
        make.size.mas_equalTo(CGSizeMake(65, 35));
    }];
    
}

- (void)sendMsgFunc:(id)sender
{
    
    NSString *temp = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([temp length] == 0) {
        return;
    }else{
        if (isEstoppel == YES) {
            [SVProgressHUD showErrorWithStatus:@"已被禁言"];
            textView.text = nil;
        }else{
        if (_danmuCount == 2001) {
            
            [[XMPPManager sharedInstance] sendMessage:textView.text inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kNormalRoomChatMessageType giftId:0 eachPrice:0 totalNumber:0 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (textView.text) {
                    textView.text = @"";
                }
            });
        }else{
            
            if ([[IVTAccountTool getChineseCoinTotal] intValue] > 100) {
            NSInteger saveCoinTotal = [[IVTAccountTool getChineseCoinTotal] intValue] - 100;
            [IVTAccountTool setChineseCoinTotal:[NSString stringWithFormat:@"%ld",(long)saveCoinTotal]];
            
            NSMutableDictionary *paramDict = [[NSMutableDictionary alloc]init];
            [paramDict setObject:[IVTAccountTool getUserId] forKey:@"username"];
            [paramDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
            [paramDict setObject:self.liveId forKey:@"liveId"];
            
            [[IVTNetworkAPIClient sharedClient] sendDanmu:paramDict success:^(NSDictionary *successData) {
                [[XMPPManager sharedInstance] sendMessage:textView.text inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kDanMuRoomChatMessageType giftId:0 eachPrice:1 totalNumber:0 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp]];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (textView.text) {
                        textView.text = @"";
                    }
                });
            } error:^(NSDictionary *successData) {
                
            } failure:^(NSError *failureError) {
                }];
            }else{
                [SVProgressHUD setMinimumDismissTimeInterval:3.0];
                [SVProgressHUD showErrorWithStatus:@"余额不足,请充值!"];
            }
            }
        }
    }
}

#pragma mark - 键盘发送按钮消息
- (BOOL)growingTextView:(HPGrowingTextView *)growingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        if (isEstoppel == YES) {
            [SVProgressHUD showErrorWithStatus:@"已被禁言"];
            textView.text = nil;
        }else{
        if (_danmuCount == 2001) {
            [[XMPPManager sharedInstance] sendMessage:textView.text inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kNormalRoomChatMessageType giftId:0 eachPrice:0 totalNumber:0 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp]];
            
            LRLog(@"发送的文本");
            dispatch_async(dispatch_get_main_queue(), ^{
                if (textView.text) {
                    textView.text = @"";
                }
            });
        }else{
            NSMutableDictionary *paramDict = [[NSMutableDictionary alloc]init];
            [paramDict setObject:[IVTAccountTool getUserId] forKey:@"username"];
            [paramDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
            [paramDict setObject:self.liveId forKey:@"liveId"];
            [[IVTNetworkAPIClient sharedClient] sendDanmu:paramDict success:^(NSDictionary *successData) {
                [[XMPPManager sharedInstance] sendMessage:textView.text inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kDanMuRoomChatMessageType giftId:0 eachPrice:1 totalNumber:0 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (textView.text) {
                        textView.text = @"";
                    }
                });
            } error:^(NSDictionary *successData) {
                
            } failure:^(NSError *failureError) {
                LRLog(@"failureError:%@",failureError);
                }];
            }
        }
        return NO;
    }
    return YES;
}

#pragma mark - 下部UI
- (void)createBottomView{
    __unsafe_unretained typeof (self) wself = self;
    
    UIView *bottomView = [[UIView alloc]init];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wself.view.mas_left);
        make.right.equalTo(wself.view.mas_right);
        make.bottom.equalTo(wself.view.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    //  聊天按钮
    _chatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_chatBtn setBackgroundImage:[UIImage imageNamed:@"聊天大厅"] forState:UIControlStateNormal];
    [bottomView addSubview:_chatBtn];
    [_chatBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView.mas_left).offset(12);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    _chatBtn.backgroundColor = [UIColor clearColor];
    _chatBtn.layer.masksToBounds = YES;
    [_chatBtn addTarget:self action:@selector(messageRoomClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //  退出房间按钮
    _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeBtn setBackgroundImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [bottomView addSubview:_closeBtn];
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView.mas_right).offset(-12);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    _closeBtn.backgroundColor = [UIColor clearColor];
    _closeBtn.layer.masksToBounds = YES;
    [_closeBtn addTarget:self action:@selector(onQuit) forControlEvents:UIControlEventTouchUpInside];
    
    //  礼物按钮
    _presentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_presentBtn setBackgroundImage:[UIImage imageNamed:@"礼物"] forState:UIControlStateNormal];
    [bottomView addSubview:_presentBtn];
    [_presentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_closeBtn.mas_left).offset(-12);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    _presentBtn.backgroundColor = [UIColor clearColor];
    _presentBtn.layer.masksToBounds = YES;
    [_presentBtn addTarget:self action:@selector(presentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //  分享房间按钮
    _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareBtn setBackgroundImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
    [bottomView addSubview:_shareBtn];
    [_shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_presentBtn.mas_left).offset(-12);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    _shareBtn.backgroundColor = [UIColor clearColor];
    _shareBtn.layer.masksToBounds = YES;
    [_shareBtn addTarget:self action:@selector(shareBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    //  消息按钮
    _msgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_msgBtn setBackgroundImage:[UIImage imageNamed:@"消息"] forState:UIControlStateNormal];
    [bottomView addSubview:_msgBtn];
    [_msgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_shareBtn.mas_left).offset(-12);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    _msgBtn.backgroundColor = [UIColor clearColor];
    _msgBtn.layer.masksToBounds = YES;
    [_msgBtn addTarget:self action:@selector(msgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    dot = [[UIImageView alloc]init];
    dot.image = [UIImage imageNamed:@"未读信息red"];
    [_msgBtn addSubview:dot];
    dot.userInteractionEnabled = YES;
    [dot mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_msgBtn.mas_right).offset(-6);
        make.top.equalTo(_msgBtn.mas_top).with.offset(6);
        make.size.mas_equalTo(CGSizeMake(6, 6));
    }];
    if ([[DBManager sharedInstance] getTotalNumberOfMessageNoRead] > 0) {
        dot.hidden = NO;
    }
    else{
        dot.hidden = YES;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNewMessageFromXmpp) name:@"getNewMessage" object:nil];
    
    //红包按钮
    _redPacket = [UIButton buttonWithType:UIButtonTypeCustom];
    [_redPacket setBackgroundImage:[UIImage imageNamed:@"redPacket"] forState:UIControlStateNormal];
    [bottomView addSubview:_redPacket];
    [_redPacket addTarget:self action:@selector(redPacketClick) forControlEvents:UIControlEventTouchUpInside];
    [_redPacket mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_msgBtn.mas_left).offset(-12);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    
//    //点赞区域
//    _zanView = [[UIView alloc]init];
//    //    _zanView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:_zanView];
//    _zanView.userInteractionEnabled = YES;
//    [_zanView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(wself.view.mas_right).with.offset(-45);
//        
//        make.bottom.equalTo(bottomView.mas_top).with.offset(-3);
//        make.size.mas_equalTo(CGSizeMake(50, 250));
//    }];
}

- (void)refreshDot{
    NSInteger total = [[DBManager sharedInstance] getTotalNumberOfMessageNoRead];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (total > 0) {
            dot.hidden = NO;
        }
        else{
            dot.hidden = YES;
        }
    });
}

- (void)requestZhuBoInfo
{
    [[IVTNetworkAPIClient sharedClient] getUserInfoForUserId:_userIDTolive success:^(NSDictionary *successData) {
        zhuBoInfo = [successData objectForKey:@"data"];
        
        miTangTotalNumberForZhuBo = [zhuBoInfo[@"mecointotal"] integerValue];
        [_headImg sd_setImageWithURL:[NSURL URLWithString:zhuBoInfo[@"avatar"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"占位头像"]];
        
        [self updataMiTang];
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        LRLog(@"failureError:%@",failureError);
    }];
    
}

#pragma mark - 创建tableview & scrollView

- (void)createTabViewFunc{
    
    __unsafe_unretained typeof (self) wself = self;
    
    self.chatRoomTableView = [[UITableView alloc] initWithFrame:CGRectMake(8, kScreenHeight - 200, kScreenWidth - 35, 150) style:UITableViewStylePlain];
    [_chatRoomTableView registerNib:[UINib nibWithNibName:@"IVTChatRoomCell" bundle:nil] forCellReuseIdentifier:cellReuseIdentifier];

    self.chatRoomTableView.backgroundColor = [UIColor clearColor];
    [self.chatRoomTableView setShowsVerticalScrollIndicator:NO];
    
    self.chatRoomTableView.delegate = self;
    self.chatRoomTableView.dataSource = self;
    
    self.chatRoomTableView.separatorColor = [UIColor clearColor];
    self.chatRoomTableView.rowHeight = UITableViewAutomaticDimension;
    self.chatRoomTableView.estimatedRowHeight = 20;
    [self.view addSubview:self.chatRoomTableView];
    
    
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 6;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, 0, 40) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.scrollEnabled = YES;
    _collectionView.backgroundColor  = [UIColor clearColor];
    _collectionView.contentSize = CGSizeMake(_collectionView.frame.size.height*4, _collectionView.frame.size.height*1);
    
    [self.collectionView  registerClass:[IVTMeLiveAllUserCollectionViewCell class] forCellWithReuseIdentifier:@"LiveAllUserCell"];
    
    [self.view addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wself.view.mas_top).offset(30);
        make.left.equalTo(_headBackGroundImg.mas_right).offset(10);
        make.right.equalTo(wself.view.mas_right).offset(-10);
        make.height.mas_equalTo(40);
    }];
}

- (void)creatScrollView
{
}

//  switchDanmuClose
- (void)switchDanmuSwitch:(UIButton *)sender
{
    if (_danmuCount == 1001) {
        textView.placeholder = @"想和大家说点什么";
        
        [danmuSwitch setBackgroundImage:[UIImage imageNamed:@"弹幕关"] forState:UIControlStateNormal];
//        [barrageView removeFromSuperview];
        
        _danmuCount = 2001;
    } else if (_danmuCount == 2001){
        textView.placeholder = @"开启弹幕,1中国币/条";
        
        
        [danmuSwitch setBackgroundImage:[UIImage imageNamed:@"弹幕开"] forState:UIControlStateNormal];
//        [self.view addSubview:barrageView];
        _danmuCount = 1001;
    }
}

#pragma mark - 
- (void)keyboardWillChange:(NSNotification *)notification
{
    /*
     计算需要移动的距离
     弹出的时候移动的值 : 键盘的Y值 – 控制view的高度 = 要移动的距离
     -  480 = -216pch
     
     隐藏的时候移动的值 : 键盘的Y值 - 控制view的高度 = 要移动的距离
     480 -  480 = 0
     */
    
    // 1.获取键盘的Y值
    NSDictionary *dict = notification.userInfo;
    CGRect keyboardFrame = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = keyboardFrame.origin.y ;
    // 获取动画执行时间
    CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    // 2.计算需要移动的距离
    CGFloat translationY = keyboardY - self.view.frame.size.height;
    // 通过动画移动view
    /*
     [UIView animateWithDuration:duration animations:^{
     self.view.transform = CGAffineTransformMakeTranslation(0, translationY);
     }];
     */
    
    /*
     输入框和键盘之间会由一条黑色的线条, 产生线条的原因是键盘弹出时执行动画的节奏和我们让控制器view移动的动画的节奏不一致导致
     */
    
    [UIView animateWithDuration:duration delay:0.0 options:7 << 16 animations:^{
        // 需要执行动画的代码
        barrageView.transform = CGAffineTransformMakeTranslation(0, translationY);
        _headBackGroundImg.transform = CGAffineTransformMakeTranslation(0, translationY);
        _mitangBackGroundImg.transform = CGAffineTransformMakeTranslation(0, translationY);
        backGround.transform = CGAffineTransformMakeTranslation(0, translationY);
        self.chatRoomTableView.transform = CGAffineTransformMakeTranslation(0, translationY);
        self.collectionView.transform = CGAffineTransformMakeTranslation(0, translationY);
        
    } completion:^(BOOL finished) {
        // 动画执行完毕执行的代码
    }];
    
}

//  注册第一响应者响应者
- (void)messageRoomClick:(UIButton *)sender
{
    backGround.hidden = NO;
    [textField becomeFirstResponder];
    [textView becomeFirstResponder];
}

-(void)viewTapped:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
  
    backGround.hidden = YES;
    
}
//  释放第一响应者
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [textView resignFirstResponder];
    [gift.view removeFromSuperview];
    backGround.hidden = YES;
    [[ShareView sharedInstance] hidden];
    [myChatListVC.view removeFromSuperview];
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
    if (theTextField == textField) {
        [theTextField resignFirstResponder];
    }
    return YES;
}

#pragma mark - 主播头像点击
-(void)imageClick:(UIButton*)sender{
    [self.view endEditing:YES];
    [[IVTNetworkAPIClient sharedClient] getUserInfoForUserId:_userIDTolive success:^(NSDictionary *successData) {
        zhuBoInfo = [successData objectForKey:@"data"];
        [self showUserInfoWithData:zhuBoInfo];
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        LRLog(@"failureError:%@",failureError);
    }];
}

#pragma mark - 进入发红包控制器
- (void)redPacketClick
{
    MyWalletViewController *myWallet = [[MyWalletViewController alloc]init];
    myWallet.liveID = self.liveId;
    myWallet.zhuBoId = self.userIDTolive;
    
    myWallet.zhuboAvatar = zhuBoInfo[@"avatar"];
    myWallet.zhuboName = zhuBoInfo[@"name"];
    [self.navigationController pushViewController:myWallet animated:YES];
}

#pragma mark - 接收红包并显示
- (void)sendRedPacket:(NSNotification *)text
{
    NSString *redPacketID = text.userInfo[@"redPacket"];
    [[XMPPManager sharedInstance] sendMessage:@"群发了一个红包" inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kGroupRedPacketType giftId:[redPacketID integerValue] eachPrice:0 totalNumber:0 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp]];
}



#pragma mark - 显示私包

- (void)sendPrivateRedPacket:(NSNotification *)text
{
    CGFloat count = [text.userInfo[@"count"] floatValue];
    [[XMPPManager sharedInstance] sendMessage:@"给主播发了一个红包" inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kPrivateRedPacketType giftId:0 eachPrice:count totalNumber:1 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp]];
}



#pragma mark - 弹框显示
- (void)showUserInfoWithData:(NSDictionary *)userInfoDict{
    if ([[userInfoDict objectForKey:@"id"] integerValue] == [[IVTAccountTool getUserId] integerValue]) {//本人
        IVTMeMineUserView *userMine = [IVTMeMineUserView sharedInstance];
        userMine.entity = userInfoDict;
        [userMine show];
    }
    else{
        if ([[userInfoDict objectForKey:@"id"] integerValue] == [_userIDTolive integerValue]) {//主播
            user = [IVTMeUserView sharedInstance];
            user.entity = userInfoDict;
            user.isPullStream = YES;
            user.isZhuBo = YES;
            [user setUI];
            user.delegate = self;
            [user show];
        }
        else{
            BOOL isManager = NO;
            for (NSInteger i=0; i<managersArray.count; i++) {
                if ([[managersArray objectAtIndex:i] integerValue] == [[userInfoDict objectForKey:@"id"] integerValue]) {
                    isManager = YES;
                    break;
                }
            }
            NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init];
            [paramDict setObject:[NSString stringWithFormat:@"%@",userInfoDict[@"id"]] forKey:@"userId"];
            [paramDict setObject:self.liveId forKey:@"liveId"];
            [[IVTNetworkAPIClient sharedClient] boolOfaddOrCanncel:paramDict success:^(NSDictionary *successData) {
                NSInteger state = [[successData objectForKey:@"state"] integerValue];
                
                user = [IVTMeUserView sharedInstance];
                user.entity = userInfoDict;
                user.isPullStream = YES;
                user.isZhuBo = NO;
                if (isManager) {
                    user.isManager = YES;
                }
                else{
                    user.isManager = NO;
                }
                if (adminTag == YES) {
                    user.isSetManager = YES;
                }
                else{
                    user.isSetManager = NO;
                }
                if (state == 1) {
                    
                    NSLog(@"已经被禁言过了");
                    
                    currentPopUserIsBan = YES;
                }
                else{
                    currentPopUserIsBan = NO;
                }
                [user setUI];
                user.delegate = self;
                [user show];

            } error:^(NSDictionary *successData) {
                
            } failure:^(NSError *failureError) {
                LRLog(@"failureError:%@",failureError);
            }];
        }
    }
}

- (void)msgBtnClick:(UIButton *)sender
{
    myChatListVC = [[IVTMyChatListViewController alloc]init];
    myChatListVC.isSmall = YES;
    [self addChildViewController:myChatListVC];
    [self.view addSubview:myChatListVC.view];
}



    
#pragma mark - 退出
- (void)onQuit
{
    manager = nil;
    [lianChengTimer invalidate];
    lianChengTimer = nil;
    [[XMPPManager sharedInstance] leaveRoomBySelf];
    [self quitRoomReq];
    [self.player stop];

    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - 分享
- (void)shareBtn:(UIButton *)sender
{
    //    username=xxx&captcha=xxx
    //    参数:liveId(视频id 必填 int类型)
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setObject:self.liveId forKey:@"liveId"];
    [paramDict setObject:[IVTAccountTool getUserName] forKey:@"username"];
    [paramDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
    [[IVTNetworkAPIClient sharedClient] liveShareSuccess:paramDict success:^(NSDictionary *successData) {
        
        NSDictionary *data = successData[@"data"];
        
        ShareContentModel * shareModel = [[ShareContentModel alloc] init];
        shareModel.shareTitle = data[@"title"];
        shareModel.shareContent = data[@"message"];
        shareModel.sharePictureURL = data[@"avatar"];
        shareModel.shareURL = data[@"url"];
        [[ShareView sharedInstance] showWithEntity:shareModel];
    } error:^(NSDictionary *successData) {
        NSString *msg = successData[@"description"];
        [HUDUtil showError:msg];
    } failure:^(NSError *failureError) {
        [HUDUtil showError:@"分享失败,请检查网络"];
    }];
}

#pragma mark - 弹出礼物页面按钮
/**
 *  发送礼物按钮点击 出现礼物页面
 *
 *  @return
 */
- (void)presentBtnClick:(id)sender
{
    gift = [[IVTMeGiftViewController alloc]init];
    gift.delegate = self;
    [self addChildViewController:gift];
    [self.view addSubview:gift.view];
}

#pragma mark -发送礼物代理方法
-(void)sendGiftWithData:(NSDictionary *)dictData isTenTimes:(BOOL)isTen{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:[IVTAccountTool getUserId] forKey:@"fromUserId"];
    [dict setObject:_userIDTolive forKey:@"toUserId"];
    [dict setObject:self.liveId forKey:@"liveId"];
    [dict setObject:dictData[@"id"] forKey:@"giftId"];
    if (isTen) {
        [dict setObject:@(10) forKey:@"count"];
    }
    else{
        [dict setObject:@(1) forKey:@"count"];
    }
    [[IVTNetworkAPIClient sharedClient] sendGift:dict success:^(NSDictionary *successData) {
        [IVTAccountTool setChineseCoinTotal:[[successData objectForKey:@"data"][0] objectForKey:@"chineseCoin"]];
        
        NSInteger currentChinesCoinNumber = [[[successData objectForKey:@"data"][0] objectForKey:@"chineseCoin"] integerValue]/100;
        
        if (gift) {
            [gift updataCurrentMiTang:currentChinesCoinNumber];
        }
        
        if ([dictData[@"type"] integerValue] == 0) {
            
            NSString *messageString = nil;
            if (isTen) {
                messageString = @"送出10个";
            
                [[XMPPManager sharedInstance] sendMessage:[NSString stringWithFormat:@"%@%@",messageString,dictData[@"name"]] inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kSmallGiftType giftId:[dictData[@"id"] integerValue] eachPrice:[dictData[@"price"] floatValue] totalNumber:10.0 giftPic:dictData[@"icon"] msgTime:[IVTThirdFuncTool timeStamp]];
                
            }else{
                
                messageString = @"送出1个";
                
                [[XMPPManager sharedInstance] sendMessage:[NSString stringWithFormat:@"%@%@",messageString,dictData[@"name"]] inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kSmallGiftType giftId:[dictData[@"id"] integerValue] eachPrice:[dictData[@"price"] floatValue] totalNumber:1.0 giftPic:dictData[@"icon"] msgTime:[IVTThirdFuncTool timeStamp]];
            }
        }else{
            [[XMPPManager sharedInstance] sendMessage:[NSString stringWithFormat:@"送了一个%@",dictData[@"name"]] inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kBigGiftType giftId:[dictData[@"id"] integerValue] eachPrice:[dictData[@"price"] floatValue] totalNumber:10.0 giftPic:dictData[@"icon"] msgTime:[IVTThirdFuncTool timeStamp]];
        }

    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        LRLog(@"failureError:%@",failureError);
    }];
}

//必须实现 否则无法触发点击事件
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}


- (void)loginRoom
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
    [dict setObject:self.liveId forKey:@"liveId"];
    [dict setObject:[IVTAccountTool getUserId] forKey:@"userId"];
    [dict setObject:[IVTAccountTool getUserId] forKey:@"username"];
    [dict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];

    [[IVTNetworkAPIClient sharedClient] loginRoom:dict success:^(NSDictionary *successData) {
        LRLog(@"successData:%@",successData);
        if ([[NSString stringWithFormat:@"%@",successData[@"code"]] isEqualToString:@"3001"]) {
            [self quitByEndLive:[successData[@"meTotal"] floatValue] audienceTotle:[successData[@"audienceTotalNum"] integerValue]];
        }
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        
    }];
}

//  离开直播间请求
- (void)quitRoomReq
{
    NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setObject:self.liveId forKey:@"liveId"];
    [[IVTNetworkAPIClient sharedClient] leaveRoom:paramDict success:^(NSDictionary *successData) {
        LRLog(@"successData:%@",successData);
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        LRLog(@"failureError:%@",failureError);
    }];
}

/**
 *  显示弹幕
 *
 *  @param avatar  头像地址
 *  @param message 说的话
 *  @param name    名字
 */
- (void)showBarrage:(NSString *)avatar message:(NSString *)message name:(NSString *)name
{
    IVTBarrageModel *model = [[IVTBarrageModel alloc] init];
    model.name = message;
    model.title = name;
    model.headImageStr = avatar;
    
    [barrageView setModel:model];
}

#pragma mark - 金山云开始观看直播
- (void)KSY_StartLiveShowFunc
{
    _player = [[KSYMoviePlayerController alloc] initWithContentURL:self.liveShowURL];
    _player.controlStyle = MPMovieControlStyleNone;
    [_player.view setFrame:_videoView.bounds];
    [_videoView addSubview: _player.view];
    _player.view.autoresizesSubviews = TRUE;
    _player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _player.shouldAutoplay = YES;
    _player.bufferTimeMax = 5;
    _player.scalingMode = MPMovieScalingModeAspectFit;
    _player.shouldEnableKSYStatModule = TRUE;
    [_player prepareToPlay];
}

#pragma mark - 刷新视频
- (void)onReloadVideo:(NSString *)liveShowURL is_flush:(BOOL)is_flush
{
    if (_player) {
        [_player reload:[NSURL URLWithString:liveShowURL] is_flush:is_flush];
    }
}

#pragma mark - 暂停视频
- (void)onPauseVideo
{
    if (_player) {
        [_player pause];
    }
}

#pragma mark - 停止视频
- (void)onStopVideo
{
    if (_player) {
        [_player stop];
        [_player.view removeFromSuperview];
        _player = nil;
    }
}

//MPMediaPlaybackIsPreparedToPlayDidChangeNotification,完成Prepared;
//MPMoviePlayerPlaybackStateDidChangeNotification,播放器状态改变;
//MPMoviePlayerPlaybackDidFinishNotification,播放完成;
//MPMoviePlayerLoadStateDidChangeNotification,数据加载状态改变;
//        NSMutableDictionary * paramDict = [[NSMutableDictionary alloc]init];
//        // 参数:liveId(房间id 必填 int类型),userId(用户名id 必填 int类型),captcha(验证码 必填 string类型)
//        [paramDict setObject:self.liveId forKey:@"liveId"];
//        [paramDict setObject:[IVTAccountTool getUserId] forKey:@"userId"];
//        [paramDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
//
//        [[IVTNetworkAPIClient sharedClient] getLiveState:paramDict success:^(NSDictionary *successData) {
//
//            LRLog(@"-------------successData:%@",successData);
//
//        } error:^(ErrorCode errorCode) {
//
//        } failure:^(NSError *failureError) {
//
//        }];
//  播放器状态判断句柄
-(void)handlePlayerNotify:(NSNotification*)notify
{
    if (!_player) {
        return;
    }
    if (MPMediaPlaybackIsPreparedToPlayDidChangeNotification ==  notify.name) {//完成Prepared;

    }
    if (MPMoviePlayerPlaybackStateDidChangeNotification ==  notify.name) {//播放器状态改变

    }
    if (MPMoviePlayerLoadStateDidChangeNotification ==  notify.name) {//数据加载状态改变
        
        if (MPMovieLoadStateUnknown == _player.loadState) {// 出现未知状态
//            [SVProgressHUD showWithStatus:@"视频正在加载"];
        }
         if (MPMovieLoadStatePlayable == _player.loadState) {// 加载完成,可以播放
//            [SVProgressHUD showWithStatus:@"视频正在加载"];
        }
        if (MPMovieLoadStateStalled == _player.loadState) {// 如果视频正在加载中
//            [SVProgressHUD showWithStatus:@"视频正在加载"];
        }
        if(MPMovieLoadStatePlaythroughOK == _player.loadState){//加载完成,如果shouldAutoplay为YES,将自动开始播放
//            [SVProgressHUD showWithStatus:@"视频正在加载"];
        }
        if (_player.bufferEmptyCount && (MPMovieLoadStatePlayable & _player.loadState || MPMovieLoadStatePlaythroughOK & _player.loadState))//缓冲完成
        {
//            [SVProgressHUD dismiss];
        }
    if (MPMoviePlayerPlaybackDidFinishNotification ==  notify.name) {
            int reason = [[[notify userInfo] valueForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
            if (reason ==  MPMovieFinishReasonPlaybackEnded) {
                
            }else if (reason == MPMovieFinishReasonPlaybackError){
                
            }else if (reason == MPMovieFinishReasonUserExited){
                
                
                }
            }
        
        if (MPMoviePlayerFirstVideoFrameRenderedNotification == notify.name)
        {

        }
        
        if (MPMoviePlayerFirstAudioFrameRenderedNotification == notify.name)
        {

        }
        
        if (MPMoviePlayerSuggestReloadNotification == notify.name)
        {
            
        }
        
        if(MPMoviePlayerPlaybackStatusNotification == notify.name)
        {
            int status = [[[notify userInfo] valueForKey:MPMoviePlayerPlaybackStatusUserInfoKey] intValue];
            if(MPMovieStatusVideoDecodeWrong == status)
            {
                NSLog(@"Video Decode Wrong!\n");
            }
            else if(MPMovieStatusAudioDecodeWrong == status)
            {
                NSLog(@"Audio Decode Wrong!\n");
            }
//            else if (MPMovieStatusHWCodecUsed == status )
//            {
//                NSLog(@"Hardware Codec used\n");
//            }
//            else if (MPMovieStatusSWCodecUsed == status )
//            {
//                NSLog(@"Software Codec used\n");
//            }
        }
        
        
        
    }
}



#pragma mark - XMPP初始化
- (void)initXmppStreamFunc
{
    [self loginRoom];
    
    [[XMPPManager sharedInstance] joinOrCreateRoomWithChatRoomAddr:self.roomJID isOwner:NO];
    
    [XMPPManager sharedInstance].delegate = self;
}

#pragma mark-横向的用户列表部分
- (void)usersListInCurrentRoom:(NSArray *)useridArray{
    NSArray *jidArray = useridArray;
    for (NSInteger i=0; i<jidArray.count; i++) {
        NSString *currentJid = [jidArray objectAtIndex:i];
        NSRange range = [currentJid rangeOfString:@"@"];
        NSString *currentUserId = [currentJid substringToIndex:range.location];
        if ([currentUserId integerValue] != [self.userIDTolive integerValue]) {
            BOOL isHave = NO;
            for (NSInteger i=0; i<_usersInfoArray.count; i++) {
                if ([[[_usersInfoArray objectAtIndex:i] valueForKey:@"userID"] integerValue] == [currentUserId integerValue]) {
                    isHave = YES;
                    break;
                }
            }
            if (!isHave) {
                personNum +=useridArray.count;
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (personNum < 0) {
                        personNum = 0;
                    }
                    _viewCount.text = [NSString stringWithFormat:@"%ld",(long)personNum];
                });
//                用户在前,机器人在后
                if ([currentUserId integerValue] >= 210000 && [currentUserId integerValue] < 220000) {
                    [_usersInfoArray addObject:[NSDictionary dictionaryWithObject:currentUserId forKey:@"userID"]];
                } else {
                    [_usersInfoArray insertObject:[NSDictionary dictionaryWithObject:currentUserId forKey:@"userID"] atIndex:0];
                }
                
                [self getUserInfoForUserInCurrentRoom:currentUserId];
            }
        }
    }
}


- (void)getUserInfoForUserInCurrentRoom:(NSString *)userId{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    NSDictionary *dicInfo = [[NSBundle mainBundle] infoDictionary];
    [dict setObject:userId forKey:@"userid"];
    [dict setObject:[IVTAccountTool getUserName] forKey:@"username"];
    [dict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
    [dict setObject:[[UIDevice currentDevice] model] forKey:@"model"];
    [dict setObject:[[UIDevice currentDevice] identifierForVendor] forKey:@"deviceID"];
    [dict setObject:[NSString stringWithFormat:@"%f",kScreenWidth] forKey:@"width"];
    [dict setObject:[NSString stringWithFormat:@"%f",kScreenHeight] forKey:@"heigth"];
    [dict setObject:[dicInfo objectForKey:@"CFBundleShortVersionString"] forKey:@"appversion"];
    [dict setObject:@"apple" forKey:@"brand"];
    [dict setObject:@"" forKey:@"msisdn"];
    [dict setObject:@"" forKey:@"otherinfo"];
    [dict setObject:@"iOS" forKey:@"platform"];
    
    [[IVTNetworkAPIClient sharedClient] getUserInfoForUserId:userId success:^(NSDictionary *successData) {
        NSDictionary *userInfo = [successData objectForKey:@"data"];
        for (NSInteger i=0; i<_usersInfoArray.count; i++) {
            if ([[[_usersInfoArray objectAtIndex:i] valueForKey:@"userID"] integerValue] == [[userInfo valueForKey:@"id"] integerValue]) {
                NSMutableDictionary *dict = [[_usersInfoArray objectAtIndex:i] mutableCopy];
                [dict addEntriesFromDictionary:userInfo];
                [_usersInfoArray replaceObjectAtIndex:i withObject:[dict copy]];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        
    }];
}

//
//-(void)likai:(NSNotification *)text{
//    NSLog(@"----%@",text);
//    NSString *jidStrLeave = text.userInfo[@"likai"];
//    NSInteger count = _usersInfoArray.count;
//    for (NSInteger i=0; i<count; i++) {
//        if ([[NSString stringWithFormat:@"%@",[[_usersInfoArray objectAtIndex:i] valueForKey:@"id"]] isEqualToString:jidStrLeave]) {
//            [_usersInfoArray removeObjectAtIndex:i];
//            personNum--;
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (personNum < 0) {
//                    personNum = 0;
//                }
//                _viewCount.text = [NSString stringWithFormat:@"%ld",(long)personNum];
//            });
////            break;
//        }else{
//            LRLog(@"没有这个人");
//        }
//    }
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.collectionView reloadData];
//    });
//}

- (void)leaveRoom:(NSString *)jid
{
    LRLog(@"%@",jid);
    for (int i = 0; i < self.usersInfoArray.count; i ++) {
        if ([[_usersInfoArray objectAtIndex:i] valueForKey:@"id"] != nil) {
        if ([[NSString stringWithFormat:@"%@",[[_usersInfoArray objectAtIndex:i] valueForKey:@"id"]] isEqualToString:jid]) {
             [_usersInfoArray removeObjectAtIndex:i];
             personNum--;
            dispatch_async(dispatch_get_main_queue(), ^{
                if (personNum < 0) {
                    personNum = 0;
                    }
                _viewCount.text = [NSString stringWithFormat:@"%ld",(long)personNum];
                });
            }
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
    });
}


#pragma mark - XMPP接收消息
- (void)didReceiveRoomChatMessage:(NSString *)messageText type:(ChatMessageType)msgType giftId:(NSInteger)giftId eachPrice:(CGFloat)price totalNumber:(NSInteger)totalNumber giftPic:(NSString *)giftPic msgTime:(NSInteger)msgTime userInfo:(NSDictionary *)userInfo
{
    if (userInfo == nil) {
        return;
    }else{
    LRLog(@"messageText:%@,msgType:%ld,giftId:%ld,price:%f,totalNumber:%ld,userinfo:%@",messageText,(long)msgType,(long)giftId,price,totalNumber,userInfo);
    if (msgType == kSystemMessageType) {

        LRLog(@"接收到系统消息");
    }else if (msgType == kNormalRoomChatMessageType) {

        LRLog(@"普通群聊消息");
    }else if (msgType == kDanMuRoomChatMessageType){
        
        [self showBarrage:[userInfo valueForKey:@"avatar"] message:messageText name:[userInfo valueForKey:@"userName"]];
        LRLog(@"接收到弹幕消息");
    
    }else if (msgType == kGroupRedPacketType){

        [self showRedPacket:[userInfo objectForKey:@"userId"] RedPacketId:[NSString stringWithFormat:@"%ld",giftId] userName:[userInfo objectForKey:@"userName"] headIcon:[userInfo objectForKey:@"avatar"] userLevel:[userInfo objectForKey:@"level"] userSex:[userInfo objectForKey:@"sex"]];
        
        LRLog(@"接收到群红包");
    }else if (msgType == kPrivateRedPacketType){
        
        miTangTotalNumberForZhuBo += price;
        [self updataMiTang];
        LRLog(@"接收到私包");
    }else if (msgType == kSetManagerType){
        [managersArray addObject:[NSString stringWithFormat:@"%zd",giftId]];
        if ([userInfo[@"userId"] integerValue] == [[IVTAccountTool getUserId] integerValue]) {
            NSLog(@"自己已经被设置为管理员");
            adminTag = YES;
        }
        LRLog(@"接收到设置为管理员");
    }else if (msgType == kCancelManagerType){
        for (NSInteger i=0; i<managersArray.count; i++) {
            if ([userInfo[@"userId"] integerValue] == [[managersArray objectAtIndex:i] integerValue]) {
                [managersArray removeObjectAtIndex:i];
                break;
            }
        }
        if ([userInfo[@"userId"] integerValue] == [[IVTAccountTool getUserId] integerValue]) {
            NSLog(@"已经被取消管理员");
            adminTag = NO;
        }
        LRLog(@"接收到取消管理员");
    }else if (msgType == kSetBanSendMessageType){
        if ([userInfo[@"userId"] integerValue] == [[IVTAccountTool getUserId] integerValue]) {
            isEstoppel = YES;
        }

        LRLog(@"接收到设置禁言");
    }else if (msgType == kCancelBanSendMessageType){
        if ([userInfo[@"userId"] integerValue] == [[IVTAccountTool getUserId] integerValue]) {
            isEstoppel = NO;
        }
        
        LRLog(@"接收到取消禁言");
    }else if (msgType == kQuitRoomType){
        
        [self quitByEndLive:price audienceTotle:totalNumber];
        
        LRLog(@"接收到退出房间");
    }else if (msgType == kBigGiftType){
        
        miTangTotalNumberForZhuBo += price* totalNumber;
        [self updataMiTang];
        [self showGifWithGiftImageUrl:giftPic];
        
        LRLog(@"接收到大图礼物");
    }else if (msgType == kSmallGiftType){
        
        //  接收礼物动画
        miTangTotalNumberForZhuBo += price * totalNumber;
        
        [self updataMiTang];
        
        [self showPresentAnimation:[userInfo objectForKey:@"userName"] userId:[userInfo valueForKey:@"userId"] giftId:giftId price:price number:totalNumber messageBody:messageText userAvatar:[userInfo valueForKey:@"avatar"] gifIcon:giftPic];

        LRLog(@"接收到小图礼物");
    }
    
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setValue:messageText forKey:@"msgBody"];
    [paramDict setValue:[NSString stringWithFormat:@"%ld",(long)msgType] forKey:@"msgType"];
    [paramDict setValue:[NSString stringWithFormat:@"%f",price] forKey:@"giftPrice"];
    [paramDict setValue:[NSString stringWithFormat:@"%ld",(long)totalNumber] forKey:@"giftNumber"];
    [paramDict setValue:[NSString stringWithFormat:@"%ld",(long)giftId] forKey:@"giftId"];
    [paramDict setValue:[NSString stringWithFormat:@"%@",giftPic] forKey:@"giftPic"];
    [paramDict setValue:[NSString stringWithFormat:@"%ld",(long)msgTime] forKey:@"msgTime"];
    [paramDict setObject:userInfo forKey:@"userInfo"];
    [_messages addObject: paramDict];

        [self scrollToBottomAnimated:NO];
    }
}


- (void)scrollToBottomAnimated:(BOOL)isAnimated
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.chatRoomTableView reloadData];

    if ([self.chatRoomTableView numberOfSections] > 0) {
        NSInteger lastSectionIndex = [self.chatRoomTableView numberOfSections] - 1;
        NSInteger lastRowIndex = [self.chatRoomTableView numberOfRowsInSection:lastSectionIndex] - 1;
        if (lastRowIndex > 0) {
            NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
            [self.chatRoomTableView reloadData];
            [self.chatRoomTableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition: UITableViewScrollPositionBottom animated:isAnimated];
        }
    }
         });
}

#pragma mark - 收到退出直播
- (void)quitByEndLive:(CGFloat)mitangTotle audienceTotle:(NSInteger)audienceTotle
{
    [lianChengTimer invalidate];
    lianChengTimer = nil;
    [self.player stop];
    [[XMPPManager sharedInstance] leaveRoomBySelf];
    [self quitRoomReq];
    IVTEndLiveViewController *endLiveVC = [[IVTEndLiveViewController alloc] init];
            endLiveVC.mitangTotle = [NSString stringWithFormat:@"%.0f",mitangTotle];
            endLiveVC.audienceTotle = [NSString stringWithFormat:@"%ld",(long)audienceTotle];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController pushViewController:endLiveVC  animated:YES];
    });
}

#pragma mark - 举报
- (void)showJuBao:(IVTMeUserView *)viewOfSelf{
    [viewOfSelf removeFromSuperview];
    informReportViewController *inform = [[informReportViewController alloc]init];
    inform.liveId = self.liveId;
    [self.navigationController pushViewController:inform animated:YES];
}

- (void)showManagement:(IVTMeUserView *)viewOfSelf{
    
    NSString *title = nil;
    if (currentPopUserIsBan) {
        title = @"取消禁言";
    }
    else{
        title = @"禁言";
    }
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (currentPopUserIsBan) {
            [self canncelEstoppel:[viewOfSelf.entity[@"id"] intValue] userName:viewOfSelf.entity[@"name"]];//
        }
        else{
            [self SetEstoppel:[viewOfSelf.entity[@"id"] intValue] userName:viewOfSelf.entity[@"name"]];//
        }
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:sheet animated:YES completion:^{
        [user hidden];
    }];

}

/*
 未被禁言的tag:5001
 被禁言的tag:6001
 */
//"0x1227"; 禁言
#pragma mark - 设置禁言
- (void)SetEstoppel:(int)userId userName:(NSString *)name
{
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
    //    参数:userId(被禁言用户id int 必填),liveId(直播间 必填 int类型)
    [paramDict setObject:[NSString stringWithFormat:@"%d",userId] forKey:@"userId"];
    [paramDict setObject:_liveId forKey:@"liveId"];
    
    [[IVTNetworkAPIClient sharedClient] addChatAuth:paramDict success:^(NSDictionary *successData) {
        [[XMPPManager sharedInstance] sendMessage:@"已被禁言" inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kSetBanSendMessageType giftId:0 eachPrice:0 totalNumber:0 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp] managedUserId:[NSString stringWithFormat:@"%d",userId] managedUserName:name];
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        
    }];
}


#pragma mark - 取消禁言
- (void)canncelEstoppel:(int)userid userName:(NSString *)name
{
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
    //    参数:userId(被禁言用户id int 必填),liveId(直播间 必填 int类型)
    [paramDict setObject:[NSString stringWithFormat:@"%d",userid] forKey:@"userId"];
    [paramDict setObject:_liveId forKey:@"liveId"];
    
    [[IVTNetworkAPIClient sharedClient] canncelChatAuth:paramDict success:^(NSDictionary *successData) {
        [[XMPPManager sharedInstance] sendMessage:@"已被取消禁言" inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kCancelBanSendMessageType giftId:0 eachPrice:0 totalNumber:0 giftPic:0 msgTime:[IVTThirdFuncTool timeStamp] managedUserId:[NSString stringWithFormat:@"%d",userid] managedUserName:name];
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        
    }];
}




#pragma mark - 点击蜜糖数
- (void)mitang:(UIButton *)sender{
    MitangViewController *supportVC = [[MitangViewController alloc]init];
    supportVC.isMain = NO;
    supportVC.userID =  [NSString stringWithFormat:@"%@",zhuBoInfo[@"id"]];
    [self.navigationController pushViewController:supportVC animated:YES];
}

#pragma mark - 显示红包
- (void)showRedPacket:(NSString *)userId RedPacketId:(NSString *)RedPacketId userName:(NSString *)username headIcon:(NSString *)headIconURL userLevel:(NSString *)level userSex:(NSString *)sex{
    dispatch_async(dispatch_get_main_queue(), ^{
        redPacketId = RedPacketId;
        IVTMeRedPacketView * redPacketview = [[IVTMeRedPacketView alloc]init];
        redPacketview.nameString = [username base64DecodedToString];
        redPacketview.redPacketID = @([RedPacketId integerValue]);
        redPacketview.levelString = level;
        redPacketview.sexString = sex;
        redPacketview.tips.text = @"发现一个红包,金额随机";
        [redPacketview.headIcon sd_setImageWithURL:[NSURL URLWithString:headIconURL] placeholderImage:[UIImage imageNamed:@"抢红包头像"]];
        redPacketview.delegate = self;
        redPacketview.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [self.view addSubview:redPacketview];
        redPacketView = redPacketview;
    });
}

//#pragma mark - 抢红包代理
-(void)changeGrabView:(NSDictionary *)dict
{
    redPacketView.grabBtn.enabled = NO;
    [SVProgressHUD show];
    NSMutableDictionary *walletDict = [[NSMutableDictionary alloc] init];
    if (redPacketId != nil && dict[@"redPacketID"] != nil) {
        [walletDict setObject:[IVTAccountTool getUserId] forKey:@"userId"];
        [walletDict setObject:[IVTAccountTool getUserName] forKey:@"username"];
        [walletDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
        [walletDict setObject:dict[@"redPacketID"] forKey:@"redEnvelopId"];
    }else{
        [walletDict setObject:[IVTAccountTool getUserId] forKey:@"userId"];
        [walletDict setObject:[IVTAccountTool getUserName] forKey:@"username"];
        [walletDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
        [walletDict setObject:dict[@"giftId"] forKey:@"redEnvelopId"];
    }
    IVTMeUnGrabView * ungrab = [[IVTMeUnGrabView alloc]init];
    [[IVTNetworkAPIClient sharedClient] receiveRedPacket:walletDict success:^(NSDictionary *successData) {
        [SVProgressHUD dismiss];
        if ([[successData objectForKey:@"state"] integerValue] == 0) {
                NSInteger chineseCoinNumber = [[IVTAccountTool getMeCoinTotal] integerValue] + [[[successData objectForKey:@"map"] valueForKey:@"money"] integerValue]*100;
                [IVTAccountTool setMeCoinTotle:[NSString stringWithFormat:@"%ld",(long)chineseCoinNumber]];
                ungrab.tips.text = [NSString stringWithFormat:@"恭喜您抢得%@中国币",[successData valueForKeyPath:@"map.money"]];
        }else{
            ungrab.tips.text = [NSString stringWithFormat:@"恭喜您抢得%@中国币",[successData valueForKeyPath:@"map.money"]];
        }
        [ungrab.headIcon setImage:redPacketView.headIcon.image];
        ungrab.nameString = redPacketView.nameString;
        ungrab.levelString = redPacketView.levelString;
        ungrab.sexString = redPacketView.sexString;
        ungrab.delegate = self;
        ungrab.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [redPacketView removeFromSuperview];
        [self.view addSubview:ungrab];
        unGrab = ungrab;
        [self closeRedPacketView];
        [PeopleRepacktedList removeAllObjects];
        NSArray *listArray = [successData objectForKey:@"list"];
        for (NSMutableDictionary *dict in listArray) {
            IVTGetRedPackedModel *getRedPacktedModel = [[IVTGetRedPackedModel alloc] initWithDictionary:dict];
            getRedPacktedModel.name = [dict[@"name"] base64DecodedToString];
            getRedPacktedModel.userId = dict[@"userId"];
            getRedPacktedModel.avatar = dict[@"avatar"];
            getRedPacktedModel.money = dict[@"money"];
            getRedPacktedModel.sex = dict[@"sex"];
            getRedPacktedModel.signature = dict[@"signature"];
            [PeopleRepacktedList addObject:getRedPacktedModel];
        }
    } error:^(NSDictionary *successData) {
        [SVProgressHUD dismiss];
        IVTMeUnGrabView * ungrab = [[IVTMeUnGrabView alloc]init];
        unGrab = ungrab;
        [redPacketView removeFromSuperview];
        [PeopleRepacktedList removeAllObjects];
        unGrab.tips.text = @"手太慢,已抢光";
        NSArray *listArray = [successData objectForKey:@"list"];
        for (NSMutableDictionary *dict in listArray) {
            IVTGetRedPackedModel *getRedPacktedModel = [[IVTGetRedPackedModel alloc] initWithDictionary:dict];
            getRedPacktedModel.name = [dict[@"name"] base64DecodedToString];
            getRedPacktedModel.userId = dict[@"userId"];
            getRedPacktedModel.avatar = dict[@"avatar"];
            getRedPacktedModel.money = dict[@"money"];
            getRedPacktedModel.sex = dict[@"sex"];
            getRedPacktedModel.signature = dict[@"signature"];
            [PeopleRepacktedList addObject:getRedPacktedModel];
        }
        
        [ungrab.headIcon setImage:redPacketView.headIcon.image];
        ungrab.nameString = redPacketView.nameString;
        ungrab.levelString = redPacketView.levelString;
        ungrab.sexString = redPacketView.sexString;
        ungrab.delegate = self;
        ungrab.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [self.view addSubview:ungrab];
    } failure:^(NSError *failureError) {
        [SVProgressHUD setMinimumDismissTimeInterval:2];
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
        redPacketView.grabBtn.enabled = YES;
    }];
}

- (void)closeRedPacketView{
    [redPacketView removeFromSuperview];
}

- (void)closeClick{
    [redPacketView removeFromSuperview];
}

#pragma mark - 显示手气列表代理
-(void)showPacketList
{
    [SVProgressHUD dismiss];
    IVTMeUnGrabListView *unGrabList = [[IVTMeUnGrabListView alloc]init];
    unGrabList.tips.text = unGrab.tips.text;
    [unGrabList.headIcon setImage:redPacketView.headIcon.image];
    unGrabList.getRepacktedList = PeopleRepacktedList;
    unGrabList.nameString = redPacketView.nameString;
    unGrabList.levelString = redPacketView.levelString;
    unGrabList.sexString = redPacketView.sexString;
    unGrabList.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [self.view addSubview:unGrabList];
    [unGrabList.grabList reloadData];
    [unGrab removeFromSuperview];
    [PeopleRepacktedList removeAllObjects];
}


/**
 *  GIF动画
 *
 *  @param giftImageUrl GIF地址
 */
#pragma mark - GIF动图
- (void)showGifWithGiftImageUrl:(NSString *)giftImageUrl
{
    CGFloat durTime = 3.0;
    UIImageView *porsche918 = [[UIImageView alloc] init];
    porsche918.frame = CGRectMake(0, 0, 0, 0);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view addSubview:porsche918];
    });
    [porsche918 sd_setImageWithURL:[NSURL URLWithString:giftImageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [UIView animateWithDuration:durTime animations:^{
            porsche918.frame = CGRectMake(kScreenWidth * 0.5 - 100, kScreenHeight * 0.5 - 100 * 0.5, 240, 180);
            
        } completion:^(BOOL finished) {
            [porsche918 removeFromSuperview];
            
        }];
    }];
}


#pragma mark 礼物动画

- (void)showPresentAnimation:(NSString *)userName userId:(NSString *)userID giftId:(NSInteger)giftID price:(CGFloat)price number:(NSInteger)totalNumber messageBody:(NSString *)messageBody userAvatar:(NSString *)userAvatar gifIcon:(NSString *)gifIcon
{
    dispatch_async(dispatch_get_main_queue(), ^{
    // 礼物模型
        GiftModel *giftModel = [[GiftModel alloc] init];
        giftModel.headImage = userAvatar;
        giftModel.name = userName;
        giftModel.giftImage = gifIcon;
        giftModel.giftName = messageBody;
        giftModel.giftCount = totalNumber;
        manager.parentView = self.view;
        NSInteger modelIID = [userID integerValue] + giftID + price;
        [manager animWithUserID:[NSString stringWithFormat:@"%zd",modelIID] giftID:giftID model:giftModel finishedBlock:^(BOOL result) {
        }];
    });
}


#pragma mark - 更新蜜糖
- (void)updataMiTang{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *totalMiTangString = [NSString stringWithFormat:@"%zd", miTangTotalNumberForZhuBo];
        _mitangCountLabel.text = totalMiTangString;
        CGFloat widthForMiTangLabel = [IVTThirdFuncTool widthOfLabelWithString:totalMiTangString sizeOfFont:15 height:15];
        [_mitangBackGroundImg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(71+widthForMiTangLabel, 23));
        }];
        [_mitangCountLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(widthForMiTangLabel + 1, 15));
        }];
        [_mitangMoreImg mas_updateConstraints:^(MASConstraintMaker *make) {
        }];
    });
}



#pragma mark - tableview delegate & datasoure

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IVTChatRoomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    cell.entity = [_messages objectAtIndex:indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor clearColor];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self viewTapped:nil];
    
    NSDictionary *dict11 = [self.messages objectAtIndex:indexPath.row];
    
    if ([[NSString stringWithFormat:@"%@",[dict11 valueForKeyPath:@"msgType"]] isEqualToString:@"3" ]){
        return;
    }else{
        [[IVTNetworkAPIClient sharedClient] getUserInfoForUserId:[[self.messages objectAtIndex:indexPath.row] valueForKeyPath:@"userInfo.userId"] success:^(NSDictionary *successData) {
            NSDictionary *dict1 = [successData objectForKey:@"data"];
            [self showUserInfoWithData:dict1];
            
        } error:^(NSDictionary *successData) {
            
        } failure:^(NSError *failureError) {
            LRLog(@"failureError:%@",failureError);
        }];
    }
    
}


#pragma mark - scrollView delegate & datasoure
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return _usersInfoArray.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    IVTMeLiveAllUserCollectionViewCell *liveAllUserCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LiveAllUserCell" forIndexPath:indexPath];
    
    [liveAllUserCell.userHeadImageView sd_setImageWithURL:[NSURL  URLWithString:[NSString stringWithFormat:@"%@",[_usersInfoArray[indexPath.row] valueForKey:@"avatar"]]] placeholderImage:[UIImage imageNamed:@"占位头像"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

    }];
    
    return liveAllUserCell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(37, 37);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self viewTapped:nil];
    
    [[IVTNetworkAPIClient sharedClient] getUserInfoForUserId:[[_usersInfoArray objectAtIndex:indexPath.row] valueForKey:@"id"] success:^(NSDictionary *successData) {
        
        NSDictionary *paramDict = [successData objectForKey:@"data"];
        
        [self showUserInfoWithData:paramDict];
        
        LRLog(@"successData:%@",[successData valueForKey:@"data"]);
    } error:^(NSDictionary *successData) {
         
    } failure:^(NSError *failureError) {
        LRLog(@"failureError:%@",failureError);
    }];
}

- (void)showUserInfo:(IVTMeUserView *)viewOfSelf{
    [viewOfSelf removeFromSuperview];
    IVTUserInfoCenterViewController *userCenter = [[IVTUserInfoCenterViewController alloc]init];
    userCenter.userId = [NSString stringWithFormat:@"%ld",[[viewOfSelf.entity valueForKey:@"id"] integerValue]];
    //    userCenter.isMain = NO;
    [self.navigationController pushViewController:userCenter animated:YES];
}


//私信
- (void)showmessage:(IVTMeUserView *)viewOfSelf{
    
    IVTMyChatContentListViewController * chatVC = [[IVTMyChatContentListViewController alloc] init];
    
    chatVC.chatToUserId = [NSString stringWithFormat:@"%@",viewOfSelf.entity[@"id"]];
    
    chatVC.chatToUserAvatarUrl = viewOfSelf.entity[@"avatar"];

    chatVC.chatToUserSex = viewOfSelf.entity[@"sex"];
    
    chatVC.chatToUserLevel = viewOfSelf.entity[@"level"];
    
    chatVC.chatToUserNickName = viewOfSelf.entity[@"name"] ;
    
    chatVC.chatToUserSignature = viewOfSelf.entity[@"signature"];
    
    [self.navigationController pushViewController:chatVC animated:YES];
    
    user.hidden = YES;
}

- (void)willTerminate:(NSString *)application
{
    LRLog(@"application:%@",application);
    NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setObject:[IVTAccountTool getUserId] forKey:@"username"];
    [paramDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
    [paramDict setObject:self.liveId forKey:@"liveId"];
    
    [[IVTNetworkAPIClient sharedClient] stopPushLive:paramDict success:^(NSDictionary *successData) {
        LRLog(@"关闭");
        [self.player stop];
        [lianChengTimer invalidate];
        lianChengTimer = nil;
        
        CGFloat  eachPrict = [[successData objectForKey:@"meTotal"] floatValue];
        NSInteger totalNumber = [[successData objectForKey:@"audienceTotalNum"] integerValue];
        
        [[XMPPManager sharedInstance] sendMessage:@"已经结束直播" inRoom:[NSString stringWithFormat:@"%@",self.roomJID] type:kQuitRoomType giftId:0 eachPrice:eachPrict totalNumber:totalNumber giftPic:0 msgTime:[IVTThirdFuncTool timeStamp]];
        
        IVTEndLiveViewController *endLiveVC = [[IVTEndLiveViewController alloc] init];
        endLiveVC.mitangTotle = [NSString stringWithFormat:@"%@",[successData objectForKey:@"meTotal"]];
        endLiveVC.audienceTotle = [NSString stringWithFormat:@"%@",[successData objectForKey:@"audienceTotalNum"]];
        
        [self.navigationController pushViewController:endLiveVC  animated:YES];
        
    } error:^(NSDictionary *successData) {
//        
        
    } failure:^(NSError *failureError) {
        LRLog(@"failureError:%@",failureError);
    }];
    
}

#pragma mark ---------------------- 画中画部分 ---------------------初始化金山云Kit(开启推流)
/*
 *
 * 当被要求pip时初始化,开始连线
 *
 */
- (void)initKSYStreamerKitInLiveShowVC
{
//    ksyPushLiveShowObj = [[IVTKSYPushLiveShowObj alloc] init];
//    [ksyPushLiveShowObj initKSYGPUStreamerKit];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end