import 'dart:io';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_ui/form/input_datepicker.dart';
import 'package:amos_flutter_utils/date_utils.dart';
import 'package:base/model/tree_node_model.dart';
import 'package:image_picker/image_picker.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/utils/request.dart';
import 'package:base/widgets/loading_dialog.dart';
import 'package:flutter/material.dart';
import 'package:jcs_airport/utils/time.dart';
import 'package:flutter/services.dart';
import 'package:amos_iot_login_tpl/mine/offline/dbAccess.dart';
import 'package:sqflite/sqflite.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import '../../sign/MessageBox.dart';

import 'package:jcs_airport/view/sign/application.dart';
import 'package:jcs_airport/view/sign/routes.dart';
import 'package:safe_control/view/CheckExecute/checkexec_inspection_list.dart';


class HideConstDanger {
  TextEditingController defectEquipment = TextEditingController(); //缺陷设备
  TextEditingController defectDescribe = TextEditingController(); //缺陷描述
  TextEditingController defectType = TextEditingController(); //缺陷类型
  num defectLevel = 1; //缺陷等级   1 一般隐患  2重大隐患
  String defectDiscoverDate ;
  String defectEquipmentIds ;
  String planClearDate ;
  num defectResource = 1; //缺陷来源 0-消防巡查 1-消防维保 2-消防检测 3-消防物联 4-其他
  TextEditingController defectDiscover = TextEditingController(); //发现人
  TextEditingController defectResponsible = TextEditingController(); //责任人

  String defectImg = '';
}

class HiddenOfflineDefectFound extends StatefulWidget {
  final num checkId;
  final String equipmentId;
  final String equipmentName;
  List<UNCheckInput> unCheckInputData;

  HiddenOfflineDefectFound({this.checkId, this.unCheckInputData, this.equipmentId, this.equipmentName });

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

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

class _HiddenOfflineDefectFound extends State<HiddenOfflineDefectFound> {
  HideConstDanger hidedanger = HideConstDanger();
  List _result = new List();
  String theme = 'blue';
  TreeNodeModel model = TreeNodeModel();

  List<UNCheckInput> oldCheckInputData = [];

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

  ScrollController scrollController = new ScrollController();

  Future<void> _saveHideDangerInfo(HideConstDanger hidedanger) async {
    setState(() {
      isAnimating = true;
      canOperate = false;
    });
    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);
      });
      hidedanger.defectImg = json.encode(image);
    }

    String disDate = "";
    String planDate = "";
    if(hidedanger.defectDiscoverDate != null) {
      disDate = hidedanger.defectDiscoverDate + " 00:00:00";
    }
    if(hidedanger.defectDiscoverDate != null) {
      planDate = hidedanger.planClearDate + " 00:00:00";
    }

    // 根据输入参数拼接请求body
    var jsonData = {
      'defectLevel': hidedanger.defectLevel,
      'defectEquipmentIds': hidedanger.defectEquipmentIds,
      'defectEquipmentName': hidedanger.defectEquipment.text,
      'defectDescribe': hidedanger.defectDescribe.text,
      'defectResource': hidedanger.defectResource,
      'defectType': hidedanger.defectType.text,
      'defectImg': hidedanger.defectImg,
      'defectDiscoverDate': disDate,
      'defectDiscover': hidedanger.defectDiscover.text,
      'defectResponsible': hidedanger.defectResponsible.text,
      'planClearDate': planDate
    };

    Database db;
    db = await DBAccess().createNewDb();
    bool res = await DBAccess().insetIntoDefect(db, jsonData);
    await DBAccess().closeDb(db);
    if(res) {
      MessageBox.showMessageSignUpAndExitCurrentPage("保存成功！", true, context);
    } else {
      MessageBox.showMessageSignUpAndExitCurrentPage("保存失败！", true, context);
    }
  }


  Future<void> reSetValue() async {
    setState(() {
      hidedanger.defectDescribe.text = '';
      hidedanger.defectEquipment.text = '';
      hidedanger.defectType.text = '';
      hidedanger.defectResource = 0;
      hidedanger.defectLevel = 0;
      hidedanger.defectDiscoverDate = '';
      hidedanger.defectDiscover.text= '';
      hidedanger.planClearDate = '';
      hidedanger.defectResponsible.text = '';
      imageList = [];
    });
  }

  bool _checkNeed() {
    if (hidedanger.defectLevel == -1) {
      HiddenOfflineDefectFound.popUpMsg('请选择缺陷等级！');
      return false;
    }
    if (hidedanger.defectDescribe.text == null || hidedanger.defectDescribe.text == '') {
      HiddenOfflineDefectFound.popUpMsg('请填写缺陷描述！');
      return false;
    }
    if (hidedanger.defectResource == -1) {
      HiddenOfflineDefectFound.popUpMsg('请选择缺陷来源！');
      return false;
    }
    // if (imageList.isEmpty || imageList == null) {
    //   HiddenOfflineDefectFound.popUpMsg('请上传隐患图片');
    //   return false;
    // }
    return true;
  }

  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;
  }

  _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) {
      hidedanger.defectImg =  imgUrls[0];
    } else {
      hidedanger.defectImg =  imgUrls.join(",");
    }

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

  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) {
    const SEX = ['消防巡检', '消防维保', '消防检测','消防物联','其他'];

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '缺陷添加',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ),
      body: ModalProgressHUD(
        child: SingleChildScrollView(
          controller: scrollController,
          child: Container(
            padding: const EdgeInsets.only(bottom: 10),
            child: Column(
              children: <Widget>[
                ///缺陷等级
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 20, top: 10, bottom: 5),
                        width: MediaQuery.of(context).size.width - 50,
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: const <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: const EdgeInsets.only(
                                top: 5,
                                bottom: 5,
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: Row(
                                      children: <Widget>[
                                        Radio(
                                          activeColor: Theme.of(context).primaryColor,
                                          value: 1,
                                          groupValue: hidedanger.defectLevel,
                                          onChanged: (val) {
                                            setState(() {
                                              hidedanger.defectLevel = val;
                                            });
                                          },
                                        ),
                                        GestureDetector(
                                          child: const Text('一般缺陷'),
                                          onTap: () {
                                            setState(() {
                                              hidedanger.defectLevel = 1;
                                            });
                                          },
                                        )
                                      ],
                                    ),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Row(
                                      children: <Widget>[
                                        Radio(
                                          activeColor: Theme.of(context).primaryColor,
                                          value: 2,
                                          groupValue: hidedanger.defectLevel,
                                          onChanged: (val) {
                                            setState(() {
                                              hidedanger.defectLevel = val;
                                            });
                                          },
                                        ),
                                        GestureDetector(
                                          child: const Text('严重缺陷'),
                                          onTap: () {
                                            setState(() {
                                              hidedanger.defectLevel = 2;
                                            });
                                          },
                                        )
                                      ],
                                    ),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Row(
                                      children: <Widget>[
                                        Radio(
                                          activeColor: Theme.of(context).primaryColor,
                                          value: 3,
                                          groupValue: hidedanger.defectLevel,
                                          onChanged: (val) {
                                            setState(() {
                                              hidedanger.defectLevel = val;
                                            });
                                          },
                                        ),
                                        GestureDetector(
                                          child: const Text('危急缺陷'),
                                          onTap: () {
                                            setState(() {
                                              hidedanger.defectLevel = 3;
                                            });
                                          },
                                        )
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                ///缺陷设备
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 20, top: 10, bottom: 5),
                        width: MediaQuery.of(context).size.width - 50,
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: const <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: const EdgeInsets.only(
                                top: 5,
                                bottom: 10,
                              ),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: TextField(
                                      onSubmitted: (text) {
                                        FocusScope.of(context).requestFocus(FocusNode());
                                      },
                                      enabled: false,
                                      autofocus: false,
                                      controller: hidedanger.defectEquipment,
                                      enableInteractiveSelection: true,
                                      maxLines: 3,
                                      decoration: const InputDecoration(
                                        contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 10),
                                        border: InputBorder.none,
                                        hintText: '自动带入巡查设备名称',
                                        filled: true,
                                        fillColor: Color.fromRGBO(244, 244, 244, 1),
                                      ),
                                      inputFormatters: <TextInputFormatter>[
                                        LengthLimitingTextInputFormatter(50) //限制长度
                                      ],
                                      onEditingComplete: () {
                                        //print(this._controller.text);
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                ///缺陷描述
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 20, top: 10, bottom: 5),
                        width: MediaQuery.of(context).size.width - 50,
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: const <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,
                              decoration: const BoxDecoration(color: Color.fromRGBO(244, 244, 244, 1)),
                              padding: const EdgeInsets.only(
                                top: 5,
                                bottom: 10,
                              ),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: TextField(
                                      autofocus: false,
                                      maxLength: 500,
                                      controller: hidedanger.defectDescribe,
                                      enableInteractiveSelection: true,
                                      maxLines: null,
                                      decoration: const InputDecoration(
                                        contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 10),
                                        border: InputBorder.none,
                                        hintText: '请输入缺陷描述信息',
                                        filled: true,
                                        fillColor: Color.fromRGBO(244, 244, 244, 1),
                                      ),
                                      inputFormatters: <TextInputFormatter>[
                                        LengthLimitingTextInputFormatter(500) //限制长度
                                      ],
                                      onEditingComplete: () {},
                                    )
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                ///缺陷来源
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 20, top: 10, bottom: 5),
                        width: MediaQuery.of(context).size.width - 50,
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: const <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: const EdgeInsets.only(
                                top: 5,
                                bottom: 5,
                                left: 20
                              ),
                              child: DropdownButtonFormField<String>(
                                isExpanded: true,
                                decoration: const InputDecoration(
                                    focusColor: Colors.grey
                                  // border: OutlineInputBorder(gapPadding: 1.0), labelText: ''
                                ),
                                // 设置默认值
                                focusColor: Colors.grey,
                                //style: TextStyle(backgroundColor: Colors.grey),
                                value: '消防巡检',
                                // 选择回调
                                onChanged: (String newPosition) {
                                  num i = 0;
                                  if(newPosition == "消防巡检") {
                                    i = 0;
                                  } else if(newPosition == "消防维保") {
                                    i = 1;
                                  } else if(newPosition == "消防检测") {
                                    i = 2;
                                  } else if(newPosition == "消防物联") {
                                    i = 3;
                                  } else if(newPosition == "其他") {
                                    i = 4;
                                  }
                                  hidedanger.defectResource = i;
                                  setState(() {});
                                },
                                // 传入可选的数组
                                items: SEX.map((String sex) {
                                  return DropdownMenuItem(value: sex, child: Text(sex));
                                }).toList(),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),
                ///缺陷类型
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.only(left: 20, top: 10, bottom: 5),
                        width: MediaQuery.of(context).size.width - 50,
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: const <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: const EdgeInsets.only(
                                top: 5,
                                bottom: 10,
                              ),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: TextField(
                                      onSubmitted: (text) {
                                        FocusScope.of(context).requestFocus(FocusNode());
                                      },
                                      autofocus: false,
                                      controller: hidedanger.defectType,
                                      enableInteractiveSelection: true,
                                      maxLines: 1,
                                      decoration: const InputDecoration(
                                        contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 10),
                                        border: InputBorder.none,
                                        hintText: '请输入缺陷缺陷类型',
                                        filled: true,
                                        fillColor: Color.fromRGBO(244, 244, 244, 1),
                                      ),
                                      inputFormatters: <TextInputFormatter>[
                                        LengthLimitingTextInputFormatter(50) //限制长度
                                      ],
                                      onEditingComplete: () {
                                        //print(this._controller.text);
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                ///图片
                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()
                ),
                Container(
                  color: Colors.grey[100],
                  height: 10,
                ),

                /// 发现日期
                Container(
                  padding: const EdgeInsets.only(left: 20, top: 10, bottom: 10),
                  child: Column(
                    children: <Widget>[
                      Row(
                        children: const <Widget>[
                          Expanded(
                            child: Text(
                              '发现日期',
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 18,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                          margin: const EdgeInsets.only(top: 30, right: 15),
                          decoration: const BoxDecoration(color: Color.fromRGBO(244, 244, 244, 1)),
                          child: InputDatePicker(
                            onChange: (val) {
                              setState(() {
                                hidedanger.defectDiscoverDate = DateUtils.formatDate(val, format: 'yyyy-MM-dd HH:mm:ss');
                              });
                            },
                            value: hidedanger.defectDiscoverDate ?? '',
                          )),
                    ],
                  ),
                ),
                /// 发现人
                Container(
                  padding: const EdgeInsets.only(left: 20, top: 10, bottom: 10),
                  child: Column(
                    children: <Widget>[
                      Row(
                        children: const <Widget>[
                          Expanded(
                            child: Text(
                              '发现人',
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 18,
                              ),
                            ),
                          ),
                        ],
                      ),
                      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: hidedanger.defectDiscover,
                                onTap: () {
                                  FocusScope.of(context)
                                      .requestFocus(
                                      new FocusNode());
                                  defectDiscoverSelect(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: Colors.grey,
                                    )),
                                // inputFormatters: <TextInputFormatter>[
                                //   LengthLimitingTextInputFormatter(255)//限制长度
                                // ],
                                // onEditingComplete: () {
                                //   //print(this._controller.text);
                                // },
                                // maxLength: 1,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                /// 计划消缺日期
                Container(
                  padding: const EdgeInsets.only(left: 20, top: 10, bottom: 10),
                  child: Column(
                    children: <Widget>[
                      Row(
                        children: const <Widget>[
                          Expanded(
                            child: Text(
                              '计划消缺日期',
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 18,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                          margin: const EdgeInsets.only(top: 30, right: 15),
                          decoration: const BoxDecoration(color: Color.fromRGBO(244, 244, 244, 1)),
                          child: InputDatePicker(
                            onChange: (val) {
                              setState(() {
                                   hidedanger.planClearDate = DateUtils.formatDate(val, format: 'yyyy-MM-dd HH:mm:ss');
                              });
                            },
                            value: hidedanger.planClearDate ?? '',
                          )),
                    ],
                  ),
                ),
                /// 责任人
                Container(
                  padding: const EdgeInsets.only(left: 20, top: 10, bottom: 10),
                  child: Column(
                    children: <Widget>[
                      Row(
                        children: const <Widget>[
                          Expanded(
                            child: Text(
                              '责任人',
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 18,
                              ),
                            ),
                          ),
                        ],
                      ),
                      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: hidedanger.defectResponsible,
                                onTap: () {
                                  FocusScope.of(context)
                                      .requestFocus(
                                      new FocusNode());
                                  defectResponsibleSelect(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: Colors.grey,
                                    )),
                                // inputFormatters: <TextInputFormatter>[
                                //   LengthLimitingTextInputFormatter(255)//限制长度
                                // ],
                                // onEditingComplete: () {
                                //   //print(this._controller.text);
                                // },
                                // maxLength: 1,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const 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 {
                    HiddenOfflineDefectFound.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 {
                    HiddenOfflineDefectFound.popUpMsg("正在执行操作！请稍等...");
                  }
                },
              ),
            ),
          ],
        ),
      ],
      resizeToAvoidBottomPadding: false,
    );
  }

  // 获取换流站用户
  void getPerson(BuildContext context) async {
    Future.delayed(Duration.zero, () async {
      showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              barrierDismissible: true,
            );
          });
      Database db;
      db = await DBAccess().createNewDb();
      List re = await DBAccess().getUnitPerson(db);

      for(var i in re  ) {
        Map<String, String> result = new Map();
        result.putIfAbsent("name", () => i["name"]);
        _result.add(result);
      }
      scrollController.jumpTo(scrollController.position.minScrollExtent);
      Navigator.of(context).pop();
    });
  }

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

  // 人员选择
  void defectDiscoverSelect(BuildContext context) {
    try {
      final params = {
        "params":   json.encode(_result),
        "title":"人员选择",
        "flag":"defectDiscover"
      };
      Application.navigateToPath(context, Routes.selectPersonDefectList,params:params ).then((value) {
        if(value != null) {
          setState(() {
            print(value);
            if(value["flag"] == "defectDiscover") {
              hidedanger.defectDiscover.text = value["name"];
            }
          });
        }
      });
    } catch (err) {
      print(err);
    }
  }

  @override
  void initState() {
    super.initState();
    getInitInfo();
    hidedanger.defectDiscoverDate = TimeUtils.getDayBeginN();
    hidedanger.planClearDate = TimeUtils.getBeginDayOfToMorrow();
    if (widget.unCheckInputData != null) {
      hidedanger.defectEquipment.text = widget.equipmentName;
      hidedanger.defectEquipmentIds = widget.equipmentId;
      for (UNCheckInput asd in widget.unCheckInputData) {
        if (widget.unCheckInputData != null) {
          for (final UNCheckInput asd in widget.unCheckInputData) {
            UNCheckInput item = UNCheckInput.fromParams(
              name: asd.name,
              isSelected: asd.isSelected,
              value: asd.value,
              routePointItemId: asd.routePointItemId,
              itemId: asd.itemId,
              limitDate: asd.limitDate,
              dangerLevel: asd.dangerLevel,
              remark: asd.remark,
            );
            oldCheckInputData.add(item);
          }
        }
      }
    }
    getPerson(this.context);
  }

  Future<void> getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      theme = data.getString('theme') ?? 'blue';
      String realName = json.decode(data.getString("myInfo"))["realName"];
      hidedanger.defectResponsible.text = realName;
      hidedanger.defectDiscover.text = realName;
    }).then((data) {});
  }
}

