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

import 'YSAddChapter.dart';
import 'YSDueDate.dart';
import 'base/YSBase.dart';
import 'base/YSTools.dart';

class YSChapters extends StatefulWidget {
  final bool isFirst;

  const YSChapters({Key key, this.isFirst = false}) : super(key: key);
  @override
  _YSChaptersState createState() => _YSChaptersState();
}

class _YSChaptersState extends State<YSChapters> {
  List _dataArray = [];
  String _expectedTime = '';
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((e){
      _getChapterData();
      getVersionData(context);
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '选择篇章',
      isBack: widget.isFirst==false,
      yschild: ListView.separated(itemBuilder: (context,index){
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            if(index<_dataArray.length+2){
              int chapters = index==0?1:index==1?2:3;
              bool sex = false;
              int childId = 0;
              if(index==1&&_expectedTime.isEmpty){
                Navigator.of(context).push(
                  CupertinoPageRoute(
                    builder: (context){
                      return YSDueDate(dueDate: _expectedTime,);
                    }
                  )
                ).then((value) {
                  if(value!=null){
                    Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
                    _prefs.then((value) => {
                      value.setInt('chapters', chapters-1),
                      value.setInt('childId', childId),
                    });
                    if(widget.isFirst){
                      Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
                          builder: (context){
                            return YSPage();
                          }
                      ), (route) => false);
                    }else{
                      Navigator.of(context).pop({'chapters':chapters,'sex':sex,'child':childId});
                    }
                  }
                });
                return;
              }
              if(index>1){
                sex = _dataArray[index-2]['gender']=='男'?true:false;
                childId = _dataArray[index-2]['id'];
              }
              Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
              _prefs.then((value) => {
                value.setInt('chapters', chapters-1),
                value.setInt('childId', childId),
              });
              if(widget.isFirst){
                Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
                    builder: (context){
                      return YSPage();
                    }
                ), (route) => false);
              }else{
                Navigator.of(context).pop({'chapters':chapters,'sex':sex,'child':childId});
              }
            }else{
              Navigator.of(context).push(
                CupertinoPageRoute(
                  builder: (context){
                    return YSAddChapter();
                  }
                )
              ).then((value){
                if(value=='完成'){
                  _getChapterData();
                }
              });
            }
          },
          onLongPress: (){
            if(index>1 && index<_dataArray.length+2){
              showDialog(
                  context:context,
                  builder:(context){
                    return AlertDialog(
                      title: Text('提示',style: TextStyle(fontSize: 16,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                      content: Text('确认删除此篇章？',style: TextStyle(fontSize: 13,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                      actions: [
                        CupertinoButton(
                          padding: EdgeInsets.all(0),
                          child: Text('取消',style: TextStyle(fontSize: 13,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                          onPressed: (){
                            Navigator.pop(context);
                          },
                        ),
                        CupertinoButton(
                          padding: EdgeInsets.all(0),
                          child: Text('确认',style: TextStyle(fontSize: 13,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                          onPressed: (){
                            Navigator.pop(context);
                            _deleteChapter(index);
                          },
                        ),
                      ],
                    );
                  }
              );
            }
          },
          child: Container(
            height: 123,
            margin: EdgeInsets.only(left: 75,right: 75),
            width: MediaQuery.of(context).size.width-150,
            decoration: BoxDecoration(
              color: Color(0xFFFAF8F5),
              borderRadius: BorderRadius.all(Radius.circular(20))
            ),
            child: index<_dataArray.length+2?Stack(
              children: [
                Image.asset(index==0?'lib/images/beiyunchapter.png':index==1?'lib/images/yunchanchapter.png':
                _dataArray[index-2]['gender']==1?'lib/images/childchapter.png':'lib/images/childchapter2.png'),
                Container(
                  height: 123,
                  width: MediaQuery.of(context).size.width-150,
                  padding: EdgeInsets.only(left: 15,right: 15,top: 20,bottom: 20),
                  child: index>1?Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('宝宝姓名:${_dataArray[index-2]['name']}',style: TextStyle(fontSize: 14,color: Colors.white,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                      Text('性别:${_dataArray[index-2]['gender']==1?'男':'女'}',style: TextStyle(fontSize: 12,color: Colors.white,decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                        maxLines: 2,overflow: TextOverflow.ellipsis,),
                      Text('出生日期:${_dataArray[index-2]['birthday']}',style: TextStyle(fontSize: 10,color: Colors.white,decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                        maxLines: 2,overflow: TextOverflow.ellipsis,),
                    ],
                  ):Container(
                    padding: EdgeInsets.only(top: 10),
                    child: Text(index==0?'备孕篇':'孕产篇',style: TextStyle(fontSize: 14,color: Colors.white,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                  ),
                )
              ],
            ):Container(
              height: 123,
              width: MediaQuery.of(context).size.width-150,
              padding: EdgeInsets.only(left: 15,right: 15,top: 20,bottom: 20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(20)),
                border: Border.all(color: Color(0xFFE6E4E1),width: 1)
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Image(
                    width: 63,
                    height: 43,
                    image: AssetImage('lib/images/addchapter.png'),
                  ),
                  Text('新增儿童',style: TextStyle(fontSize: 13,color: Color(0xFFBCBCBC),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                ],
              ),
            ),
          ),
        );
      }, separatorBuilder: (context,index){
        return Divider(color: Colors.transparent,height: 15,thickness: 15,);
      },
        itemCount: _dataArray.length+3,
        padding: EdgeInsets.only(top: 15,bottom: 15),
      ),
    );
  }

  _getChapterData() async{
    Map dict = await ysRequestHttp(context,requestType.get, 'chapter/list', {});
    if(dict!=null){
      _expectedTime = dict['data']['pregnancy']['expected_time']??'';
      setState(() {
        _dataArray = dict['data']['child'];
      });
    }
  }

  _deleteChapter(int index) async{
    Map dict = await ysRequestHttp(context,requestType.delete, 'child/chapter/delete', {'child_id':_dataArray[index-2]['id']});
    if(dict!=null){
      setState(() {
        _dataArray.removeAt(index-2);
      });
    }
  }
}



