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

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

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

class _YSLiveAddState extends State<YSLiveAdd> {
  List _titleArray = [
    {'title':'主题','type':1,'key':'title'},
    {'title':'会议密码','type':1,'isClose':true,'key':'password'},
    {'title':'预计培训时间','type':2,'isClose':true,'key1':'expect_start','key2':'expect_end'},
    {'title':'上传封面','type':3,'key':'cover'},
  ];
  final ImagePicker _picker = ImagePicker();
  bool _isEnable = false;

  _checkEnable() {
    bool isEnable = true;
    outLoop:
    for(int i=0;i<_titleArray.length;i++){
      Map item = _titleArray[i];
      if(item['value']==null&&item['isClose']==null){
        isEnable = false;
        continue outLoop;
      }
    }
    _isEnable = isEnable;
    setState(() {});
  }
  @override
  Widget build(BuildContext context) {
    return YSBase2(
      title: '创建视频直播',
      color: Color(0xFFF5F3F0),
      child: Column(
        children: [
          ListView.builder(
            itemBuilder: (context,index){
              Map item = _titleArray[index];
              String title = item['title'];
              int type = item['type'];
              bool isClose = item['isClose'];
              return Column(
                children: [
                  Container(
                    height: 40,
                    alignment: Alignment.centerLeft,
                    child: isClose!=null?Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(title,style: TextStyle(fontSize: 15,color: Color(0xFF606266)),),
                        Switch(value: isClose, onChanged: (value){
                          item['isClose'] = !item['isClose'];
                          setState(() {});
                        },activeColor: Colors.pinkAccent,)
                      ],
                    ):Text(title,style: TextStyle(fontSize: 15,color: Color(0xFF606266)),),
                    padding: EdgeInsets.only(left: 10,right: 10),
                  ),
                  if(item['isClose']!=false)Container(
                    color: Colors.white,
                    padding: EdgeInsets.only(left: 10,right: 10),
                    child: type==1?Container(
                      height: 50,
                      child: CupertinoTextField(
                        placeholder: '请输入$title',
                        style: TextStyle(fontSize: 14,color: Color(0xFF606266)),
                        decoration: BoxDecoration(),
                        onChanged: (value){
                          if(value.isNotEmpty){
                            item['value'] = value;
                          }else{
                            item.remove('value');
                          }
                          _checkEnable();
                        },
                      ),
                    ):type==2?ListView.builder(
                      itemBuilder: (context,indexSub){
                        return GestureDetector(
                          onTap: (){
                            FocusScope.of(context).unfocus();
                            ysShowBottomAlertView(context, YSDatePicker(
                              choose: (value){
                                if(indexSub==0){
                                  item['value1'] = value;
                                }else{
                                  item['value2'] = value;
                                }
                                setState(() {});
                                _checkEnable();
                              },
                              withTime: true,
                            ),isBarr: true);
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Row(
                            children: [
                              Container(
                                width: MediaQuery.of(context).size.width-40,
                                child: Text(item[indexSub==0?'value1':'value2']??'请选择${indexSub==0?'开始':'结束'}时间',style: TextStyle(fontSize: 14,color: Color(0xFF606266)),),
                                alignment: Alignment.centerLeft,
                                height: 50,
                              ),
                              Icon(Icons.keyboard_arrow_down,size: 20,color: Color(0xFF606266),)
                            ],
                          ),
                        );
                      },
                      itemCount: 2,
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      padding: EdgeInsets.all(0),
                    ):type==3?Container(
                      child: GestureDetector(
                        child: Container(
                          height: 80,
                          width: 80,
                          child: item['url']==null?Icon(
                            Icons.add,size: 40,color: Color(0xFFD3D3D3),
                          ):Image.network(
                            item['url'],
                            fit: BoxFit.cover,
                          ),
                          decoration: BoxDecoration(
                            border: Border.all(color: Color(0xFFD3D3D3),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(() {});
                              _checkEnable();
                            });
                          },),isBarr: true);
                        },
                      ),
                      padding: EdgeInsets.only(top: 20,bottom: 20),
                      alignment: Alignment.centerLeft,
                    ):Container(),
                  )
                ],
              );
            },
            itemCount: _titleArray.length,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsets.all(0),
          ),
          GestureDetector(
            onTap: (){
              // Navigator.of(context).push(
              //     CupertinoPageRoute(builder: (context){
              //       return YSLiveAnchor();
              //     })
              // );
              // return;
              if(_isEnable==false)return;
              _postLiveAddData();
            },
            child: Container(
              width: MediaQuery.of(context).size.width-100,
              margin: EdgeInsets.only(top: 15),
              height: 50,
              decoration: BoxDecoration(
                color: _isEnable==true?Colors.pinkAccent:Colors.grey,
                borderRadius: BorderRadius.all(Radius.circular(5))
              ),
              alignment: Alignment.center,
              child: Text('创建直播',style: TextStyle(fontSize: 15,color: Colors.white,fontWeight: FontWeight.bold),),
            ),
          )
        ],
      ),
    );
  }
  _postLiveAddData() async{
    Map request = {};
    _titleArray.forEach((element) {
      if(element['title']=='预计培训时间'){
        if(element['value1']!=null)request[element['key1']] = '${element['value1']}:00';
        if(element['value2']!=null)request[element['key2']] = '${element['value2']}:00';
      }else{
        if(element['value']!=null)request[element['key']] = element['value'];
      }
    });
    Map dict = await ysRequestHttp(context, requestType.post, 'train/live2/create', request);
    if(dict!=null){
      Map data = dict['data'];
      Navigator.pop(context);
      Navigator.of(context).push(
        CupertinoPageRoute(builder: (context){
          return YSLiveAnchor(liveId: data['live_id'],);
        })
      );
    }
  }
}
