import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_pro/webview_flutter.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:image_picker/image_picker.dart';
import 'package:live_flutter_plugin/v2_tx_live_premier.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../YSPage.dart';
import '../YSMeans.dart';
import '../version2/YSVersionView.dart';

double ysHeight(BuildContext context) => MediaQuery.of(context).size.height;
double ysWidth(BuildContext context) => MediaQuery.of(context).size.width;
double ysTOP(BuildContext context) => MediaQuery.of(context).padding.top;
double ysBottom(BuildContext context) => MediaQuery.of(context).padding.bottom;
Color ysBgColor = const Color(0xFFF6F6F6);

class YSDatePicker extends StatefulWidget {
  final ValueSetter<String> choose;
  final bool withTime;
  const YSDatePicker({Key key, this.choose, this.withTime = false}) : super(key: key);
  @override
  _YSDatePickerState createState() => _YSDatePickerState();
}

class _YSDatePickerState extends State<YSDatePicker> {
  String birthday = DateTime.now().year.toString()+'-'+DateTime.now().month.toString().padLeft(2,'0')+'-'+DateTime.now().day.toString().padLeft(2,'0');
  @override
  void initState() {
    if(widget.withTime){
      birthday = birthday+' '+'${DateTime.now().hour}'.padLeft(2,'0')+':'+'${DateTime.now().minute}'.padLeft(2,'0');
    }
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.transparent,
      height: 340,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          CupertinoButton(
            padding: EdgeInsets.all(0),
            child: Container(
              height: 20,
              child: Image.asset('lib/images/off.png'),
            ),
            onPressed: (){
              Navigator.pop(context);
            },
          ),
          Container(
            height: 240,
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(topLeft: Radius.circular(20),topRight: Radius.circular(20))
            ),
            child: CupertinoDatePicker(
              initialDateTime: DateTime.now(),
              onDateTimeChanged: (date) {
                birthday = date.year.toString()+'-'+date.month.toString().padLeft(2,'0')+'-'+date.day.toString().padLeft(2,'0');
                if(widget.withTime){
                  birthday = birthday+' '+'${date.hour}'.padLeft(2,'0')+':'+'${date.minute}'.padLeft(2,'0');
                }
              },
              mode: widget.withTime?CupertinoDatePickerMode.dateAndTime:CupertinoDatePickerMode.date,
            ),
          ),
          Container(
            height: 56,
            width: MediaQuery.of(context).size.width,
            color: Colors.white,
            child: CupertinoButton(
              padding: EdgeInsets.all(0),
              child: Container(
                height: 30,
                width: 80,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(15)),
                    boxShadow: [
                      BoxShadow(color: Colors.grey,blurRadius: 3)
                    ]
                ),
                child: Text('确定',style: TextStyle(fontSize: 14,color: Color(0xFF4CC17C),decoration: TextDecoration.none,fontWeight: FontWeight.normal)),
                alignment: Alignment.center,
              ),
              onPressed: (){
                Navigator.pop(context);
                widget.choose(birthday);
              },
            ),
            alignment: Alignment.center,
          )
        ],
      ),
    );
  }
}

ysDatePicker(BuildContext context,ValueSetter valueSetter,{DateTime firstDate,DateTime lastDate,DateTime initDate}) {
  showDatePicker(
    context: context,
    firstDate: firstDate!=null?firstDate:DateTime.parse('2000-01-01 00:00:00'),
    initialDate: initDate!=null?initDate:DateTime.now(),
    lastDate: lastDate!=null?lastDate:DateTime.parse('3000-01-01 00:00:00'),
    builder: (BuildContext context, Widget child) {
      return Theme(
        data: ThemeData.dark().copyWith(
          colorScheme: ColorScheme.light(
            primary: Colors.pinkAccent,
          ),
          dialogBackgroundColor:Colors.white,
        ),
        child: child,
      );
    },

  ).then((date) {
    if(date==null)return;
    String dateStr = date.year.toString()+'-'+date.month.toString().padLeft(2,'0')+'-'+date.day.toString().padLeft(2,'0');
    valueSetter(dateStr);
  });
}


ysUploadFile(BuildContext context,{String path,ValueSetter setter,String type}) async{
  var dict = await ysRequestHttpNoLoading(context, requestType.get, 'upQiniuToken', {'type':type});
  if(dict!=null){
    Storage _storage = Storage();
    _storage.putFile(
      File(path),
      dict['token'],
      options: PutOptions(
        key: dict['path'],
      ),
    ).then((PutResponse response) async{
      setter({'path':dict['path'],'url':dict['url']});
    });
  }

}


GlobalKey<_YSRefreshLoadState> refreshKey = GlobalKey();
GlobalKey<_YSRefreshLoadState> refreshKey2 = GlobalKey();
GlobalKey<_YSRefreshLoadState> refreshKey3 = GlobalKey();
class YSRefreshLoad extends StatefulWidget {
  final dataWidget;
  final ValueSetter postData;
  final String url;
  final Map request;
  const YSRefreshLoad({Key key, @required this.url, @required this.request, @required this.dataWidget, @required this.postData,}) : super(key: key);
  @override
  _YSRefreshLoadState createState() => _YSRefreshLoadState();
}

class _YSRefreshLoadState extends State<YSRefreshLoad> {
  int _page = 1;
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  List _dataArray = [];
  int _totalNum = 0;
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      _refreshData();
    });
    super.initState();
  }

  refresh(){
    _refreshData();
  }

  @override
  void dispose() {
    if(_refreshController!=null){
      _refreshController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
        onRefresh: _refreshData,
        onLoading: _loadMore,
        enablePullUp: _dataArray.length<_totalNum,
        controller: _refreshController,
        header: ClassicHeader(
          height: 45.0,
          releaseText: '松开手刷新',
          refreshingText: '刷新中',
          completeText: '刷新完成',
          failedText: '刷新失败',
          idleText: '下拉刷新',
        ),
        footer: ClassicFooter(
          height: 45.0,
          canLoadingText: '没有更多数据了',
          noDataText: ' 无数据',
          loadingText: '加载中 ',
          failedText: '加载失败',
          idleText: '上拉加载',
        ),
        child: NotificationListener<CustomNotification>(
          onNotification: (value){
            _refreshData();
            return true;
          },
          child: _dataArray.isEmpty?Center(
            child: Image.asset('lib/images/none.png',height: 200,width: 200,),
          ):widget.dataWidget,
        )
    );
  }

  Future<void> _refreshData() async{
    _page = 1;
    Map request = {'page':_page};
    request.addAll(widget.request);
    requestType type = requestType.get;
    if(widget.url=='transfer/coupon/getCommunityVouchers'){
      type = requestType.post;
      request['pageSize'] = 10;
    }
    Map dict = await ysRequestHttpNoLoading(context,type,widget.url,request);
    if(dict!=null){
      List array = [];
      array = dict['data']['datas'];
      _totalNum = dict['data']['pages']['total'];
      _refreshController.refreshCompleted();
      _dataArray = array;
      widget.postData(_dataArray);
    }
  }

  Future<void> _loadMore() async{
    _page++;
    Map request = {'page':_page};
    request.addAll(widget.request);
    requestType type = requestType.get;
    if(widget.url=='transfer/coupon/getCommunityVouchers'){
      type = requestType.post;
      request['pageSize'] = 10;
    }
    Map dict = await ysRequestHttpNoLoading(context,type,widget.url,request);
    if(dict!=null){
      List array = [];
      array = dict['data']['datas'];
      _refreshController.loadComplete();
      _dataArray.addAll(array);
      widget.postData(_dataArray);
    }
  }
}


class YSRefreshLoad2 extends StatefulWidget {
  final dataWidget;
  final ValueSetter postData;
  final String url;
  final Map request;
  const YSRefreshLoad2({Key key, @required this.url, @required this.request, @required this.dataWidget, @required this.postData,}) : super(key: key);
  @override
  _YSRefreshLoad2State createState() => _YSRefreshLoad2State();
}

class _YSRefreshLoad2State extends State<YSRefreshLoad2> {
  int _page = 1;
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  List _dataArray = [];
  int _totalNum = 0;
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      _refreshData();
    });
    super.initState();
  }

  refresh(){
    _refreshData();
  }

  @override
  void dispose() {
    if(_refreshController!=null){
      _refreshController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
        onRefresh: _refreshData,
        onLoading: _loadMore,
        enablePullUp: _dataArray.length<_totalNum,
        controller: _refreshController,
        header: ClassicHeader(
          height: 45.0,
          releaseText: '松开手刷新',
          refreshingText: '刷新中',
          completeText: '刷新完成',
          failedText: '刷新失败',
          idleText: '下拉刷新',
        ),
        footer: ClassicFooter(
          height: 45.0,
          canLoadingText: '没有更多数据了',
          noDataText: ' 无数据',
          loadingText: '加载中 ',
          failedText: '加载失败',
          idleText: '上拉加载',
        ),
        child: NotificationListener<CustomNotification>(
          onNotification: (value){
            _refreshData();
            return true;
          },
          child: widget.dataWidget,
        )
    );
  }

  Future<void> _refreshData() async{
    _page = 1;
    Map request = {'page':_page};
    request.addAll(widget.request);
    Map dict = await ysRequestHttpNoLoading(context,requestType.post,widget.url,request);
    if(dict!=null){
      List array = [];
      array = dict['data']['records'];
      _totalNum = dict['data']['total'];
      _refreshController.refreshCompleted();
      _dataArray = array;
      widget.postData(_dataArray);
    }
  }

  Future<void> _loadMore() async{
    _page++;
    Map request = {'page':_page};
    request.addAll(widget.request);
    Map dict = await ysRequestHttpNoLoading(context,requestType.post,widget.url,request);
    if(dict!=null){
      List array = [];
      array = dict['data']['records'];
      _totalNum = dict['data']['total'];
      _refreshController.loadComplete();
      _dataArray.addAll(array);
      widget.postData(_dataArray);
    }
  }
}


class CustomNotification extends Notification {
  CustomNotification(this.value);
  final String value;
}


class LogUtil {
  static var _separator = "=";
  static var _split =
      "$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator";
  static var _title = "Yl-Log";
  static var _isDebug = true;
  static int _limitLength = 800;
  static String _startLine = "$_split$_title$_split";
  static String _endLine = "$_split$_separator$_separator$_separator$_split";

  static void init({String title, @required bool isDebug,int limitLength}) {
    _title = title;
    _isDebug = isDebug;
    _limitLength = limitLength??=_limitLength;
    _startLine = "$_split$_title$_split";
    var endLineStr = StringBuffer();
    var cnCharReg = RegExp("[\u4e00-\u9fa5]");
    for (int i = 0; i < _startLine.length; i++) {
      if (cnCharReg.stringMatch(_startLine[i]) != null) {
        endLineStr.write(_separator);
      }
      endLineStr.write(_separator);
    }
    _endLine = endLineStr.toString();
  }

  //仅Debug模式可见
  static void d(dynamic obj) {
    if (_isDebug) {
      _log(obj.toString());
    }
  }

  static void v(dynamic obj) {
    _log(obj.toString());
  }

  static void _log(String msg) {
    print("$_startLine");
    _logEmpyLine();
    if(msg.length<_limitLength){
      print(msg);
    }else{
      segmentationLog(msg);
    }
    _logEmpyLine();
    print("$_endLine");
  }

  static void segmentationLog(String msg) {
    var outStr = StringBuffer();
    for (var index = 0; index < msg.length; index++) {
      outStr.write(msg[index]);
      if (index % _limitLength == 0 && index!=0) {
        print(outStr);
        outStr.clear();
        var lastIndex = index+1;
        if(msg.length-lastIndex<_limitLength){
          var remainderStr = msg.substring(lastIndex,msg.length);
          print(remainderStr);
          break;
        }
      }
    }
  }

  static void _logEmpyLine(){
    print("");
  }
}

ysShowBottomAlertView(BuildContext context,Widget widget,{bool isBarr = false}) {
  showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      barrierColor: !isBarr?Colors.transparent:Colors.black54,
      builder: (context){
        return widget;
      }
  );
}

ysShowBottomAlertView2(BuildContext context,Widget widget,{bool isBarr = false}) {
  showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      barrierColor: !isBarr?Colors.transparent:Colors.black54,
      builder: (context){
        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets,
          duration: const Duration(milliseconds: 100),
          child: widget
        );
      }
  );
}

ysShowCenterAlertView(BuildContext context,Widget widget,{bool isTrans = false,bool isBarr = false}) {
  showGeneralDialog(
      context: context,
      barrierDismissible: isBarr,
      barrierLabel: '',
      barrierColor: isTrans==true?Colors.transparent:Colors.black54,
      pageBuilder: (context,animation,scAnimation){
        return widget;
      }
  );
}

class User {
  // 工厂模式 : 单例公开访问点
  factory User() => _getInstance();

  static User get instance => _getInstance();

  // 静态私有成员，没有初始化
  static User _instance;
  String userId = '0';
  String name = '';
  String avatar = '';
  String stream = '';
  String idCard;
  String content = '';
  bool isAnchor = false;
  String routeStr = '';
  int chapter = 0;
  String castAvatar;
  String castName;
  // 私有构造函数
  User._internal() {
    // 初始化
  }

  // 静态、同步、私有访问点
  static User _getInstance() {
    if (_instance == null) {
      _instance = new User._internal();
    }
    return _instance;
  }
}


class YSChooseFileView extends StatefulWidget {
  final bool isPhoto;
  final ValueSetter valueSetter;
  const YSChooseFileView({Key key, this.valueSetter, this.isPhoto = true}) : super(key: key);

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

class YSChooseFileViewState extends State<YSChooseFileView> {
  final ImagePicker _picker = ImagePicker();
  final List _chooseArray = [];
  @override
  void initState() {
    _chooseArray.clear();
    if(widget.isPhoto){
      _chooseArray.addAll([
        {'title':'拍摄图片','type':1},
        {'title':'选择图片','type':2},
        {'title':'取消','type':0}
      ]);
    }else{
      _chooseArray.addAll([
        {'title':'拍摄图片','type':1},
        {'title':'选择图片','type':2},
        {'title':'拍摄视频','type':3},
        {'title':'选择视频','type':4},
        {'title':'取消','type':0}
      ]);
    }
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 20+50*_chooseArray.length/1,
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(topRight: Radius.circular(10),topLeft: Radius.circular(10))
      ),
      child: ListView.separated(
        physics: const NeverScrollableScrollPhysics(),
        itemCount: _chooseArray.length,
        padding: const EdgeInsets.all(0),
        itemBuilder: (context,index){
          Map item = _chooseArray[index];
          int type = item['type'];
          return GestureDetector(
            onTap: (){
              if(type==0){
                Navigator.pop(context);
              }else{
                if(type==1){
                  _picker.pickImage(source: ImageSource.camera,imageQuality: 60).then((value){
                    widget.valueSetter(value);
                    Navigator.pop(context);
                  });
                }else if(type==2){
                  _picker.pickImage(imageQuality: 60,source: ImageSource.gallery).then((value){
                    widget.valueSetter(value);
                    Navigator.pop(context);
                  });
                }else if(type==3||type==4){
                  _picker.pickVideo(source: type==3?ImageSource.camera:ImageSource.gallery).then((value){
                    widget.valueSetter(value);
                    Navigator.pop(context);
                  });
                }
              }
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              height: 50,
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(left: 16,right: 16),
              alignment: Alignment.center,
              child: Text(item['title'],style: TextStyle(fontSize: 16,color: Colors.black),),
            ),
          );
        },
        separatorBuilder: (context,index){
          return Divider(height: index==_chooseArray.length-2?8:1,thickness: index==_chooseArray.length-2?8:1,color: const Color(0xFFF7F7F7),);
        },
      ),
    );
  }
}

setupLicense() {
  var LICENSEURL = "https://license.vod2.myqcloud.com/license/v2/1308439060_1/v_cube.license";
  var LICENSEURLKEY = "e194f81894e300965d1ae08a5e0bf404";
  V2TXLivePremier.setLicence(LICENSEURL, LICENSEURLKEY);
}

Future<bool> permissionHandler(String serviceStr) async{
  if(serviceStr=='location'){
    if (await Permission.location.request().isGranted||await Permission.locationWhenInUse.request().isGranted) {
      return true;
    }else if (await Permission.location.request().isPermanentlyDenied&&await Permission.locationWhenInUse.request().isPermanentlyDenied) {
      return false;
    }else{
      Map<Permission, PermissionStatus> statuses = await [Permission.location,Permission.locationWhenInUse].request();
      if(statuses[Permission.location].isGranted || statuses[Permission.locationWhenInUse].isGranted){
        return true;
      }
    }
  }else if(serviceStr=='camera'){
    if (await Permission.camera.request().isGranted) {
      return true;
    }else if (await Permission.camera.request().isPermanentlyDenied) {
      return false;
    }else{
      Map<Permission, PermissionStatus> statuses = await [Permission.camera].request();
      if(statuses[Permission.camera].isGranted){
        return true;
      }
    }
  }else if(serviceStr=='microphone'){
    if (await Permission.microphone.request().isGranted) {
      return true;
    }else if (await Permission.microphone.request().isPermanentlyDenied) {
      return false;
    }else{
      Map<Permission, PermissionStatus> statuses = await [Permission.microphone].request();
      if(statuses[Permission.microphone].isGranted){
        return true;
      }
    }
  }
  return false;
}

class CustomerNotification extends Notification {
  CustomerNotification();
}

class CustomerValueNotification extends Notification {
  final Map value;
  CustomerValueNotification(this.value);
}

// class SocketManage {
//   static  WebSocket _socket;
//   static ValueSetter<Map> setter;
//   // 建立连接
//   static void connectSocket() async {
//     WebSocket.connect('ws://101.43.97.222:8686').then((socket) {
//       _socket = socket;
//       _socket.listen(onData,onError: onError, onDone: onDone, cancelOnError: false);
//     }).catchError((e){
//       LogUtil.d("Unable to connect: $e");
//       connectSocket(); // 连接超时，重新建立连接
//     });
//   }
//
//   // 收到消息回调
//   static void onData(event) async{
//     Map dict = jsonDecode(event);
//     LogUtil.d("---onData---$dict");
//     Map data = dict['data'];
//     if(dict['msg']=='连接成功'){
//       setter({'type':0,'content':data['content']});
//       Map message = {};
//       message['type'] = 'bind';
//       message['live_stream'] = User().stream;
//       message['uid'] = data['uid'];
//       message['user'] = {'username':User().name,'avatar':User().avatar,'is_owner':User().isAnchor};
//       LogUtil.d('---onData---$message');
//       writeData(message);
//     }
//   }
//
//   // 收到错误回调
//   static void onError(err) {
//     LogUtil.d("---onError---");
//   }
//
//   // 断开回调
//   static void onDone() {
//     // Future.delayed(const Duration(milliseconds: 2000), () {
//     //   connectSocket(); // 重新建立连接
//     // });
//     LogUtil.d("---onDone---");
//   }
//
//   // 发数据
//   static void writeData(Object object){
//     _socket.add(jsonEncode(object));
//   }
//
//   // 关闭流通道
//   static void socketClose(){
//     _socket.close();
//   }
// }
class YSTipsAlertView extends StatelessWidget {
  final ValueSetter<bool> valueSetter;
  final String tipsStr;
  const YSTipsAlertView({Key key, this.valueSetter, this.tipsStr}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: ysWidth(context)-60,
        height: 200,
        decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))
        ),
        child: LayoutBuilder(
          builder: (context,conSize){
            return Column(
              children: [
                Container(
                  height: 50,
                  decoration: const BoxDecoration(
                      border: Border(bottom: BorderSide(color: Color(0xFFEBEDF0),width: 0.5))
                  ),
                  alignment: Alignment.center,
                  child: Text('提醒',style: TextStyle(fontSize: 16,color: Colors.black,decoration: TextDecoration.none),),
                ),
                Container(
                  height: 100,
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(10),
                  child: Text(tipsStr,style: TextStyle(fontSize: 14,color: const Color(0xFF4A4A4A),
                      decoration: TextDecoration.none,fontWeight: FontWeight.normal),maxLines: 3,overflow: TextOverflow.ellipsis,),
                ),
                Container(
                  height: 50,
                  decoration: const BoxDecoration(
                      border: Border(top: BorderSide(color: Color(0xFFEBEDF0),width: 0.5))
                  ),
                  child: ListView.separated(
                    itemBuilder: (context,index){
                      return GestureDetector(
                        onTap: (){
                          Navigator.pop(context);
                          valueSetter(index==1);
                        },
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          width: conSize.maxWidth/2-0.25,
                          alignment: Alignment.center,
                          child: Text(
                            index==0?'取消':'确定',
                            style: TextStyle(
                                fontSize: 16,
                                color: index==0?const Color(0xFF323233):const Color(0xFFF05183),
                                decoration: TextDecoration.none,
                                fontWeight: FontWeight.normal
                            ),
                          ),
                        ),
                      );
                    },
                    separatorBuilder: (context,index){
                      return Container(width: 0.5,color: const Color(0xFFEBEDF0),);
                    },
                    itemCount: 2,
                    scrollDirection: Axis.horizontal,
                  ),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}

class YSTipsAlertView2 extends StatelessWidget {
  final ValueSetter<bool> valueSetter;
  final String tipsStr;
  const YSTipsAlertView2({Key key, this.valueSetter, this.tipsStr}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: ysWidth(context)-60,
        height: 200,
        decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))
        ),
        child: LayoutBuilder(
          builder: (context,conSize){
            return Column(
              children: [
                Container(
                  height: 50,
                  decoration: const BoxDecoration(
                      border: Border(bottom: BorderSide(color: Color(0xFFEBEDF0),width: 0.5))
                  ),
                  alignment: Alignment.center,
                  child: Text('提醒',style: TextStyle(fontSize: 16,color: Colors.black,decoration: TextDecoration.none),),
                ),
                Container(
                  height: 100,
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(10),
                  child: Text(tipsStr,style: TextStyle(fontSize: 14,color: const Color(0xFF4A4A4A),
                      decoration: TextDecoration.none,fontWeight: FontWeight.normal),maxLines: 3,overflow: TextOverflow.ellipsis,),
                ),
                GestureDetector(
                  onTap: (){
                    Navigator.pop(context);
                    valueSetter(true);
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Container(
                    height: 50,
                    decoration: const BoxDecoration(
                        border: Border(top: BorderSide(color: Color(0xFFEBEDF0),width: 0.5))
                    ),
                    alignment: Alignment.center,
                    child: Text('确定',
                      style: TextStyle(
                          fontSize: 16,
                          color: const Color(0xFFF05183),
                          decoration: TextDecoration.none,
                          fontWeight: FontWeight.normal
                      ),
                    ),
                  ),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}


showNegotiate1AlertDio(BuildContext context,{String content = '',String title = ''}) {
  showGeneralDialog(
      context: context,
      barrierDismissible:true,
      barrierColor: Colors.black.withOpacity(0.6),
      barrierLabel: '',
      transitionDuration: Duration(milliseconds: 200),
      pageBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return Center(
          child: Container(
            height: MediaQuery.of(context).size.height-(MediaQuery.of(context).padding.top+50*2),
            width: MediaQuery.of(context).size.width-50,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(5))
            ),
            child: Column(
              children: [
                Container(
                  height: 50,
                  padding: EdgeInsets.only(left: 15,right: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(),
                      Text(title,style: TextStyle(fontSize: 17,color: Color(0xFF242329),decoration: TextDecoration.none),),
                      GestureDetector(
                        child: Icon(Icons.close,size: 25,color: Color(0xFF242329)),
                        onTap: (){Navigator.pop(context);},
                      )
                    ],
                  ),
                ),
                Divider(height: 0.5,thickness: 0.5,color: Color(0xFFEDEDED),),
                Container(
                  height: MediaQuery.of(context).size.height-(MediaQuery.of(context).padding.top+50*2)-50-0.5,
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.all(10),
                  child: WebView(
                    javascriptMode: JavascriptMode.unrestricted,
                    onWebViewCreated: (WebViewController webViewController) {
                      // webViewController.loadUrl(Uri.dataFromString(content, mimeType: 'text/html', encoding: Encoding.getByName('utf-8')).toString());
                      webViewController.loadUrl(content);
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      }
  );
}

showNegotiate2AlertDio(BuildContext context,{String content = '',String title = '',VoidCallback agree,VoidCallback disAgree}) {
  showGeneralDialog(
      context: context,
      barrierDismissible:true,
      barrierColor: Colors.black.withOpacity(0.6),
      barrierLabel: '',
      transitionDuration: Duration(milliseconds: 200),
      pageBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return WillPopScope(
          onWillPop: () async{
            return false;
          },
          child: Center(
            child: Container(
              height: MediaQuery.of(context).size.height-(MediaQuery.of(context).padding.top+50*2),
              width: MediaQuery.of(context).size.width-50,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(5))
              ),
              child: Column(
                children: [
                  Container(
                    height: 50,
                    padding: EdgeInsets.only(left: 15,right: 15),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(),
                        Text(title,style: TextStyle(fontSize: 17,color: Color(0xFF242329),decoration: TextDecoration.none),),
                        Container(),
                        // GestureDetector(
                        //   child: Icon(Icons.close,size: 25,color: Color(0xFF242329)),
                        //   onTap: (){Navigator.pop(context);},
                        // )
                      ],
                    ),
                  ),
                  Divider(height: 0.5,thickness: 0.5,color: Color(0xFFEDEDED),),
                  Container(
                    height: MediaQuery.of(context).size.height-(MediaQuery.of(context).padding.top+50*2)-100-0.5,
                    width: MediaQuery.of(context).size.width-50,
                    padding: EdgeInsets.all(10),
                    child: WebView(
                      javascriptMode: JavascriptMode.unrestricted,
                      onWebViewCreated: (WebViewController webViewController) {
                        // webViewController.loadUrl(Uri.dataFromString(content, mimeType: 'text/html', encoding: Encoding.getByName('utf-8')).toString());
                        webViewController.loadUrl(content);
                      },
                    ),
                  ),
                  Container(
                      height: 50,
                      alignment: Alignment.center,
                      child: Row(
                        children: [
                          GestureDetector(
                            onTap: (){
                              Navigator.pop(context);
                              disAgree();
                            },
                            child: Container(
                              width: (MediaQuery.of(context).size.width-50)/2-0.5,
                              alignment: Alignment.center,
                              child: Text('不同意',style: TextStyle(fontSize: 17,color: Color(0xFF999999),decoration: TextDecoration.none),),
                            ),
                          ),
                          Container(
                            height: 50,
                            width: 0.5,
                            color: Color(0xFFF9F9F9),
                          ),
                          GestureDetector(
                            onTap: (){
                              Navigator.pop(context);
                              agree();
                            },
                            child: Container(
                              width: (MediaQuery.of(context).size.width-50)/2-0.5,
                              alignment: Alignment.center,
                              child: Text('同意',style: TextStyle(fontSize: 17,color: Colors.pinkAccent,decoration: TextDecoration.none),),
                            ),
                          )
                        ],
                      )
                  ),
                ],
              ),
            ),
          ),
        );
      }
  );
}

showNegotiate3AlertDio(BuildContext context,{String content = '',String title = '',VoidCallback agree,}) {
  showGeneralDialog(
      context: context,
      barrierDismissible:false,
      barrierColor: Colors.black.withOpacity(0.6),
      barrierLabel: '',
      transitionDuration: Duration(milliseconds: 200),
      pageBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return YSAlertView3(title: title,content: content,callback: agree,);
      }
  );
}

class YSAlertView3 extends StatefulWidget {
  final String title;
  final String content;
  final VoidCallback callback;
  const YSAlertView3({Key key, this.title, this.content, this.callback}) : super(key: key);

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

class _YSAlertView3State extends State<YSAlertView3> {
  Timer _timer;
  int _count = 10;
  @override
  void dispose() {
    if(_timer.isActive)_timer.cancel();
    super.dispose();
  }
  _startTimer() {
    _timer =Timer.periodic(Duration(seconds: 1), (timer) {
      _count--;
      if(_count<=0){
        timer.cancel();
      }
      setState(() {});
    });
  }
  @override
  void initState() {
    _startTimer();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        return false;
      },
      child: Center(
        child: Container(
          height: MediaQuery.of(context).size.height-(MediaQuery.of(context).padding.top+50*2),
          width: MediaQuery.of(context).size.width-50,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(5))
          ),
          child: Column(
            children: [
              // Container(
              //   height: 50,
              //   padding: EdgeInsets.only(left: 15,right: 15),
              //   child: Row(
              //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //     children: [
              //       Container(),
              //       Text(widget.title,style: TextStyle(fontSize: 17,color: Color(0xFF242329),decoration: TextDecoration.none),),
              //       Container(),
              //       // GestureDetector(
              //       //   child: Icon(Icons.close,size: 25,color: Color(0xFF242329)),
              //       //   onTap: (){Navigator.pop(context);},
              //       // )
              //     ],
              //   ),
              // ),
              // Divider(height: 0.5,thickness: 0.5,color: Color(0xFFEDEDED),),
              Container(
                height: MediaQuery.of(context).size.height-(MediaQuery.of(context).padding.top+50*2)-50,
                width: MediaQuery.of(context).size.width-50,
                padding: EdgeInsets.all(10),
                child: WebView(
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webViewController) {
                    webViewController.loadUrl(Uri.dataFromString(widget.content, mimeType: 'text/html', encoding: Encoding.getByName('utf-8')).toString());
                    // webViewController.loadUrl(content);
                  },
                ),
              ),
              GestureDetector(
                onTap: (){
                  // LogUtil.d('obj');
                  if(_count==0){
                    Navigator.pop(context);
                    widget.callback();
                  }
                },
                behavior: HitTestBehavior.opaque,
                child: Container(
                  width: ysWidth(context),
                  height: 50,
                  alignment: Alignment.center,
                  child: Text(_count==0?'我已阅读':'我已阅读($_count)',style: TextStyle(fontSize: 17,color: _count==0?Colors.blue:Colors.grey,decoration: TextDecoration.none),),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


///手机号验证
bool isChinaPhoneLegal(String str) {
  return RegExp(r"^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[1589])\d{8}$").hasMatch(str);
}

getVersionData(BuildContext context) async{
  Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'app/version', {'device':Platform.isAndroid?'android':'ios'});
  if(dict!=null){
    Map data = dict['data'];
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    if(int.parse(packageInfo.buildNumber)<data['version']){
      ysShowCenterAlertView(context, YSVersionView(
        buildNumber: '${data['version']}',
        content: data['up_log'],
        url: data['down_url'],
        isMust: data['is_force'],)
      );
    }
  }
}

class YSAppleView extends StatelessWidget {
  final ValueSetter valueSetter;
  const YSAppleView({Key key, this.valueSetter}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return  Container(
        height: 60,
        width: 60,
        margin: EdgeInsets.only(right: 30),
        child: SignInWithAppleButton(
          text: '',
          style: SignInWithAppleButtonStyle.black,
          onPressed: () async {
            final credential = await SignInWithApple.getAppleIDCredential(
              scopes: [
                AppleIDAuthorizationScopes.email,
                AppleIDAuthorizationScopes.fullName,
              ],
            );

            if (credential != null) {
              debugPrint("facebook userInfo : userId=${credential.userIdentifier}   email=${credential.email}  "
                  "giveName=${credential.givenName}   familyName=${credential.familyName} identityToken=${credential.identityToken}");
              valueSetter({'client_user':credential.userIdentifier,'identity_token':credential.identityToken});
            }
          },
        )
    );
  }
}

class ColorUtil {
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }
}

class DashLine extends StatelessWidget {
  const DashLine({
    Key key,
    this.width = 2.0,
    this.height = 1.0,
    this.color,
    this.direction = Axis.horizontal,
  }) : super(key: key);

  final double width; // 虚线宽度
  final double height; // 虚线高度
  final Color color; // 虚线颜色
  final Axis direction; // 虚线方向

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {

        final boxWidth = direction == Axis.horizontal
            ? constraints.constrainWidth()
            : constraints.constrainHeight();
        final dashCount = (boxWidth / (2 * width)).floor();

        return Flex(
          children: List.generate(dashCount, (_) {
            return SizedBox(
              width: direction == Axis.horizontal ? width : height,
              height: direction == Axis.horizontal ? height : width,
              child: DecoratedBox(
                decoration: BoxDecoration(color: color ?? Colors.grey),
              ),
            );
          }),
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          direction: direction,
        );
      },
    );
  }
}


class YSScreenChange {
  static YSScreenChange _instance;
  var _channel;
  YSScreenChange._internal() {
    _instance = this;
    _channel = MethodChannel('com.flutter.screen.MethodChannel');
  }

  factory YSScreenChange() => _instance ?? YSScreenChange._internal();

  change(int number){
    _channel.invokeMethod('setScreen',{'number': number});
  }

}

toPage(BuildContext context) async{
  SharedPreferences  _perfer = await SharedPreferences.getInstance();
  Map period = await ysRequestHttpNoLoading(context, requestType.get, 'chapter/list', {});
  if(period!=null){
    Map periodData = period['data'];
    _perfer.setInt('chapters', periodData['category_id']-1);
    int childId = periodData['child_id']??0;
    if(childId!=0){
      _perfer.setInt('childId', periodData['child_id']);
    }
    Map profile = await ysRequestHttpNoLoading(context, requestType.get, 'user/info/isComplete', {});
    if(profile!=null){
      Map profileData = profile['data'];
      bool isComplete = profileData['is_complete']??false;
      if(isComplete==true){
        _perfer.setBool('isMeans', true);
        Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
            builder: (context){
              return YSPage();
            }
        ), (route) => false);
      }else{
        Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
            builder: (context){
              return YSMeans(isFirst: true,);
            }
        ), (route) => false);
      }
    }
  }
}

toPage2(BuildContext context) async{
  Map profile = await ysRequestHttpNoLoading(context, requestType.get, 'user/info/isComplete', {});
  if(profile!=null){
    Map profileData = profile['data'];
    bool isComplete = profileData['is_complete']??false;
    if(isComplete==true){}else{
      Navigator.of(context,rootNavigator:true ).pushAndRemoveUntil(MaterialPageRoute(
          builder: (context){
            return YSMeans(isFirst: true,);
          }
      ), (route) => false);
    }
  }
}

checkValue(BuildContext context,{String tips = '当前绑定卫生院存在未使用券信息，无法更改至其他卫生院'}) async{
  Map info = await ysRequestHttpNoLoading(context, requestType.get, 'user/info', {});
  if(info!=null){
    String cardStr = info['id_card']??'';
    if(cardStr.isNotEmpty){
      Map dict1 = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getCommunityVouchers',
          {'idcard':User().idCard,'pageSize':1,'pageNum':10});
      if(dict1!=null){
        Map dict2 = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getUserCouponList',
            {'idcard':User().idCard,'pageSize':1,'pageNum':10});
        if(dict2!=null){
          // List array1 = dict1['data']['datas']??[];
          //array1.isEmpty&&
          var data = dict2['data'];
          bool isArray = data is List;
          // return;
          if(isArray){
            return true;
          }else{
            ysShowCenterAlertView(context, YSTipsAlertView2(
              tipsStr: tips,
              valueSetter: (value){
                if(User().routeStr.isNotEmpty){
                  Navigator.popUntil(context, ModalRoute.withName(User().routeStr));
                }
              },
            ));
          }
        }
      }
    }else{
      return true;
    }
  }
}