import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutterappfuyou/code/YSHospital.dart';
import 'package:flutterappfuyou/code/YSHospitalDetail.dart';
import 'package:flutterappfuyou/code/YSMeans.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:flutterappfuyou/code/version2/YSMineLive.dart';
import 'package:flutterappfuyou/code/version2/YSMineQuestionnaire.dart';
import 'package:flutterappfuyou/code/version3/YSPerfectChapterInfo.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'YSAddChapter.dart';
import 'YSCollection.dart';
import 'YSDiary.dart';
import 'YSDueDate.dart';
import 'YSFeedback.dart';
import 'YSPeriod.dart';
import 'YSPhoto.dart';
import 'YSSetting.dart';
import 'YSUserInfo.dart';
import 'package:shared_preferences/shared_preferences.dart';

class YSMine extends StatefulWidget {
  @override
  _YSMineState createState() => _YSMineState();
}

class _YSMineState extends State<YSMine> {
  int chapter;
  String avatar,name,phone;
  List _titleArray = [
    {'title':'我的收藏','icon':'collect','isMore':true},
    {'title':'我的相册','icon':'photo','isMore':true},
    {'title':'调查问卷','icon':'photo','isMore':true},
    {'title':'客服电话','icon':'phone'}
  ];
  bool _isLive = false;
  Map _userInfo = {};
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      _getUserData();
      _getPhoneData();
      _getLiveData();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    chapter = User().chapter;
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: CupertinoPageScaffold(
        child: RefreshIndicator(
          onRefresh: _getLiveData,
          child: SingleChildScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            child: Container(
              color: Color(0xFFF5F3F0),
              height: ysHeight(context)-40,
              child: Stack(
                children: [
                  Container(
                    width: MediaQuery.of(context).size.width,
                    height: 211.5,
                    child: Image(
                      image: AssetImage('lib/images/minebg.png'),
                      fit: BoxFit.fill,
                    )
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 26,top: MediaQuery.of(context).padding.top+15),
                    child: Text('个人中心',style: TextStyle(fontSize: 16,color: Colors.white,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                  ),
                  GestureDetector(
                    onTap: (){
                      Navigator.of(context,rootNavigator: true).push(
                        CupertinoPageRoute(
                          builder: (context){
                            return YSUserInfo();
                          }
                        )
                      ).then((value) {
                        _getUserData();
                      });
                    },
                    child: Container(
                      margin: EdgeInsets.only(left: 16,top: MediaQuery.of(context).padding.top+75),
                      height: 60,
                      width: 60,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(30)),
                        color: Color(0xFFEED1C3),
                        image: DecorationImage(image: avatar!=null?NetworkImage(avatar):AssetImage('lib/images/head.png'),fit: BoxFit.cover)
                      ),
                    ),
                  ),
                  Container(
                    height: 20,
                    width: MediaQuery.of(context).size.width-100,
                    margin: EdgeInsets.only(left: 86,top: MediaQuery.of(context).padding.top+95),
                    child: Text(name!=null?name:'',style: TextStyle(fontSize: 16,color: Colors.white,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 200),
                    child: Column(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10)),
                            color: Colors.white,
                          ),
                          height: 50,
                          child: Row(
                            children: [
                              GestureDetector(
                                onTap: (){
                                  Navigator.of(context,rootNavigator: true).push(
                                    CupertinoPageRoute(
                                      builder: (context){
                                        return chapter==0?YSDiary():chapter==1?YSDueDate(dueDate: _userInfo['expected_time'],):YSAddChapter(isEdit: true,);
                                      }
                                    )
                                  );
                                },
                                child: Container(
                                  width: MediaQuery.of(context).size.width/2-0.25,
                                  child: (chapter==null||chapter==0)?Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Image(height: 20,width: 20,image: AssetImage('lib/images/riji2.png'),),
                                      Text(' 备孕日记',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                    ],
                                  ):chapter==1?Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Image(height: 20,width: 20,image: AssetImage('lib/images/rili2.png'),),
                                      Text(' 预产期',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                    ],
                                  ):Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Image(height: 20,width: 20,image: AssetImage('lib/images/babyInfo.png'),),
                                      Text(' 宝宝资料',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                    ],
                                  ),
                                ),
                              ),
                              Container(
                                height: 30,
                                color: Color(0xFFE5E1E1),
                                width: 0.5,
                              ),
                              GestureDetector(
                                onTap: (){
                                  // Navigator.of(context,rootNavigator: true).push(
                                  //     CupertinoPageRoute(
                                  //         builder: (context){
                                  //           return YSPerfectChapterInfo();
                                  //         }
                                  //     )
                                  // );
                                  // return;
                                  Navigator.of(context,rootNavigator: true).push(
                                    CupertinoPageRoute(
                                      builder: (context){
                                        return YSFeedback();
                                      }
                                    )
                                  );
                                },
                                child: Container(
                                  width: MediaQuery.of(context).size.width/2-0.25,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Image(height: 20,width: 20,image: AssetImage('lib/images/feedback.png'),),
                                      Text(' 意见反馈',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: ysHeight(context)-300,
                          child: SingleChildScrollView(
                            padding: EdgeInsets.only(bottom: 10),
                            child: Column(
                              children: [
                                // Container(
                                //   height: 500,
                                // ),
                                chapter==0?GestureDetector(
                                  onTap: (){
                                    Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return YSPeriod();
                                            }
                                        )
                                    );
                                  },
                                  child: Container(
                                    width: MediaQuery.of(context).size.width-10,
                                    height: 50,
                                    margin: EdgeInsets.only(top: 5),
                                    padding: EdgeInsets.only(left: 18),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(6))
                                    ),
                                    child: Row(
                                      children: [
                                        Image(height: 20,width: 20,image: AssetImage('lib/images/systemMsg.png'),),
                                        Text('  经期设置',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                      ],
                                    ),
                                  ),
                                ):Container(),
                                Container(
                                  width: MediaQuery.of(context).size.width-10,
                                  height: 200,
                                  margin: EdgeInsets.only(top: 5),
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.all(Radius.circular(6))
                                  ),
                                  child: ListView.builder(
                                      padding: EdgeInsets.all(0),
                                      itemCount: _titleArray.length,
                                      physics: NeverScrollableScrollPhysics(),
                                      itemBuilder: (context,index){
                                        Map item = _titleArray[index];
                                        String title = item['title'];
                                        return GestureDetector(
                                          behavior: HitTestBehavior.opaque,
                                          onTap: (){
                                            if(title=='客服电话'){
                                              if(phone.isEmpty)return;
                                              showDialog(
                                                  context: context,
                                                  builder: (context){
                                                    return CupertinoAlertDialog(
                                                      title: Text('提示\n'),
                                                      content: Text('是否拨打$phone'),
                                                      actions: [
                                                        CupertinoButton(
                                                          child: Container(
                                                            child: Text('取消',style: TextStyle(fontSize: 16,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                                            height: 40,
                                                            alignment: Alignment.center,
                                                          ),
                                                          padding: EdgeInsets.all(0),
                                                          onPressed: (){
                                                            Navigator.pop(context);
                                                          },
                                                        ),
                                                        CupertinoButton(
                                                          child: Container(
                                                            child: Text('确定',style: TextStyle(fontSize: 16,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                                            height: 40,
                                                            alignment: Alignment.center,
                                                          ),
                                                          padding: EdgeInsets.all(0),
                                                          onPressed: (){
                                                            Navigator.pop(context);
                                                            launchUrlString('tel:$phone');
                                                          },
                                                        )
                                                      ],
                                                    );
                                                  }
                                              );
                                            }else{
                                              Navigator.of(context,rootNavigator: true).push(
                                                  CupertinoPageRoute(
                                                      builder: (context){
                                                        return title=='我的收藏'?YSCollection():title=='我的相册'?YSPhoto():title=='调查问卷'?YSMineQuestionnaire():YSMineQuestionnaire();
                                                      }
                                                  )
                                              );
                                            }
                                          },
                                          child: Container(
                                            height: 50,
                                            padding: EdgeInsets.only(left: 18,right: 18),
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                              children: [
                                                Row(
                                                  children: [
                                                    Image(height: 20,width: 20,image: AssetImage('lib/images/${item['icon']}.png'),),
                                                    Text('  $title',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                                  ],
                                                ),
                                                title=='客服电话'?Row(
                                                  children: [
                                                    Text(phone!=null?phone:'',style: TextStyle(color: Color(0xFFAEB3BD),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                                    Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
                                                  ],
                                                ):Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
                                              ],
                                            ),
                                          ),
                                        );
                                      }
                                  ),
                                ),
                                if(_isLive)GestureDetector(
                                  onTap: (){
                                    Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return YSMineLive();
                                            }
                                        )
                                    );
                                  },
                                  child: Container(
                                    width: MediaQuery.of(context).size.width-10,
                                    height: 50,
                                    margin: EdgeInsets.only(top: 5),
                                    padding: EdgeInsets.only(left: 18,right: 18),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(6))
                                    ),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Row(
                                          children: [
                                            Image(height: 20,width: 20,image: AssetImage('lib/images/直播培训图标.png'),),
                                            Text('  直播培训',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                          ],
                                        ),
                                        Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
                                      ],
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: (){
                                    Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return _userInfo['health_id']!=null?YSHospitalDetail(healthId: _userInfo['health_id']):YSHospital(healthId: _userInfo['health_id'], areaId: _userInfo['region_id'],);
                                            }
                                        )
                                    ).then((value) {
                                      _getUserData();
                                    });
                                  },
                                  child: Container(
                                    width: MediaQuery.of(context).size.width-10,
                                    height: 50,
                                    margin: EdgeInsets.only(top: 5),
                                    padding: EdgeInsets.only(left: 18,right: 18),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(6))
                                    ),
                                    child: Row(
                                      children: [
                                        Image(height: 20,width: 20,image: AssetImage('lib/images/set.png'),),
                                        Container(
                                          width: (ysWidth(context)-86)*0.4,
                                          child: Text('  卫生院',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                        ),
                                        Container(
                                          width: (ysWidth(context)-86)*0.6,
                                          alignment: Alignment.centerRight,
                                          child: Text(_userInfo['health_name']??'',style: TextStyle(color: Color(0xFFB8B6B4),fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                        ),
                                        Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
                                      ],
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: (){
                                    Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return YSMeans(isEdit: true,);
                                            }
                                        )
                                    ).then((value) {
                                      _getUserData();
                                    });
                                  },
                                  child: Container(
                                    width: MediaQuery.of(context).size.width-10,
                                    height: 50,
                                    margin: EdgeInsets.only(top: 5),
                                    padding: EdgeInsets.only(left: 18,right: 18),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(6))
                                    ),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Row(
                                          children: [
                                            Image(height: 20,width: 20,image: AssetImage('lib/images/set.png'),),
                                            Text('  用户资料',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                          ],
                                        ),
                                        Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
                                      ],
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: (){
                                    Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return YSSetting();
                                            }
                                        )
                                    );
                                  },
                                  child: Container(
                                    width: MediaQuery.of(context).size.width-10,
                                    height: 50,
                                    margin: EdgeInsets.only(top: 5),
                                    padding: EdgeInsets.only(left: 18,right: 18),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(6))
                                    ),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Row(
                                          children: [
                                            Image(height: 20,width: 20,image: AssetImage('lib/images/set.png'),),
                                            Text('  系统设置',style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                          ],
                                        ),
                                        Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  // Positioned(
                  //   bottom: 10,
                  //   child: Container(
                  //     color: Color(0xFFF5F3F0),
                  //     height: 30,
                  //     width: MediaQuery.of(context).size.width,
                  //     child: Text('西安大唐云信息科技有限公司提供技术支持',style: TextStyle(color: Color(0xFFB8B6B4),fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.center,),
                  //   ),
                  // )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _getUserData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'user/info', {});
    if(dict!=null){
      _userInfo = dict;
      SharedPreferences prefer = await SharedPreferences.getInstance();
      prefer.setString('avatar', '${dict['avatar']}');
      prefer.setString('name', dict['simple_name']??dict['username']??'');
      User().name = dict['simple_name']??dict['username']??'';
      User().idCard = dict['id_card']??'';
      setState(() {
        avatar = '${dict['avatar']}';
        name = dict['simple_name']??dict['username']??'';
      });
    }
  }

  Future<void> _getPhoneData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'basic/info', {});
    if(dict!=null){
      setState(() {
        phone = '${dict['data']['contact']??''}';
      });
    }
  }

  Future<void> _getLiveData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'train/live2/canLive', {});
    if(dict!=null){
      Map data = dict['data'];
      _isLive = data['is_can_live']??false;
      setState(() {});
    }
  }
}
