import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'base/YSBase.dart';
import 'base/YSTools.dart';
import 'base/YSNetWorking.dart';

class YSAddChapter extends StatefulWidget {
  final bool isEdit;
  const YSAddChapter({Key key, this.isEdit}) : super(key: key);
  @override
  _YSAddChapterState createState() => _YSAddChapterState();
}

class _YSAddChapterState extends State<YSAddChapter> {
  int childId = 0;
  TextEditingController _name = TextEditingController();
  TextEditingController _number = TextEditingController();
  String birthday='';
  String sex='';
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      if(widget.isEdit==true){
        _getChildData();
      }
    });
    super.initState();
  }
  @override
  void dispose() {
    _number.dispose();
    _name.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '宝宝出生了',
      yschild: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 400,
              child: ListView.separated(
                itemBuilder: (context,index){
                  return Container(
                    padding: EdgeInsets.only(left: 15,right: 15),
                    height: 65,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(index==0?'  宝宝姓名':index==1?'  宝宝生日':index==2?'  宝宝性别':'  保健册号',style: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                        Container(
                          height: 40,
                          margin: EdgeInsets.only(top: 8),
                          padding: EdgeInsets.only(left: 15,right: 15),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(20)),
                            border: Border.all(color: Color(0xFFD7D7D7),width: 0.5)
                          ),
                          child: index==0||index==3?CupertinoTextField(
                            placeholder: '请输入${index==0?'宝宝姓名':'保健册号'}',
                            style: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                            decoration: BoxDecoration(),
                            placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                            controller: index==0?_name:_number,
                          ):CupertinoButton(
                            padding: EdgeInsets.all(0),
                            child: Container(
                              width: MediaQuery.of(context).size.width-30,
                              child: Text(index==1?birthday.isEmpty?'请选择宝宝生日':birthday:sex.isEmpty?'请选择宝宝性别':sex,
                                style: TextStyle(fontSize: 14,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                            ),
                            onPressed: (){
                              if(index==1){
                                ysDatePicker(context, (value){
                                  setState(() {
                                    birthday = value;
                                  });
                                });
                                // showModalBottomSheet(context: context,builder: (context){
                                //   return YSDatePicker(
                                //     choose: (value){
                                //       setState(() {
                                //         birthday = value;
                                //       });
                                //     },
                                //   );
                                // },backgroundColor: Colors.transparent);
                              }else{
                                showDialog(context: context, builder: (context){
                                  return Dialog(
                                    backgroundColor: Colors.transparent,
                                    child: Container(
                                      height: 150,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.all(Radius.circular(10)),
                                        color: Colors.white,
                                      ),
                                      child: Column(
                                        children: [
                                          Container(
                                            height: 50,
                                            alignment: Alignment.centerLeft,
                                            padding: EdgeInsets.only(left: 20,right: 20),
                                            child: Text('选择性别',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.w600)),
                                          ),
                                          CupertinoButton(
                                            padding: EdgeInsets.all(0),
                                            child: Container(
                                              height: 50,
                                              alignment: Alignment.centerLeft,
                                              padding: EdgeInsets.only(left: 20,right: 20),
                                              child: Text('男',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                            ),
                                            onPressed: (){
                                              Navigator.pop(context);
                                              setState(() {
                                                sex = '男';
                                              });
                                            },
                                          ),
                                          CupertinoButton(
                                            padding: EdgeInsets.all(0),
                                            child: Container(
                                              height: 50,
                                              alignment: Alignment.centerLeft,
                                              padding: EdgeInsets.only(left: 20,right: 20),
                                              child: Text('女',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                            ),
                                            onPressed: (){
                                              Navigator.pop(context);
                                              setState(() {
                                                sex = '女';
                                              });
                                            },
                                          )
                                        ],
                                      ),
                                    ),
                                  );
                                });

                              }
                            },
                          ),
                        )
                      ],
                    ),
                  );
                },
                separatorBuilder: (context,index){
                  return Divider(height: 20,thickness: 20,color: Colors.transparent,);
                },
                itemCount: 4,
                padding: EdgeInsets.only(top: 20),
                physics: NeverScrollableScrollPhysics(),
              ),
            ),
            CupertinoButton(
              padding: EdgeInsets.all(0),
              child: Container(
                height: 40,
                margin: EdgeInsets.only(left: 75),
                width: MediaQuery.of(context).size.width-150,
                decoration: BoxDecoration(
                  color: Color(0xFFDB5278),
                  borderRadius: BorderRadius.all(Radius.circular(20))
                ),
                child: Center(child: Text('保存',style: TextStyle(fontSize: 16,color: Colors.white,decoration: TextDecoration.none,fontWeight: FontWeight.normal),)),
              ),
              onPressed: (){
                _addChapterData();
              },
            )
          ],
        ),
      ),
    );
  }

  _addChapterData() async{
    if(_name.text.isEmpty){
      ysFlutterToast(context, '请输入宝宝姓名');
      return;
    }
    if(birthday.isEmpty){
      ysFlutterToast(context, '请选择宝宝生日');
      return;
    }
    if(sex.isEmpty){
      ysFlutterToast(context, '请选择宝宝性别');
      return;
    }
    if(_number.text.isEmpty){
      ysFlutterToast(context, '请输入保健册号');
      return;
    }
    DateTime now = DateTime.now();
    DateTime expected = DateTime.parse('$birthday ${now.hour.toString().padLeft(2,'0')}:${now.minute.toString().padLeft(2,'0')}:${now.second.toString().padLeft(2,'0')}');
    bool isBefore = now.isBefore(expected);
    if(isBefore){
      ysFlutterToast(context, '宝宝生日不能大于当前日期');
      return;
    }
    Map pragma = Map();
    if(childId!=0){
      pragma['child_id'] = childId;
    }
    pragma['name'] = _name.text;
    pragma['health_book'] = _number.text;
    pragma['birthday'] = birthday;
    if(sex=='男'){
      pragma['gender'] = 1;
    }else{
      pragma['gender'] = 2;
    }
    Map dict = await ysRequestHttp(context,requestType.post, 'child/chapter/addOrUp', pragma);
    if(dict!=null){
      Navigator.of(context).pop('完成');
    }
  }

  _getChildData() async{
    SharedPreferences prefer = await SharedPreferences.getInstance();
    Map request = Map();
    request['category_id'] = prefer.getInt('chapters')+1;
    request['child_id'] = prefer.getInt('childId');
    Map dict = await ysRequestHttp(context, requestType.get, 'chapter/info', request);
    if(dict!=null){
      childId = dict['data']['id'];
      setState(() {
        _name.text = dict['data']['name'];
        _number.text = dict['data']['health_book'];
        birthday = dict['data']['birthday'];
        sex = dict['data']['gender']==2?'女':'男';
      });
    }
  }
}
