import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:flutterappfuyou/code/live/YSLiveAdd.dart';
import 'package:flutterappfuyou/code/live/YSLiveDetail.dart';
import 'package:flutterappfuyou/code/live/YSVideoDetail.dart';

class YSLive extends StatefulWidget {
  const YSLive({Key key}) : super(key: key);

  @override
  _YSLiveState createState() => _YSLiveState();
}

class _YSLiveState extends State<YSLive> with SingleTickerProviderStateMixin{
  List _titleArray = [
    {'title':'视频','type':'1'},
    {'title':'培训','type':'2'}
  ];
  TabController _tabController;
  bool _isChange = false;
  @override
  void initState() {
    _tabController = TabController(
        vsync: this,
        length: _titleArray.length
    );
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: Scaffold(
        backgroundColor: Color(0xFFFAF8F5),
        body: Container(
          width: MediaQuery.of(context).size.width,
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  height: MediaQuery.of(context).padding.top+50,
                  color: Colors.white,
                  padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
                  child: Row(
                    children: [
                      Container(
                        width: MediaQuery.of(context).size.width-100,
                        height: 50,
                        alignment: Alignment.center,
                        child: Text('视频培训',style: TextStyle(fontSize: 20,color: Colors.black),),
                        margin: EdgeInsets.only(left: 50),
                      ),
                      Container(
                        width: 50,
                        // child: PopupMenuButton<String>(
                        //   icon: Icon(Icons.more_horiz),
                        //   onSelected: (value){
                        //     if(value=='1'){
                        //       Navigator.of(context,rootNavigator: true).push(
                        //         CupertinoPageRoute(builder: (context,){
                        //           return YSLiveAdd();
                        //         })
                        //       ).then((value) {
                        //         if(value!=null){
                        //           _isChange = !_isChange;
                        //           setState(() {});
                        //         }
                        //       });
                        //     }
                        //   },
                        //   itemBuilder: (context) {
                        //     return _moreArray.map((e) {
                        //       return PopupMenuItem<String>(
                        //         value: e['type'],
                        //         child: Text('${e['title']}',style: TextStyle(fontSize: 12),),
                        //       );
                        //     }).toList();
                        //   },
                        // )
                      )
                    ],
                  ),
                ),
                DefaultTabController(
                  length: _titleArray.length,
                  child: Column(
                    children: [
                      Container(
                        height: 40,
                        color: Colors.white,
                        width: MediaQuery.of(context).size.width,
                        child: TabBar(
                          controller: _tabController,
                          isScrollable: true,
                          indicatorColor: Color(0xFFFA4444),
                          labelColor: Color(0xFFFA4444),
                          indicatorWeight: 2,
                          indicatorSize: TabBarIndicatorSize.label,
                          labelStyle: TextStyle(fontSize: 15),
                          unselectedLabelColor: Color(0xFF5D6978),
                          tabs: _titleArray.map((f) {
                            return Tab(text: '${f['title']}');
                          }).toList(),
                        )
                      ),
                      Container(
                        height: MediaQuery.of(context).size.height-MediaQuery.of(context).padding.top-140,
                        width: MediaQuery.of(context).size.width,
                        child: TabBarView(
                          controller: _tabController,
                          children: _titleArray.map((f) {
                            return _isChange?Container(
                              child: YSLiveView(f: f,callback: (){
                                _isChange = !_isChange;
                                setState(() {});
                              },),
                            ):YSLiveView(f: f,callback: (){
                              _isChange = !_isChange;
                              setState(() {});
                            },);
                          }).toList(),
                        ),
                      ),
                    ],
                  )
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class YSLiveView extends StatefulWidget {
  final Map f;
  final VoidCallback callback;
  const YSLiveView({Key key, this.f, this.callback}) : super(key: key);

  @override
  _YSLiveViewState createState() => _YSLiveViewState();
}

class _YSLiveViewState extends State<YSLiveView> {
  List _dataArray = [];
  TextEditingController _editingController = TextEditingController();
  @override
  void dispose() {
    _editingController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return YSRefreshLoad(
      url: widget.f['type']=='1'?'train/video/list':'train/live2/list',
      request: {},
      postData: (value){
        _dataArray = value;
        setState(() {});
      },
      dataWidget: SingleChildScrollView(
        child: GridView.builder(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            childAspectRatio: 0.8,
            crossAxisCount: 2,
            mainAxisSpacing: 10,
            crossAxisSpacing: 10
        ), itemBuilder: (context,index){
          Map item = _dataArray[index];
          return GestureDetector(
            onTap: () async{
              if(widget.f['type']=='2'&&item['have_password']==true){
                ysShowCenterAlertView(context, YSLivePassWordView(
                  editingController: _editingController,
                  callback: () async{
                    Map request = {'live_id':item['id']};
                    request['password'] = _editingController.text;
                    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'train/live2/info', request);
                    if(dict!=null){
                      Navigator.of(context,rootNavigator: true).push(
                          CupertinoPageRoute(builder: (context){
                            return YSLiveDetail(liveId: item['id'],passWord: _editingController.text,);
                          })
                      ).then((value) {
                        if(value!=null){
                          widget.callback();
                        }
                      });
                    }
                  },
                ));
              }else{
                Navigator.of(context,rootNavigator: true).push(
                    CupertinoPageRoute(builder: (context){
                      return widget.f['type']=='1'?YSVideoDetail(videoId: item['id'],):YSLiveDetail(liveId: item['id']);
                    })
                );
              }
            },
            behavior: HitTestBehavior.opaque,
            child: ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(5)),
              child: Container(
                color: Colors.white,
                child: LayoutBuilder(
                  builder: (context,conSize){
                    return widget.f['type']=='1'?Column(
                      children: [
                        Container(
                          height: conSize.maxHeight*0.6,
                          child: Stack(
                            children: [
                              Image.network(item['cover'],fit: BoxFit.cover,width: double.infinity,height: double.infinity,),
                              if(item['is_recommend']==true)Image.asset('lib/images/tuijian.png',height: 40,width: 40,),
                            ],
                          )
                        ),
                        Container(
                          height: conSize.maxHeight*0.25,
                          decoration: BoxDecoration(
                              border: Border(bottom: BorderSide(color: Colors.grey,width: 0.1))
                          ),
                          padding: EdgeInsets.only(left: 5,right: 5),
                          child: RichText(
                            text: TextSpan(
                                style: TextStyle(fontSize: 12,color: Color(0xFF707070)),
                                children: [
                                  // if(item['is_recommend']==true)WidgetSpan(child: Container(
                                  //   padding: EdgeInsets.only(left: 5,right: 5,top: 2,bottom: 2),
                                  //   decoration: BoxDecoration(
                                  //       border: Border.all(color: Colors.red,width: 0.5),
                                  //       color: Colors.red.withOpacity(0.3)
                                  //   ),
                                  //   child: Text('推荐',style: TextStyle(fontSize: 12,color: Colors.red),),
                                  // ),alignment: PlaceholderAlignment.middle),
                                  TextSpan(text: ' ${item['title']}')
                                ]
                            ),
                            maxLines: 1,
                          ),
                          alignment: Alignment.centerLeft,
                        ),
                        Container(
                          height: conSize.maxHeight*0.15,
                          child: RichText(
                            text: TextSpan(
                                style: TextStyle(fontSize: 12,color: Color(0xFF707070)),
                                children: [
                                  WidgetSpan(child: Icon(Icons.remove_red_eye_outlined,size: 15,color: Color(0xFF707070))),
                                  TextSpan(text: ' ${item['views']??'0'}')
                                ]
                            ),
                          ),
                          padding: EdgeInsets.only(left: 5,right: 5),
                          alignment: Alignment.centerLeft,
                        )
                      ],
                    ):Column(
                      children: [
                        Container(
                          height: conSize.maxHeight*0.5,
                          child: Image.network(item['cover'],fit: BoxFit.cover,height: double.infinity,width: double.infinity,),
                        ),
                        Container(
                          height: conSize.maxHeight*0.15,
                          child: RichText(
                            text: TextSpan(
                                style: TextStyle(fontSize: 12,color: Color(0xFF707070)),
                                children: [
                                  // WidgetSpan(child: Container(
                                  //   padding: EdgeInsets.only(left: 5,right: 5,top: 2,bottom: 2),
                                  //   decoration: BoxDecoration(
                                  //       border: Border.all(color: Colors.red,width: 0.5),
                                  //       color: Colors.red.withOpacity(0.3)
                                  //   ),
                                  //   child: Text('培训中',style: TextStyle(fontSize: 12,color: Colors.red),),
                                  // )),
                                  TextSpan(text: ' ${item['title']}')
                                ]
                            ),
                            maxLines: 1,
                          ),
                          padding: EdgeInsets.only(left: 5,right: 5,top: 10),
                          alignment: Alignment.centerLeft,
                        ),
                        Container(
                          height: conSize.maxHeight*0.15,
                          child: RichText(
                            text: TextSpan(
                                style: TextStyle(fontSize: 12,color: Color(0xFF707070)),
                                children: [
                                  WidgetSpan(child: Icon(Icons.person,size: 15,color: Color(0xFF707070))),
                                  TextSpan(text: ' ${item['watch_number']}')
                                ]
                            ),
                          ),
                          padding: EdgeInsets.only(left: 5,right: 5),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              border: Border(bottom: BorderSide(color: Colors.grey,width: 0.2))
                          ),
                        ),
                        Container(
                          height: conSize.maxHeight*0.2,
                          child: RichText(
                            text: TextSpan(
                                style: TextStyle(fontSize: 12,color: Color(0xFF707070)),
                                children: [
                                  WidgetSpan(child: ClipRRect(
                                    child: Image.network(item['cast_avatar'],height: 15,width: 15,),
                                    borderRadius: BorderRadius.all(Radius.circular(50)),
                                  )),
                                  TextSpan(text: ' ${item['cast_name']}'),
                                  TextSpan(text: ' ${item['expect_start']??''}',style: TextStyle(color: Color(0xFFD3D3D3)))
                                ]
                            ),
                          ),
                          padding: EdgeInsets.only(left: 5,right: 5),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              border: Border(bottom: BorderSide(color: Colors.grey,width: 0.2))
                          ),
                        )
                      ],
                    );
                  },
                ),
              ),
            ),
          );
        },padding: EdgeInsets.all(10),itemCount: _dataArray.length,physics: NeverScrollableScrollPhysics(),shrinkWrap: true,),
      ),
    );
  }
}

class YSLivePassWordView extends StatelessWidget {
  final TextEditingController editingController;
  final VoidCallback callback;
  const YSLivePassWordView({Key key, this.editingController, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(5)),
        child: Container(
          height: 200,
          width: MediaQuery.of(context).size.width-100,
        color: Colors.white,
          child: Column(
            children: [
              Container(
                height: 50,
                decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(color: Colors.black,width: 0.1))
                ),
                alignment: Alignment.center,
                child: Text('提示',style: TextStyle(fontSize: 14,color: Colors.black,decoration: TextDecoration.none),),
              ),
              Container(
                height: 100,
                padding: EdgeInsets.all(20),
                child: CupertinoTextField(
                  padding: EdgeInsets.only(left: 20,right: 20),
                  placeholder: '请输入房间密码',
                  style: TextStyle(fontSize: 14,color: Colors.black,decoration: TextDecoration.none),
                  textAlign: TextAlign.center,
                  controller: editingController,
                  maxLength: 10,
                ),
              ),
              Row(
                children: [
                  GestureDetector(
                    onTap: (){
                      Navigator.pop(context);
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      width: (MediaQuery.of(context).size.width-100)/2,
                      height: 50,
                      decoration: BoxDecoration(
                        border: Border(top: BorderSide(color: Colors.black,width: 0.1)),
                        color: Colors.white,
                      ),
                      alignment: Alignment.center,
                      child: Text('取消',style: TextStyle(fontSize: 14,color: Colors.grey,decoration: TextDecoration.none),),
                    ),
                  ),
                  GestureDetector(
                    onTap: (){
                      Navigator.pop(context);
                      if(editingController.text.isEmpty){
                        ysFlutterToast(context, '请输入房间密码');
                        return;
                      }
                      callback();
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      width: (MediaQuery.of(context).size.width-100)/2,
                      height: 50,
                      decoration: BoxDecoration(
                        border: Border(top: BorderSide(color: Colors.black,width: 0.1)),
                        color: Colors.blue,
                      ),
                      alignment: Alignment.center,
                      child: Text('确定',style: TextStyle(fontSize: 14,color: Colors.white,decoration: TextDecoration.none),),
                    ),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

