import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:will_play/views/palRoom/PalRoom.dart';

class PartyPage extends StatefulWidget {
  PartyPage({Key? key}) : super(key: key);

  @override
  State<PartyPage> createState() => _PartyPageState();
}

class _PartyPageState extends State<PartyPage> {
  final _search = TextEditingController();
  final _tabDataList = [
    Tab(text: '关注'),
    Tab(text: '推荐'),
    Tab(text: '相亲'),
    Tab(text: 'KTV'),
    Tab(text: '交友'),
    Tab(text: '音乐'),
  ];

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 1, // 默认选中
      length: 6,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          elevation: 0, // z轴阴影
          leading: null,
          titleSpacing: 10, // 标题与其他控件的间隔
          backgroundColor: Colors.white,
          title: Container(
            height: 35,
            margin: EdgeInsetsDirectional.only(end: 25),
            padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
            decoration: BoxDecoration(
              color: Color.fromRGBO(247, 247, 247, 1),
              borderRadius: BorderRadius.circular(30),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  child: Padding(
                    padding: EdgeInsets.only(right: 5),
                    child: Image.asset(
                      'images/party/search.png',
                      width: 17.0,
                      height: 17.0,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: TextField(
                    controller: _search,
                    decoration: InputDecoration(
                      isDense: true,
                      border: InputBorder.none,
                      hintText: '搜索房间号',
                      hintStyle: TextStyle(
                        fontSize: 12,
                        color: Color.fromRGBO(203, 203, 203, 1),
                      ),
                    ),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.black,
                    ),
                    textInputAction: TextInputAction.search, // 键盘右下角图标
                  ),
                ),
              ],
            ),
          ),
          actions: [
            IconButton(
              onPressed: () {
                Navigator.pushNamed(context, 'CreateRoom');
              },
              icon: Image.asset(
                'images/party/create.png',
                fit: BoxFit.cover,
                width: 22.0,
                height: 22.0,
              ),
            ),
          ],
          bottom: TabBar(
            // isScrollable: true,
            indicatorSize: TabBarIndicatorSize.label, // 指示器大小计算方式
            indicatorColor: Color.fromRGBO(255, 255, 255, 0), // 指示器颜色
            labelColor: Colors.black, // 选中label颜色
            labelStyle: TextStyle(fontSize: 18), // 选中label的Style
            unselectedLabelStyle: TextStyle(fontSize: 14), // 未选中label的Style
            unselectedLabelColor:
                Color.fromRGBO(153, 153, 153, 1), // 未选中label颜色
            tabs: _tabDataList,
            enableFeedback: true,
            onTap: (index) {
              print(_tabDataList[index]);
            },
          ),
        ),
        body: TabBarView(
          children: [
            ViewsWidget(),
            ViewsWidget(),
            ViewsWidget(),
            ViewsWidget(),
            ViewsWidget(),
            ViewsWidget(),
          ],
        ),
      ),
    );
  }
}

// tab视图页
class ViewsWidget extends StatefulWidget {
  ViewsWidget({Key? key}) : super(key: key);

  @override
  State<ViewsWidget> createState() => _ViewsWidgetState();
}

class _ViewsWidgetState extends State<ViewsWidget> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          Banner(),
          Lists(),
        ],
      ),
    );
  }
}

// 横幅组件
class Banner extends StatefulWidget {
  Banner({Key? key}) : super(key: key);

  @override
  State<Banner> createState() => _BannerState();
}

class _BannerState extends State<Banner> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.fromLTRB(15, 15, 15, 0),
        child: GestureDetector(
          child: Image.asset('images/party/banner.png'),
          onTap: () {
            print('Banner on tap');
          },
        ),
      ),
    );
  }
}

// 列表组件
class Lists extends StatefulWidget {
  Lists({Key? key}) : super(key: key);

  @override
  State<Lists> createState() => _ListsState();
}

class _ListsState extends State<Lists> {
  final List _list = [
    {
      "photo": "images/party/photo1.png",
      "name": "小明",
      "num": "12",
      "title": "今日听君歌一曲",
      "type": "music",
      "sex": "0",
      "role": ClientRole.Broadcaster,
    },
    {
      "photo": "images/party/photo1.png",
      "name": "小红",
      "num": "12",
      "title": "成年人的避风港",
      "type": "pal",
      "sex": "1",
      "role": ClientRole.Audience,
    },
    {
      "photo": "images/party/photo1.png",
      "name": "小黑",
      "num": "12",
      "title": "今日听君歌一曲",
      "type": "auction",
      "sex": "0",
      "role": ClientRole.Audience,
    },
    {
      "photo": "images/party/photo1.png",
      "name": "小白",
      "num": "122",
      "title": "今日听君歌一曲",
      "type": "family",
      "sex": "0",
      "role": ClientRole.Audience,
    },
  ];

  // 判断是否开启权限方法
  Future<void> _handleCameraAndMic(Permission permission) async {
    PermissionStatus status = await permission.request();
    print('权限状态$status');
    if (!status.isGranted) {
      openAppSettings();
    }
  }

  // 页面跳转方法
  Future<void> onJoin(name, role) async {
    await _handleCameraAndMic(Permission.camera);
    await _handleCameraAndMic(Permission.microphone);

    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PalRoomPage(
          userName: name,
          channelName: 'call',
          role: role,
        ),
      ),
    );
  }

  List<Widget> _tempList() {
    var tempList = _list.map((value) {
      return GestureDetector(
        onTap: () => onJoin(value['name'], value['role']),
        child: Container(
          height: 75,
          padding: EdgeInsets.all(5),
          margin: EdgeInsets.fromLTRB(15, 30, 15, 0),
          width: double.infinity,
          decoration: BoxDecoration(
            color: Color.fromRGBO(255, 255, 255, 1),
            borderRadius: BorderRadius.all(Radius.circular(50)),
            boxShadow: [
              BoxShadow(
                  color: Color.fromRGBO(0, 0, 0, 0.1),
                  offset: Offset(0.0, 1.0), // 阴影xy轴偏移量
                  blurRadius: 1.0, // 阴影模糊程度
                  spreadRadius: 1.0 // 阴影扩散程度
                  )
            ],
          ),
          child: Row(
            children: [
              ClipOval(
                child: Image.asset(
                  value['photo'],
                  width: 65,
                  height: 65,
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                  flex: 1,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        children: [
                          typeElement(type: value['type']),
                          Container(
                            child: Text(
                              value['title'],
                              style: TextStyle(
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                  fontSize: 16),
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 9),
                      Row(
                        children: [
                          Image.asset(
                            'images/party/live.png',
                            width: 17,
                            height: 18,
                          ),
                          SizedBox(width: 5),
                          Text(
                            value["num"] + '人',
                            style: TextStyle(
                                color: Color.fromRGBO(153, 153, 153, 1),
                                fontSize: 12),
                          )
                        ],
                      ),
                    ],
                  )),
            ],
          ),
        ),
      );
    });
    return tempList.toList();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: _tempList(),
    );
  }
}

// 房间类型标签小组件
class typeElement extends StatelessWidget {
  String type;

  var typeData = {
    "music": {
      'title': "音乐",
      'color': [
        Color.fromRGBO(207, 167, 248, 1),
        Color.fromRGBO(133, 157, 254, 1),
      ],
    },
    "pal": {
      "title": "交友",
      'color': [
        Color.fromRGBO(207, 167, 248, 1),
        Color.fromRGBO(133, 157, 254, 1),
      ],
    },
    "auction": {
      "title": "拍卖",
      "color": [
        Color.fromRGBO(249, 163, 125, 1),
        Color.fromRGBO(251, 218, 137, 1),
      ]
    },
    "family": {
      'title': "家族",
      "color": [
        Color.fromRGBO(85, 221, 236, 1),
        Color.fromRGBO(66, 224, 154, 1),
      ]
    },
  };

  var textData = {"music": '音乐', "pal": '交友', "auction": '拍卖', "family": '家族'};

  var colorData = {
    "music": [
      Color.fromRGBO(207, 167, 248, 1),
      Color.fromRGBO(133, 157, 254, 1),
    ],
    "pal": [
      Color.fromRGBO(254, 174, 205, 1),
      Color.fromRGBO(247, 111, 162, 1),
    ],
    "auction": [
      Color.fromRGBO(249, 163, 125, 1),
      Color.fromRGBO(251, 218, 137, 1),
    ],
    "family": [
      Color.fromRGBO(85, 221, 236, 1),
      Color.fromRGBO(66, 224, 154, 1),
    ],
  };

  typeElement({Key? key, this.type = ''}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 32,
      height: 16,
      margin: EdgeInsets.only(right: 5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(8),
        ),
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: colorData[type] ?? [],
        ),
      ),
      child: Text(
        textData[type] ?? "",
        textAlign: TextAlign.center,
        style: TextStyle(color: Colors.white, fontSize: 10),
      ),
    );
  }
}
