import 'package:flutter/material.dart';
import 'commonFun.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../pages/Works/SBBJ/sbbj_content.dart';
import 'doJSON.dart';

//删除消息对话框。自定义透明背景窗口，类似对话框
class CustomDialogJ extends StatefulWidget {
  CustomDialogJ({Key key, this.title = "", this.theKey = "", this.index = -1}) : super(key: key);
  String title;
  String theKey;
  int index;

  _CheckBoxDemoState createState() => _CheckBoxDemoState();
}

//需要监听软键盘的弹出和隐藏 主要用 WidgetsBindingObserver 这个继承类
//https://www.jianshu.com/p/872e23124470
class _CheckBoxDemoState extends State<CustomDialogJ> with WidgetsBindingObserver {
  String getTitle(int index) {}
  int mapLen = 0;

  @override
  void dispose() {
    // TODO: implement dispose
    //销毁
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //mapLen = mapGetSbbjGetData.length;
    print("mapLen = $mapLen");
    getContent();
    //初始化
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘
          bViewInsets = false;
        } else {
          //显示键盘
          bViewInsets = true;
        }
      });
    });
  }

  String strContent = '';
  bool bModifiable = false;
  bool bViewInsets = false;

  getContent() async {
    // strContent = ("" == mapGetSbbjGetData[widget.theKey].toString())
    //     ? "（无数据）"
    //     : mapGetSbbjGetData[widget.theKey].toString();
    // widget.title =
    //     "第 ${widget.index + 1} 项（共 ${mapLen} 项） ： " + mapGetSbbjGetDataText[widget.theKey];
    getPreBtn_NextBtn();

    //时间戳转换
    if(strContent.isNotEmpty && ('addtime' == widget.theKey || 'createtime' == widget.theKey)) {
      strContent = getDate(int.parse(strContent));
    }

    myController.text = strContent;
    bModifiable = false;//mapGetSbbjGetDataModifiable[widget.thekey];
    setState(() {});
  }

  Widget getBtnSizeX({@required text, width = 60.0, height = 30.0, onPressedFun}) {
    return Container(
      color: Colors.white12, //onPressedFun为null时无效
      width: width,
      height: height,
      child: RaisedButton(
        padding: EdgeInsets.all(0),
        textColor: Colors.black,
        child: Text(text),
        onPressed: onPressedFun,
      ),
    );
  }

  Future<bool> alertDialog(String title, String content, var onPresse) async {
    return await showDialog(
      barrierDismissible: false, //表示点击灰色背景的时候是否消失弹出框
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(title),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text("确定"),
              onPressed: onPresse,
            ),
            FlatButton(
              child: Text("取消"),
              onPressed: () {
                Navigator.pop(context, false);
              },
            ),
          ],
        );
      },
    );
  }

  //解决第一次进入报错问题。因为getPreBtn_NextBtn()还未执行，preBtn和nextBtn为空
  Widget preBtn = Container(
    color: Colors.white12, //onPressedFun为null时无效
    width: 60.0,
    height: 30.0,
    child: RaisedButton(
      padding: EdgeInsets.all(0),
      textColor: Colors.black,
      child: Text('上一项'),
      onPressed: null,
    ),
  );

  Widget nextBtn = Container(
    color: Colors.white12, //onPressedFun为null时无效
    width: 60.0,
    height: 30.0,
    child: RaisedButton(
      padding: EdgeInsets.all(0),
      textColor: Colors.black,
      child: Text('下一项'),
      onPressed: null,
    ),
  );

  getPreBtn_NextBtn() {
    preBtn = getBtnSizeX(
      text: "上一项",
      onPressedFun: null,
    );
    nextBtn = getBtnSizeX(
      text: "下一项",
      onPressedFun: null,
    );

    if (widget.index > 0 && mapLen > 0) {
      preBtn = getBtnSizeX(
        text: "上一项",
        onPressedFun: () async {
          if (widget.index > 0) {
            widget.index--;
            //widget.theKey = mapGetSbbjGetData.keys.elementAt(widget.index);
            getContent();
          }
        },
      );
    }

    if (widget.index < (mapLen - 1) && mapLen > 0) {
      nextBtn = getBtnSizeX(
        text: "下一项",
        onPressedFun: () async {
          if (widget.index < mapLen - 1) {
            widget.index++;
            //widget.theKey = mapGetSbbjGetData.keys.elementAt(widget.index);
            getContent();
          }
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    Size mediaSize = MediaQuery.of(context).size;
    // TODO: implement build
    return WillPopScope(
      child: Scaffold(
        //type: MaterialType.transparency,
        //color: Colors.transparent,
        //backgroundColor: Colors.transparent,
        //color: Colors.blue,
        backgroundColor: Color.fromRGBO(212, 212, 212, 0.6),
        body: SafeArea(
          child: Stack(
            children: <Widget>[
              Container(
                alignment: Alignment(0, 0.2),
                child: Container(
                  height: bViewInsets ? mediaSize.height * 0.4 : mediaSize.height * 0.85,
                  width: mediaSize.width * 0.95,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    //border: Border.all(width: 1.0, color: Colors.black),
                    borderRadius: BorderRadius.all(
                      Radius.circular(3),
                    ),
                  ),
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: Stack(
                          children: <Widget>[
                            Align(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                "     ${widget.title}",
                                style: TextStyle(
                                  fontSize: 15.0,
                                ),
                              ),
                            ),
                            Align(
                              alignment: Alignment.centerRight,
                              child: InkWell(
                                child: Icon(Icons.close),
                                onTap: () {
                                  Navigator.pop(context); //关闭弹框，播放输入视频地址
                                },
                              ),
                            )
                          ],
                        ),
                      ),
                      Divider(),
                      Container(
                        padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
                        width: double.infinity,
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(width: 1.0, color: Colors.blue),
                            borderRadius: BorderRadius.all(
                              Radius.circular(3),
                            ),
                          ),
                          padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                          width: double.infinity,
                          height: mediaSize.height * 0.15,
                          child: SingleChildScrollView(
                            child: Container(
                              child: TextField(
                                //textAlign: TextAlign.right,
                                keyboardType: TextInputType.multiline,
                                maxLines: 5,
                                minLines: 1,
                                style: TextStyle(fontSize: 14),
                                decoration: InputDecoration(
                                  hintText: '請輸入字段信息',
                                  border: InputBorder.none, //TextField去掉下划线
                                  contentPadding: EdgeInsets.only(right: 0),
                                ),
                                controller: myController,
                                enabled: bModifiable,
                                //利用控制器初始化文本
                                onChanged: (value) {},
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 5),
                      bViewInsets
                          ? SizedBox(height: 0)
                          : Container(
                              padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
                              width: double.infinity,
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(width: 1.0, color: Colors.blue),
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(3),
                                  ),
                                ),
                                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                                width: double.infinity,
                                height: mediaSize.height * 0.45,
                                child: SingleChildScrollView(
                                  child: Container(
                                    //child: Text(strContent),
                                    child: Text(strContent),
                                  ),
                                ),
                              ),
                            ),
                      Expanded(
                        child: Container(),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          getBtnSizeX(
                            text: "复制",
                            onPressedFun: () {
                              // Flutter 复制文本到剪贴板
                              Clipboard.setData(ClipboardData(text: strContent));
                              //showToast('帮助信息已复制到剪贴板', textAlign: TextAlign.left);
                              Fluttertoast.showToast(
                                  msg: '联系人信息已复制到剪贴板', gravity: ToastGravity.BOTTOM);
                            },
                          ),
                          getBtnSizeX(
                            text: "返回",
                            onPressedFun: () {
                              Navigator.pop(context); //关闭弹框，播放输入视频地址
                            },
                          ),
                          preBtn,
                          nextBtn,
                        ],
                      ),
                      SizedBox(height: 35),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      onWillPop: () {
        // 屏蔽点击返回键的操作
        //player.pause();
        Navigator.pop(context);
      },
    );
  }
}
