import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:amos_iot_login_tpl/mine/offline/GetConfig.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'loading_dialog.dart';
import 'package:amos_iot_login_tpl/mine/offline/request.dart';
import 'package:shared_preferences/shared_preferences.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 'TimeWeight.dart';
import 'MessageBox.dart';
import 'package:amos_iot_login_tpl/mine/offline/DateUtil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:dio/dio.dart';

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

class Sign extends StatefulWidget {
  Sign({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<Sign> {

  Map<String,dynamic> _person;
  Map<String,dynamic> _result;
  bool canSign = true;
  bool isSubmit = true;

  SignData sign = SignData();
  String theme = 'blue';

  // 当前点的附件
  List<File> imageList = [];
  bool isAnimating = false;

  String REGEX_EMOJI = "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]";

  // TextField(
  // cursorColor: Theme.of(context).cursorColor,
  // inputFormatters: [
  //
  // ],
  // )

  // _upDateImg(List<File> att) async {
  //
  //   //var bizCode = "latent_danger";
  //   await updataImg(att).then((data) {
  //     if (mounted) {
  //       setState(() {
  //         if (data.success) {
  //           sign.photoUrls = data.message;
  //
  //           // HiddenDangerFound.popUpMsg("图片上传成功!");
  //         } else {
  //           isAnimating = false;
  //           Sign.popUpMsg(data.message);
  //           setState(() {
  //             imageList.clear();
  //           });
  //         }
  //
  //         isAnimating = false;
  //       });
  //     }
  //   }).catchError((onError) {
  //     setState(() {
  //       isAnimating = false;
  //     });
  //   });
  // }

  _upDateImg(images) async {
    // showDialog(
    //     context: context,
    //     builder: (ctx) {
    //       return LoadingDialog(
    //         barrierDismissible: true,
    //       );
    //     });
    if (images is List && images.isEmpty) {
      return;
    }
    setState(() {
      isAnimating = true;
    });

    bool uoloadSucess = true;
    List<String> imgUrls = new List();
      for (int i = 0; i < images.length; i++) {
        File file = images[i];

        File path=await imageCompressAndGetFile(file);

        var name = file.path.substring(file.path.lastIndexOf("/") + 1, file.path.length);
        String imageType = name.substring(name.lastIndexOf(".") + 1, name.length);
        var image = await MultipartFile.fromFile(
          path.path,
          filename: name,
        );
        FormData formData = FormData.fromMap({"files": image});
        // 使用 dio 上传图片
        var response = await HttpRequest.uploadImage(data: formData);

        if (response["status"] == 200) {
          //String url = response["result"]["url"].toString().replaceAll(',', '');
          //url.replaceAll(',', '');
          imgUrls.add(response["result"]["url"]);

          // return response["result"]["url"];
        } else {
          // return null;
          uoloadSucess = false;
          break;
        }
      }
    if (imgUrls.length == 1) {
      sign.photoUrls =  imgUrls[0];
    } else {
      sign.photoUrls =  imgUrls.join(",");
    }

    setState(() {
      isAnimating = false;
    });
  }

  Future<File> imageCompressAndGetFile(File file) async {
    if (file.lengthSync() < 200 * 1024) {
      return file;
    }
    var quality = 100;
    if (file.lengthSync() > 4 * 1024 * 1024) {
      quality = 50;
    } else if (file.lengthSync() > 2 * 1024 * 1024) {
      quality = 60;
    } else if (file.lengthSync() > 1 * 1024 * 1024) {
      quality = 70;
    } else if (file.lengthSync() > 0.5 * 1024 * 1024) {
      quality = 80;
    } else if (file.lengthSync() > 0.25 * 1024 * 1024) {
      quality = 90;
    }
    var dir = await path_provider.getTemporaryDirectory();
    var targetPath = dir.absolute.path +"/"+DateTime.now().millisecondsSinceEpoch.toString()+ ".jpg";

    var result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      minWidth: 600,
      quality: quality,
      rotate: 0,
    );

    print("压缩后：${file.lengthSync() / 1024}");

    print("压缩后：${result.lengthSync() / 1024}");

    return result;
  }

  // 获取换流站用户
  void getPerson(BuildContext context) async {
    Future.delayed(Duration.zero, () {
      showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              barrierDismissible: true,
            );
          });

      HttpRequest.getPersonList().then((res) {
        Navigator.of(context).pop();
        if (res["status"] == 200) {
          _result = res["result"];
          // Provider.of<PersonViewModel>(context, listen: false)
          //     .persons = res["result"];
        }
      }).catchError((_) {
        Navigator.of(context).pop();
      });
    });
  }

  bool _checkNeed() {
    if (sign.userName.text == null || sign.userName.text == "") {
      Sign.popUpMsg("请选择打卡人！");
      return false;
    }
    if (imageList.length == 0 || imageList == null) {
      Sign.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);
                      }
                    });
                    _upDateImg(imageList);
                  });
                },
                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: const Text(
          '签到打卡',
          style: TextStyle(
            color: Colors.black,
            fontSize: 19,
          ),
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        leading: 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: 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: const EdgeInsets.only(top: 5),
                            decoration: const BoxDecoration(
                                color: Color.fromRGBO(244, 244, 244, 1)),
                            child:TextField(
                              autofocus: false,
                              maxLength: 50,
                              textInputAction: TextInputAction.done,
                              controller: sign.remarks,
                              enableInteractiveSelection: true,
                              maxLines: null,
                              decoration: const InputDecoration(
                                contentPadding:  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: const EdgeInsets.only(top: 30),
                            decoration:  const BoxDecoration(
                                color: Color.fromRGBO(244, 244, 244, 0)),
                            child:MaterialButton(
                              onPressed: onTapPress,
                              color: canSign ? Colors.blue : Colors.grey,
                              textColor: Colors.white,
                              child: TimerWidget(title:'打卡'),
                              padding: const EdgeInsets.all(8),
                              shape: const CircleBorder(),
                            )
                        ),
                      ]
                      )
                  )
          ),
        inAsyncCall: isAnimating,
        // demo of some additional parameters
        opacity: 0.7,
        progressIndicator: CircularProgressIndicator(),),
      // persistentFooterButtons: <Widget>[
      //   Row(
      //     children: <Widget>[
      //       Container(
      //         width: (MediaQuery.of(context).size.width / 2) - 16,
      //         height: 60,
      //         margin: EdgeInsets.only(left: 0),
      //         child: new MaterialButton(
      //           color: Color.fromRGBO(242, 246, 249, 1),
      //           height: 60,
      //           textColor: Colors.black,
      //           child: new Text(
      //             '重置',
      //             style: TextStyle(fontSize: 24),
      //           ),
      //           onPressed: () {
      //             if (canOperate) {
      //               // reSetValue();
      //             } else {
      //               // HiddenDangerFound.popUpMsg("网速较慢！请等待图片上传完成");
      //             }
      //           },
      //         ),
      //       ),
      //       Container(
      //         width: (MediaQuery.of(context).size.width / 2),
      //         child: new MaterialButton(
      //           color: GetConfig.getColor(theme),
      //           height: 60,
      //           textColor: Colors.white,
      //           child: new Text('确定', style: TextStyle(fontSize: 24)),
      //           onPressed: () {
      //             //必填项判断
      //             if (canOperate) {
      //               if (_checkNeed()) {
      //                 // _upDateImg(imageList);
      //                 // _saveHideDangerInfo(hidedanger);
      //               }
      //             } else {
      //               // HiddenDangerFound.popUpMsg("正在执行操作！请稍等...");
      //             }
      //           },
      //         ),
      //       ),
      //     ],
      //   ),
      // ],
      resizeToAvoidBottomPadding: true,
    );
  }

  Future<void> onTapPress() async {
    if(isSubmit){
      isSubmit = false;
    bool flag = _checkNeed();
    if(flag) {
      // HttpRequest.getHasSign(sign.type.toString(), _person["amosUserId"]).then((res) {
      //   if (res["status"] == 200) {
      //     bool fl = res["result"];
      //     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 = {};
      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"] = sign.photoUrls;
      }

      map["source"] = '1';  // 来源在线打卡
      map["name"] = sign.userName.text;
      map["type"] = sign.type.toString();
      // map["photos"] = sign.photoUrls;
      map["signUserId"] = _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);
      HttpRequest.saveSign(map).then((value) {
        if(value["result"]) {
          setState(() {
            imageList.clear();
            sign.userName.text = '';
            sign.photoUrls = '';
            sign.type = 0;
            sign.remarks.text = '';
          });
          MessageBox.showMessageSignAndExitCurrentPage("恭喜你，成功签到打卡！", false, context);
        } else {
          MessageBox.showMessageSignUpAndExitCurrentPage("打卡失败！", false, context);
        }
        isSubmit = true;
      });
    }
    else{
      isSubmit =true;
    }
  }
  }


  // hasSign(String type) async {
  //   HttpRequest.getHasSign(type).then((res){
  //     if (res["status"] == 200) {
  //       setState(() {
  //         canSign = res["result"];
  //       });
  //     }
  //   }).catchError((_) {
  //     Navigator.of(context).pop();
  //   });
  // }


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

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