import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:amos_iot_login_tpl/mine/offline/dbAccess.dart';
import 'package:amos_iot_login_tpl/mine/offline/GetConfig.dart';
import '../MessageBox.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:flutter/rendering.dart';
import '../application.dart';
import 'package:amos_iot_login_tpl/mine/offline/flutter_toast.dart';
import '../routes.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/mine/offline/DateUtil.dart';
import '../TimeWeight.dart';
import 'package:image_picker/image_picker.dart';

class SignData {
  TextEditingController userName = new TextEditingController(); //打卡人员
  num type = 0; //                  0 上班  1下班
  String photoUrls = ""; // 照片
  TextEditingController remarks = new TextEditingController(); // 备注
}

class OfflineSign extends StatefulWidget {
  OfflineSign({Key key}) : super(key: key);

  ///消息提示
  static popUpMsg(String msg, {txtColor, bgColor, gravity, time}) {
    Fluttertoast.showToast(
        msg: msg,
        gravity: gravity ?? ToastGravity.CENTER,
        toastLength: time ?? Toast.LENGTH_SHORT,
        textColor: txtColor ?? Colors.white,
        backgroundColor: bgColor ?? Colors.black54);
  }

  @override
  _Sign createState() => new _Sign();
}

class _Sign extends State<OfflineSign> {

  Map<String,dynamic> _person;
  Map<String,dynamic> _result;
  bool canSign = true;
  String call = "打卡";


  SignData sign = new SignData();
  String theme = "blue";

  // 当前点的附件
  List<File> imageList = List();
  bool isAnimating = false;
  String REGEX_EMOJI = "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]";
  bool canOperate = true;


  // 获取换流站用户
  getPerson(BuildContext context) async {
    Database db;
    db = await DBAccess().createNewDb();
    _result= await DBAccess().getPerson(db);
    await DBAccess().closeDb(db);
  }

  bool _checkNeed() {
    if (sign.userName.text == null || sign.userName.text == "") {
      OfflineSign.popUpMsg("请选择打卡人！");
      return false;
    }
    if (imageList.length == 0 || imageList == null) {
      OfflineSign.popUpMsg("请上传打卡图片");
      return false;
    }
    return true;
  }

  // 人员选择
  void personSelect(BuildContext context) {
    try {
      final params = {
        "params":   json.encode(_result["persons"]),
        "title":"人员选择"
      };
      Application.navigateToPath(context, Routes.selectPersonList,params:params ).then((value) {
        if(value != null) {
          setState(() {
            _person = value;
            sign.userName.text = value["name"];
          });
        }
      });
    } catch (err) {
      FlutterToast.toastCenter("接口请求出错!");
    }
  }


  List<Widget> getImagesWidget() {
    List<Widget> widgets = List();
    imageList.forEach((c) {
      widgets.add(Stack(
        children: <Widget>[
          Container(
            width: 110,
            height: 70,
            margin: EdgeInsets.only(top: 15, left: 5),
            child: GestureDetector(
              child: c.path.substring(c.path.lastIndexOf(".")) == ".jpg"
                  ? Image.file(c)
                  : VideoViewSmallPage(c),
              onTap: () {
                String fileType = c.path.substring(c.path.lastIndexOf("."));
                if (fileType == ".jpg") {
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return ImageView(Image.file(c,repeat: ImageRepeat.repeat));
                  }));
                } else {
                  // 视频
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return VideoViewPage(c);
                  }));
                }
              },
            ),
//            padding: EdgeInsets.only(top: 10),
          ),
          Positioned(
              right: 0.0,
              top: 0.0,
              left: 100,
              child: InkWell(
                  child: Icon(Icons.cancel,
                      color: Theme.of(context).disabledColor),
                  onTap: () {
                    setState(() {
                      imageList.remove(c);
                    });
                  }))
        ],
      ));
    });

    // 拍照按钮
    widgets.add(Container(
        width: 110,
        height: 70,
        margin: EdgeInsets.only(top: 15, left: 10),
        alignment: Alignment.bottomCenter,
        child: Container(
          alignment: Alignment.center,
          decoration: new BoxDecoration(
              border:
              new Border.all(color: Colors.grey[200], width: 0.5), // 边色与边宽度
              color: Colors.grey[200]),
          padding: EdgeInsets.only(top: 10),
          child: Column(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  ImagePicker.pickImage(source: ImageSource.camera).then((c) {
                    setState(() {
                      if (c != null) {
                        imageList.insert(0, c);
                      }
                    });
                  });
                },
                onLongPress: () {
                  ImagePicker.pickVideo(source: ImageSource.camera).then((f) {
                    setState(() {
                      if (f != null) {
                        imageList.insert(0, f);
                      }
                    });
                  });
                },
                child: IconButton(
                  icon: Icon(
                    Icons.camera_alt,
                    size: 28,
                    color: GetConfig.getColor(theme),
                  ),
//                      onPressed: (){
//                        ImagePicker.pickImage(source: ImageSource.camera).then((c){
//                          setState(() {
//                            if(c!=null){
//                              _imageList.insert(0,c);
//                            }
//                          });
//                        });
//                      },
                ),
              )
            ],
          ),
        )));
    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "签到打卡",
          style: TextStyle(
            color: Colors.black,
            fontSize: 19,
          ),
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        leading: new Container(
          child: GestureDetector(
            onTap: () => Navigator.pop(context),
            child: Icon(Icons.keyboard_arrow_left,
                color: GetConfig.getColor(theme) /*GetConfig.getColor(theme)*/,
                size: 32),
          ),
        ),
      ),
      body: ModalProgressHUD(
          child: Container(
              child: SingleChildScrollView(
                  child: Container(
                      padding: EdgeInsets.only(bottom: 10),
                      child: Column(children: <Widget>[
                        /// 打卡人员
                        Row(
                          children: <Widget>[
                            Expanded(
                              child: Container(
                                padding: EdgeInsets.only(
                                    left: 20, top: 10, bottom: 5),
                                width: MediaQuery.of(context).size.width - 50,
                                child: Column(
                                  children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Expanded(
                                          child: Text(
                                            "*",
                                            style: TextStyle(color: Colors.red),
                                          ),
                                          flex: 0,
                                        ),
                                        Expanded(
                                          child: Text(
                                            "打卡人员",
                                            style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 18,
                                            ),
                                          ),
                                          flex: 19,
                                        ),
                                      ],
                                    ),
                                    Container(
                                      width: MediaQuery.of(context).size.width -
                                          50,
                                      padding: EdgeInsets.only(
                                        top: 5,
                                        bottom: 10,
                                      ),
                                      child: Row(
                                        children: <Widget>[
                                          Expanded(
                                            child: TextField(
                                              enableInteractiveSelection: false,
                                              autofocus: false,
                                              controller: sign.userName,
                                              onTap: () {
                                                FocusScope.of(context)
                                                    .requestFocus(
                                                        new FocusNode());
                                                personSelect(context);
                                              },
                                              maxLines: 1,
                                              decoration: InputDecoration(
                                                  contentPadding:
                                                      const EdgeInsets
                                                              .symmetric(
                                                          vertical: 10.0,
                                                          horizontal: 10),
                                                  border: InputBorder.none,
                                                  hintText: "请选择打卡人",
                                                  filled: true,
                                                  fillColor: Color.fromRGBO(
                                                      244, 244, 244, 1),
                                                  suffixIcon: Icon(
                                                    Icons.chevron_right,
                                                    color: GetConfig.getColor(
                                                        theme),
                                                  )),
                                              // inputFormatters: <TextInputFormatter>[
                                              //   LengthLimitingTextInputFormatter(255)//限制长度
                                              // ],
                                              // onEditingComplete: () {
                                              //   //print(this._controller.text);
                                              // },
                                              // maxLength: 1,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        Container(
                          child: GestureDetector(
                            child: Row(
                              children: <Widget>[
                                Expanded(
                                  flex: 10,
                                  child: Container(
                                    padding:
                                    EdgeInsets.only(left: 20, top: 10, bottom: 10),
                                    height: 50,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      children: <Widget>[
                                        Expanded(
                                          child: Text("*",style: TextStyle(color: Colors.red),),
                                          flex: 0,
                                        ),
                                        Expanded(
                                          child: Text(
                                            "打卡照片",
                                            textAlign: TextAlign.left,
                                            style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 18,
                                            ),
                                          ),
                                          flex: 9,
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            onTap: () {

                            },
                          ),
                        ),
                        Row(
                            children: getImagesWidget()
                        ),
                        Row(
                          children: <Widget>[
                            Expanded(
                              child: Container(
                                padding: EdgeInsets.only(
                                    left: 20, top: 10, bottom: 5),
                                width: MediaQuery.of(context).size.width - 50,
                                child: Column(
                                  children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Expanded(
                                          child: Text(
                                            "*",
                                            style: TextStyle(color: Colors.red),
                                          ),
                                          flex: 0,
                                        ),
                                        Expanded(
                                          child: Text(
                                            "打卡类型",
                                            style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 18,
                                            ),
                                          ),
                                          flex: 19,
                                        ),
                                      ],
                                    ),

                                    Container(
                                      width: MediaQuery.of(context).size.width - 20,
                                      padding: EdgeInsets.only(
                                        top: 5,
                                        bottom: 5,
                                      ),
                                      child: new Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.start,
                                        children: <Widget>[
                                          Expanded(
                                            flex: 1,
                                            child:Row(
                                              children: <Widget>[
                                                Radio(
                                                  value:0,
                                                  groupValue: sign.type,
                                                  onChanged: (val){
                                                    setState(() {
                                                      sign.type=val;
                                                    });
                                                  },
                                                ),
                                                GestureDetector(
                                                  child:  Text("上班打卡"),
                                                  onTap: (){
                                                    setState(() {
                                                      sign.type=0;
                                                    });
                                                  },
                                                )
                                              ],
                                            ),
                                            //带文字的单选按钮 value值=groupValue值 即选中状态
                                          ),
                                          Expanded(
                                            flex: 1,
                                            child:Row(
                                              children: <Widget>[
                                                Radio(
                                                  value: 1,
                                                  groupValue: sign.type,
                                                  onChanged: (val){
                                                    setState(() {
                                                      sign.type=val;
                                                    });
                                                  },
                                                ),
                                                GestureDetector(
                                                  child:  Text("下班打卡"),
                                                  onTap: (){
                                                    setState(() {
                                                      sign.type=1;
                                                    });
                                                  },
                                                )
                                              ],
                                            ),
                                            //带文字的单选按钮 value值=groupValue值 即选中状态
                                          )

//
//                                    Expanded(
//                                      flex: 1,
//                                      child: RadioListTile(
//                                          title: Text("重大隐患"),
//                                          value: 2,
//                                          groupValue:
//                                          hidedanger.dangerLevel,
//                                          onChanged: (value) {
//                                            setState(() {
//                                              print(value);
//                                              hidedanger.dangerLevel =
//                                                  value;
//                                            });
//                                          }),
//                                      //带文字的单选按钮 value值=groupValue值 即选中状态
//                                    ),
//                                    Expanded(
//                                      flex: 1,
//                                      child: RadioListTile(
//                                          title: Text("安全问题"),
//                                          value: 3,
//                                          groupValue:
//                                          hidedanger.dangerLevel,
//                                          onChanged: (value) {
//                                            setState(() {
//                                              print(value);
//                                              hidedanger.dangerLevel =
//                                                  value;
//                                            });
//                                          }),
//                                      //带文字的单选按钮 value值=groupValue值 即选中状态
//                                    ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        Container(
                            width: MediaQuery.of(context).size.width - 50,
                            height: 100,
                            margin: EdgeInsets.only(top: 5),
                            decoration: new BoxDecoration(
                                color: Color.fromRGBO(244, 244, 244, 1)),
                            child:TextField(
                              autofocus: false,
                              maxLength: 50,

                              controller: sign.remarks,
                              enableInteractiveSelection: true,
                              maxLines: null,
                              decoration: InputDecoration(
                                contentPadding: const EdgeInsets.symmetric(
                                    vertical: 1.0, horizontal: 1),
                                border: InputBorder.none,
                                hintText: "请输入备注信息",
                                filled: true,
                                fillColor: Color.fromRGBO(244, 244, 244, 1),
                              ),
                              inputFormatters: <TextInputFormatter>[
                                LengthLimitingTextInputFormatter(500),//限制长度
                                FilteringTextInputFormatter.deny(RegExp(REGEX_EMOJI))
                              ],
                              onEditingComplete: () {},
                            )
                        ),
                        Container(
                            width: MediaQuery.of(context).size.width - 210,
                            height: 140,
                            margin: EdgeInsets.only(top: 30),
                            decoration: new BoxDecoration(
                                color: Color.fromRGBO(244, 244, 244, 0)),
                            child:MaterialButton(
                              onPressed: onTapPress,
                              color: canSign ? Colors.blue : Colors.grey,
                              textColor: Colors.white,
                              child: new TimerWidget(title: call,),
                              padding: EdgeInsets.all(8),
                              shape: CircleBorder(),
                            )
                        ),
                      ])))),
        inAsyncCall: isAnimating,
        // demo of some additional parameters
        opacity: 0.7,
        progressIndicator: CircularProgressIndicator(),),
      resizeToAvoidBottomPadding: true,
    );
  }

  Future<bool> _checkExit(String type, String userId) async {
    Database db;
    db = await DBAccess().createNewDb();
    String date = DateUtil.timestampToDateByDay(new DateTime.now().millisecondsSinceEpoch);
    bool res = await DBAccess().hasSign(db,date,type,userId);
    await DBAccess().closeDb(db);
    if(res) {
      return true;
    } else {
      return false;
    }
  }

  Future<void> onTapPress() async {
    if(canSign) {
      bool flag = _checkNeed();
      if(flag) {
        // bool fl = await _checkExit(sign.type.toString(), _person["amosUserId"]) ;
        // if(sign.type.toString() == '1' && fl) {
        //   MessageBox.showMessageSignUpAndExitCurrentPage("下班卡已打", false, context);
        // } else if(sign.type.toString() == '0' && fl) {
        //   MessageBox.showMessageSignUpAndExitCurrentPage("上班卡已打", false, context);
        // } else {
        //
        // }

        Map<String, dynamic> map = new Map();
        if (null != this.imageList && this.imageList.length > 0) {
          List<String> image = [];
          this.imageList.forEach((f) {
            // fileData.add(Attachment.fromParams(file: f));
            image.add(f.path);
          });
          map["photos"] = json.encode(image);
        }
        Database db;

        db = await DBAccess().createNewDb();
        map["name"] = sign.userName.text;
        map["type"] = sign.type.toString();
        // map["photos"] = sign.photoUrls;
        map["userId"] = _person["amosUserId"] == null ? '' : _person["amosUserId"];
        map["bizOrgName"] = _person["bizOrgName"] == null ? '' : _person["bizOrgName"];
        map["bizOrgCode"] = _person["bizOrgCode"] == null ? '' : _person["bizOrgCode"];
        map["jobTitle"] = _person["jobTitle"];
        map["remarks"] = sign.remarks.text;
        map["signTime"] = DateUtil.timestampToDate(new DateTime.now().millisecondsSinceEpoch);
        map["date"] = DateUtil.timestampToDateByDay(new DateTime.now().millisecondsSinceEpoch);
        bool res = await DBAccess().insetIntoSign(db, map);
        await DBAccess().closeDb(db);
        if(res) {
          setState(() {
            imageList.clear();
            sign.userName.text = '';
            sign.photoUrls = '';
            sign.type = 0;
            sign.remarks.text = '';
          });
          MessageBox.showMessageSignAndExitCurrentPage("恭喜你，成功签到打卡！", false, context);
        } else {
          MessageBox.showMessageSignUpAndExitCurrentPage("打卡失败！", false, context);
        }
      }
    }
  }

  // hasSign() async {
  //   Database db;
  //   db = await DBAccess().createNewDb();
  //   String date = DateUtil.timestampToDateByDay(new DateTime.now().millisecondsSinceEpoch);
  //   bool res = await DBAccess().hasSign(db,date,null,null);
  //   await DBAccess().closeDb(db);
  //   if(res) {
  //     setState(() {
  //       canSign = true;
  //       call = "打卡";
  //     });
  //   }
  // }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getInitInfo();
    getPerson(this.context).then((res) {
      notice();
    });;
  }



  void getInitInfo() async {
    // hasSign();
    await SharedPreferences.getInstance().then((data) {
      this.theme = data.getString("theme") ?? "blue";
    }).then((data) {});
  }

  Future<void> notice() async {
    Database db;
    db = await DBAccess().createNewDb();
    Map<String,dynamic> res  = await DBAccess().getFirstSign(db);
    await DBAccess().closeDb(db);
    var third = 60*60*1000*24*30;
    if(res != null) {
      DateTime date = DateTime.parse(res["sign"][0]["signTime"]);
      DateTime date1 = new DateTime.now();
      Duration diff = date1.difference(date);
      print(diff.inDays);

      if(diff.inDays > 30) {
        MessageBox.showMessageSignUpAndExitCurrentPage("打卡数据超期未更新，请连接网线，上传打卡数据", true, context);
      }
    }

    // if(true) {
    //   MessageBox.showMessageSignUpAndExitCurrentPage("打卡数据超期未更新，请连接网线，上传打卡数据", false, context);
    // }
  }
}
