import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';

import '../live/YSLiveAnchor.dart';

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

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

class _YSMineLiveAddState extends State<YSMineLiveAdd> {
  List _titleArray = [
    {'title':'主题','type':1,'key':'title'},
    {'title':'密码','type':1,'key':'password'},
    {'title':'封面','type':3,'key':'cover'},
    {'title':'预告','type':2,'key':'expect_start','isClose':false},
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          width: ysWidth(context),
          height: ysHeight(context),
          decoration: BoxDecoration(
            image: DecorationImage(image: AssetImage('lib/images/图.png'),fit: BoxFit.fill)
          ),
          padding: EdgeInsets.only(top: ysTOP(context),left: 10,right: 10,bottom: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.only(top: 10,left: 10,bottom: 30),
                child: GestureDetector(
                  onTap: (){
                    Navigator.pop(context);
                  },
                  child: Icon(Icons.close,size: 30,color: Colors.white,),
                )
              ),
              ListView.separated(
                itemBuilder: (context,index){
                  Map item = _titleArray[index];
                  bool isColumn = item['title']=='预告';
                  bool isMust = item['title']=='主题'||item['title']=='封面';
                  bool isClose = item['isClose']??false;
                  return Container(
                    padding: isColumn?EdgeInsets.all(0):EdgeInsets.only(top: 15,bottom: 15),
                    child: LayoutBuilder(
                      builder: (context,conSize){
                        return isColumn?Column(
                          children: [
                            Container(
                              alignment: Alignment.centerLeft,
                              decoration: BoxDecoration(
                                border: Border(bottom: BorderSide(color: Colors.white,width: 0.1))
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(item['title'],style: TextStyle(fontSize: 15,color: Colors.white),),
                                  Switch(value: isClose, onChanged: (value){
                                    item['isClose'] = !item['isClose'];
                                    setState(() {});
                                  },activeColor: Colors.pinkAccent,)
                                ],
                              ),
                              padding: EdgeInsets.only(left: 10,right: 10),
                            ),
                            if(isClose)Container(
                              padding: EdgeInsets.only(left: 10,right: 10),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  border: Border(bottom: BorderSide(color: Colors.white,width: 0.1))
                              ),
                              child: GestureDetector(
                                onTap: (){
                                  FocusScope.of(context).unfocus();
                                  ysShowBottomAlertView(context, YSDatePicker(
                                    choose: (value){
                                      item['value'] = value;
                                      setState(() {});
                                    },
                                    withTime: true,
                                  ),isBarr: true);
                                },
                                behavior: HitTestBehavior.opaque,
                                child: Container(
                                  width: conSize.maxWidth-40,
                                  child: RichText(
                                    text: TextSpan(
                                      text: '${item['value']??'请选择预约时间'}  ',
                                      style: TextStyle(fontSize: 14,color: Colors.white),
                                      children: [
                                        WidgetSpan(child: Icon(Icons.calendar_today,size: 20,color: Colors.white,))
                                      ]
                                    ),
                                  ),
                                  alignment: Alignment.center,
                                  height: 50,
                                ),
                              ),
                            )
                          ],
                        ):Row(
                          children: [
                            Container(
                              width: 80,
                              child: RichText(
                                text: TextSpan(
                                  style: TextStyle(fontSize: 15,color: Colors.white),
                                  children: [
                                    TextSpan(
                                      text: '*',style: TextStyle(color: isMust?Color(0xFFE26085):Colors.transparent),
                                    ),
                                    TextSpan(
                                      text: item['title'],
                                    )
                                  ]
                                ),
                              ),
                            ),
                            Container(
                              width: conSize.maxWidth-80,
                              child: item['title']=='封面'?GestureDetector(
                                child: Container(
                                  height: 80,
                                  width: 80,
                                  child: item['url']==null?Icon(
                                    Icons.add,size: 40,color: Colors.white,
                                  ):Image.network(
                                    item['url'],
                                    fit: BoxFit.cover,
                                  ),
                                  decoration: BoxDecoration(
                                      border: Border.all(color: Colors.white,width: 0.2)
                                  ),
                                ),
                                onTap: (){
                                  ysShowBottomAlertView(context, YSChooseFileView(valueSetter: (value){
                                    ysUploadFile(context,path: value.path,type: 'diary',setter: (result){
                                      item['value'] = result['path'];
                                      item['url'] = result['url'];
                                      setState(() {});
                                    });
                                  },),isBarr: true);
                                },
                              ):CupertinoTextField(
                                placeholder: '请输入${item['title']}',
                                decoration: BoxDecoration(
                                  color: Colors.transparent,
                                ),
                                style: TextStyle(fontSize: 15,color: Colors.white),
                                placeholderStyle: TextStyle(fontSize: 15,color: Colors.white),
                                onChanged: (value){
                                  if(value.isNotEmpty){
                                    item['value'] = value;
                                  }else{
                                    item.remove('value');
                                  }
                                },
                              ),
                              alignment: Alignment.centerLeft,
                            )
                          ],
                        );
                      },
                    ),
                  );
                },
                separatorBuilder: (context,index){
                  return Divider(height: 0.1,thickness: 0.1,color: Colors.white,);
                },
                itemCount: _titleArray.length,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                padding: EdgeInsets.all(0),
              ),
              GestureDetector(
                onTap: () async{
                  Map request = {};
                  bool isSubmit = true;
                  bool isSelect = true;
                  _titleArray.forEach((element) {
                    if(isSubmit==false)return;
                    if(element['title']=='预告'){
                      if(element['isClose']==true){
                        isSelect = false;
                        if(element['value']!=null){
                          request['expect_start'] = '${element['value']}:${'${DateTime.now().second}'.padLeft(2,'0')}';
                          DateTime time = DateTime.parse('${request['expect_start']}');
                          if(time.isBefore(DateTime.now())){
                            isSubmit = false;
                            ysFlutterToast(context, '开始时间不能早于当前时间');
                            return;
                          }
                          DateTime end = time.add(Duration(hours: 3));
                          String endStr = end.year.toString()+'-'+end.month.toString().padLeft(2,'0')+'-'+end.day.toString().padLeft(2,'0')+' '+
                              '${end.hour}'.padLeft(2,'0')+':'+'${end.minute}'.padLeft(2,'0')+':'+'${end.second}'.padLeft(2,'0');
                          request['expect_end'] = endStr;
                        }else{
                          isSubmit = false;
                          ysFlutterToast(context, '请选择预告时间');
                          return;
                        }
                      }else{
                        isSelect = true;
                        DateTime start = DateTime.now().add(Duration(seconds: 10));
                        String startStr = start.year.toString()+'-'+start.month.toString().padLeft(2,'0')+'-'+start.day.toString().padLeft(2,'0')+' '+
                            '${start.hour}'.padLeft(2,'0')+':'+'${start.minute}'.padLeft(2,'0')+':'+'${start.second}'.padLeft(2,'0');
                        request['expect_start'] = startStr;
                        DateTime time = DateTime.parse('${request['expect_start']}');
                        DateTime end = time.add(Duration(hours: 3));
                        String endStr = end.year.toString()+'-'+end.month.toString().padLeft(2,'0')+'-'+end.day.toString().padLeft(2,'0')+' '+
                            '${end.hour}'.padLeft(2,'0')+':'+'${end.minute}'.padLeft(2,'0')+':'+'${end.second}'.padLeft(2,'0');
                        request['expect_end'] = endStr;
                      }
                    }else if(element['title']=='主题'){
                      if(element['value']!=null){
                        request[element['key']] = element['value'];
                      }else{
                        isSubmit = false;
                        ysFlutterToast(context, '请输入主题');
                        return;
                      }
                    }else{
                      if(element['value']!=null)request[element['key']] = element['value'];
                    }
                  });
                  if(isSubmit==false)return;
                  Map dict = await ysRequestHttp(context, requestType.post, 'train/live2/create', request);
                  if(dict!=null){
                    Map data = dict['data'];
                    Navigator.of(context).push(
                        CupertinoPageRoute(builder: (context){
                          return YSMineLiveAddDone(liveId: data['live_id'],title: request['title'],isSelect: isSelect,);
                        })
                    );
                  }
                },
                behavior: HitTestBehavior.opaque,
                child: Container(
                  margin: EdgeInsets.only(top: 100),
                  height: 44,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    color: Color(0xFFE36085)
                  ),
                  alignment: Alignment.center,
                  child: Text('创建直播',style: TextStyle(color: Colors.white,fontSize: 18),),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class YSMineLiveAddDone extends StatefulWidget {
  final liveId;
  final String title;
  final bool isSelect;
  const YSMineLiveAddDone({Key key, this.liveId, this.title = '', this.isSelect = false}) : super(key: key);

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

class _YSMineLiveAddDoneState extends State<YSMineLiveAddDone> {
  bool _isSelect = false;
  @override
  void initState() {
    _isSelect = widget.isSelect;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          width: ysWidth(context),
          height: ysHeight(context),
          decoration: BoxDecoration(
              image: DecorationImage(image: AssetImage('lib/images/图.png'),fit: BoxFit.fill)
          ),
          padding: EdgeInsets.only(top: ysTOP(context),left: 10,right: 10,bottom: 10),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                  padding: EdgeInsets.only(top: 10,left: 10,bottom: 30),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        onTap: (){
                          Navigator.pop(context);
                        },
                        child: Icon(Icons.close,size: 30,color: Colors.white,),
                      ),
                      Text('创建完成',style: TextStyle(fontSize: 16,color: Colors.white),),
                      Icon(Icons.close,size: 30,color: Colors.transparent,),
                    ],
                  )
              ),
              Container(
                padding: EdgeInsets.only(left: 40,right: 20,top: 300),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('${widget.title}直播间已创建成功， \n是否进入直播间？',style: TextStyle(fontSize: 18,color: Colors.white,fontWeight: FontWeight.bold),),
                    Container(
                      padding: EdgeInsets.only(top: 20,bottom: 20),
                      child: Row(
                        children: [
                          GestureDetector(
                            child: Icon(_isSelect?Icons.check_box:Icons.check_box_outline_blank,size: 20,color: Colors.white,),
                            onTap: (){
                              _isSelect = !_isSelect;
                              setState(() {});
                            },
                          ),
                          Text(' 立即推流',style: TextStyle(fontSize: 18,color: Colors.white,fontWeight: FontWeight.bold),),
                        ],
                      ),
                    ),
                    Text('注意：选择开启推流，则会立即进入直播模式',style: TextStyle(fontSize: 12,color: Colors.white),),
                  ],
                )
              ),
              GestureDetector(
                onTap: (){
                  Navigator.of(context).push(
                      CupertinoPageRoute(builder: (context){
                        return YSLiveAnchor(liveId: widget.liveId,isSelect: _isSelect,);
                      })
                  );
                },
                child: Container(
                  margin: EdgeInsets.only(top: 60),
                  height: 44,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                      color: Color(0xFFE36085)
                  ),
                  alignment: Alignment.center,
                  child: Text('进入直播间',style: TextStyle(color: Colors.white,fontSize: 18),),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

