import 'dart:convert';
import 'dart:io';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';

import '../../model/CheckItem.dart';
import '../../model/CheckRecordDto.dart';
import '../../model/ExtClass.dart';
import '../../model/MovePointAttachment.dart';
import '../../model/PlanTaskInitConfig.dart';
import '../../services/CheckRecordServices.dart';
import '../../services/PlanTaskInitConfigServices.dart';
import '../../view/CheckExecute/ImageList.dart';
import '../../view/CheckExecute/TextView.dart';
import '../../view/CheckExecute/checkexec_inspection_list_detail.dart';
import '../../view/hidedanger_manage/hidden_danger_found.dart';

class CheckExecInspectionList extends StatefulWidget {
  // 计划ID
  int planId;

  // 巡检点ID
  int pointId;
  String checkMode;

  CheckExecInspectionList(this.pointId, [this.planId, this.checkMode]);

  @override
  State<StatefulWidget> createState() => _CheckExecInspectionList();
}

class _CheckExecInspectionList extends State<CheckExecInspectionList> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  // 页面配置信息
  PlanTaskInitConfig initConfig;

  // 当前点的附件
  List<File> imageList;

  // 点备注
  final TextEditingController _remarkController = TextEditingController();

  Map<String, TextEditingController> txtControllers = {};

  File img;

  // 正在保存
  bool issaving = false;

  int selectClass = -1;

  // 过滤后的检查项
  final List<CheckItem> _filtercheckItem = [];

  bool isAnimating = false;

  String theme = '';

  ExtClass classifySelected;

  // 确定要提交的分类
  Map<String, bool> commitClassifies = {};

  // 问题列表
  Map<num, bool> unCheckInputMap = {};

  @override
  void initState() {
    super.initState();
    // 根据点ID和计划ID获取配置初始化checkitems
    getInitConfig();
    initThemeConfig();
  }

  initThemeConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  void getInitConfig() async {
    // 调用接口获取配置
    await getInitPlanTaskConfig(widget.planId, widget.pointId).then((data) {
      if (null == data) {
        MsgBox.showMessageAndExitCurrentPage('数据加载失败！', true, context);
        return;
      }

      if (data.errorMsg != null && data.errorMsg.isNotEmpty) {
        MsgBox.showMessageAndExitCurrentPage(data.errorMsg, true, context);
        return;
      }

      setState(() {
        initConfig = data;
        if (data.extClass.isNotEmpty) {
          classifySelected = data.extClass[0];
          data.extClass.forEach((f) {
            commitClassifies[f.id.toString()] = false;
          });
        }
      });
      for (var item in initConfig.checkItem) {
        List<ItemPictureInfo> pics = [];
        for (final pic in json.decode(item.pictureJson)) {
          ItemPictureInfo p = ItemPictureInfo.fromJson(pic);
          pics.add(p);
        }
        item.pictureInfo = pics;
        item.uniqueKey = Uuid().v4();
        _checkItem.add(item);
        if (classifySelected != null) {
          if (item.classifyIds == null && classifySelected.id.toString() == 'null') {
            _filtercheckItem.add(item);
          } else if (item.classifyIds == classifySelected.id.toString()) {
            _filtercheckItem.add(item);
          }
        } else {
          _filtercheckItem.add(item);
        }

        // TextField 绑定初始化controller
        if (item.itemType == '文本' || item.itemType == '数字') {
          txtControllers[item.uniqueKey.toString()] = TextEditingController();
        }

        if (item.itemType == '选择') {
          List<RadioWidgetInfo> rds = [];
          for (var rd in jsonDecode(item.dataJson)) {
            rds.add(RadioWidgetInfo.fromJson(rd));
          }
          rds.forEach((rd) {
            if (rd.isChecked == '是') {
              ItemResultData itemResultData = ItemResultData.fromParams();
              itemResultData.uniqueKey = item.uniqueKey;
              itemResultData.value = rd.name;
              itemResultData.routePointItemId = item.routePointItemId;
              _itemResultDataMap[item.uniqueKey] = itemResultData;
            }
          });
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    if (null == initConfig) {
      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), size: 32),
          ),
        ),
      ));
    }

    return Scaffold(
      appBar: AppBar(
        title: widget.planId == null
            ? Text(
                null != initConfig.point ? initConfig.point.name ?? '' : '',
                style: const TextStyle(color: Colors.black, fontSize: 19),
              )
            : Text(
                null != initConfig.planTask ? initConfig.planTask.pointName ?? '' : '',
                style: const 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), size: 32),
          ),
        ),
        actions: <Widget>[
          IconButton(
            icon: Image(
              image: AssetImage('assets/images/icons/save_' + theme + '.png', package: ExternalAssetsPackageKey.BASE),
              width: 22,
            ),
            onPressed: () {
              if (!issaving) {
                saveData();
              }
            },
          )
        ],
      ),
      body: ModalProgressHUD(
        inAsyncCall: isAnimating,
        // demo of some additional parameters
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
        child: SingleChildScrollView(
          child: Container(
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                    padding: const EdgeInsets.only(left: 10, top: 10, bottom: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(
                              padding: const EdgeInsets.only(left: 10, top: 10),
                              width: 130,
                              height: 40,
                              child: const Text(
                                "点编号",
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                              ),
                            ),
                            widget.planId == null
                                ? Text(
                                    null != initConfig.point ? initConfig.point.pointNo ?? "" : "",
                                    style: const TextStyle(color: Colors.grey),
                                  )
                                : Text(
                                    null != initConfig.planTask ? initConfig.planTask.pointNo ?? "" : "",
                                    style: const TextStyle(color: Colors.grey),
                                  )
                          ],
                        ),
                        Row(
                          children: <Widget>[
                            Container(
                              padding: const EdgeInsets.only(left: 10, top: 10),
                              width: 130,
                              height: 40,
                              child: const Text(
                                '检查计划',
                                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                              ),
                            ),
                            Container(
                              width: MediaQuery.of(context).size.width - 150,
                              padding: const EdgeInsets.only(top: 10),
                              child: Text(
                                ((null == initConfig.planTask) ? '计划外' : initConfig.planTask.planName),
                                style: const TextStyle(
                                  fontWeight: FontWeight.w500,
                                  fontSize: 16,
                                  color: Colors.red,
                                ),
                              ),
                            )
                          ],
                        ),
                      ],
                    )),
                Container(
                  height: 10.0,
                  color: const Color.fromRGBO(242, 246, 249, 1),
                ),
                Container(
                  color: Colors.white,
                  padding: const EdgeInsets.only(left: 10, top: 10),
                  width: double.infinity,
                  height: 40,
                  child: const Text(
                    '检查项目',
                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
                  ),
                ),
                const Divider(
                  height: 1,
                ),
                Container(
                  height: 10.0,
                  color: const Color.fromRGBO(242, 246, 249, 1),
                ),
                Container(
                  child: Column(
                    children: initConfig.extClass.map((f) {
                      return GestureDetector(
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Expanded(
                                  flex: 8,
                                  child: Container(
                                    padding: const EdgeInsets.only(left: 10, right: 10, top: 8, bottom: 6),
                                    child: Text(f.name),
                                    alignment: Alignment.centerLeft,
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    child: Icon(Icons.check_circle,
                                        color: f.hasDone
                                            ? const Color.fromRGBO(0, 180, 22, 1)
                                            : const Color.fromRGBO(215, 219, 225, 1)),
                                  ),
                                  flex: 1,
                                ),
                                Expanded(
                                  child: Container(
                                    padding: const EdgeInsets.only(right: 20),
                                    child: Icon(
                                      Icons.chevron_right,
                                      size: 28,
                                      color: GetConfig.getColor(theme),
                                    ),
                                    alignment: Alignment.centerRight,
                                  ),
                                  flex: 1,
                                ),
                              ],
                            ),
                            const Divider()
                          ],
                        ),
                        onTap: () {
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return CheckExecInspectionListDetail(
                                initConfig, f, _itemResultDataMap, widget.pointId, widget.planId, widget.checkMode);
                          })).then((v) {
                            if (v != null) {
                              if (v.toString().startsWith('cancel')) {
                                List<String> ids = v.toString().substring(8).split("||");
                                for (final String id in ids) {
                                  commitClassifies[id] = false;
                                  _itemResultDataMap[id] = null;
                                  f.hasDone = commitClassifies[id];
                                }
                              } else if (v.toString().startsWith('back')) {
                                List<dynamic> returnData = v.toString().split('||');
                                var exts = json.decode(returnData[1]);
                                f.hasDone = exts['hasDone'];
                                if (returnData.length > 2) {
                                  List<dynamic> oldData = json.decode(v.toString().split('||')[2]);
                                  setState(() {
                                    for (final data in oldData) {
                                      List<String> _data = data.toString().split('//');
                                      for (final _mKey in _itemResultDataMap.keys) {
                                        if (_itemResultDataMap[_mKey].uniqueKey == _data[0]) {
                                          _itemResultDataMap[_mKey].value = _data[1];
                                          continue;
                                        }
                                      }
                                    }
                                  });
                                }
                              } else {
                                setState(() {
                                  for (final _mKey in v.keys) {
                                    _itemResultDataMap[_mKey] = v[_mKey];
                                    if (_itemResultDataMap[_mKey] == null ||
                                        _itemResultDataMap[_mKey].uniqueKey == null) {
                                      commitClassifies[_mKey] = false;
                                      f.hasDone = false;
                                    } else {
                                      commitClassifies[_mKey] = true;
                                      f.hasDone = true;
                                    }
                                  }
                                });
                              }
                            } else {
                              f.hasDone = false;
                            }
                          });
                        },
                      );
                    }).toList(),
                  ),
                ),
                Container(
                  height: 10.0,
                  color: const Color.fromRGBO(242, 246, 249, 1),
                ),
                Container(
                  width: MediaQuery.of(context).size.width - 10,
                  child: Padding(
                      padding: const EdgeInsets.only(left: 10.0, bottom: 20.0, top: 15),
                      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                        GestureDetector(
                          child: Row(
                            children: <Widget>[
                              const Expanded(
                                child: Text(
                                  "现场照片",
                                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
                                ),
                                flex: 9,
                              ),
                              Expanded(
                                child: Image.asset(
                                  "assets/images/icons/camera_" + theme + ".png",
                                  height: 20,
                                  package: ExternalAssetsPackageKey.BASE,
                                ),
                                flex: 1,
                              ),
                              Expanded(
                                child: Icon(
                                  Icons.keyboard_arrow_right,
                                  color: GetConfig.getColor(theme),
                                  size: 28,
                                ),
                                flex: 0,
                              ),
                            ],
                          ),
                          onTap: () {
                            Navigator.push(context, MaterialPageRoute(builder: (context) {
                              return ImageList(imageList);
                            })).then((v) {
                              if (v != null) {
                                setState(() {
                                  imageList = v;
                                });
                              }
                            });
                          },
                        )
                      ])),
                ),
                Container(
                  height: 10.0,
                  color: const Color.fromRGBO(242, 246, 249, 1),
                ),
                Container(
                  width: MediaQuery.of(context).size.width - 10,
                  child: GestureDetector(
                    child: Padding(
                        padding: const EdgeInsets.only(left: 10.0, bottom: 20.0, top: 15),
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                          Row(
                            children: <Widget>[
                              const Expanded(
                                flex: 9,
                                child: Text(
                                  "备注说明",
                                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Image.asset(
                                  'assets/images/icons/message.png',
                                  package: ExternalAssetsPackageKey.BASE,
                                  height: 20,
                                ),
                              ),
                              Expanded(
                                child: Icon(
                                  Icons.keyboard_arrow_right,
                                  color: GetConfig.getColor(theme),
                                  size: 28,
                                ),
                                flex: 0,
                              ),
                            ],
                          ),
                        ])),
                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return TextView(text: _remarkController.text.isEmpty ? '' : _remarkController.text);
                      })).then((v) {
                        if (v != 'back') {
                          setState(() {
                            _remarkController.text = v;
                          });
                        }
                      });
                    },
                  ),
                  color: Colors.white,
                ),
                Container(
                  height: 10.0,
                  color: const Color.fromRGBO(242, 246, 249, 1),
                )
              ],
            ),
          ),
        ),
      ),
      resizeToAvoidBottomPadding: false,
    );
  }

  //////////////////////////////////////////////////////////////////////////////////////
  // 开始加载价检查项
  final List<CheckItem> _checkItem = [];
  final Map<String, ItemResultData> _itemResultDataMap = {};

  saveData() {
    print('check 要提交数据完整性=====================================================');
    for (final item in _checkItem) {
      if (item.isMust == '是') {
        if (_itemResultDataMap[item.uniqueKey] == null) {
          HiddenDangerFound.popUpMsg('有未提交的数据项！');

          return;
        }
        if (_itemResultDataMap[item.uniqueKey] != null &&
            (_itemResultDataMap[item.uniqueKey].value == null || _itemResultDataMap[item.uniqueKey].value.isEmpty) &&
            (_itemResultDataMap[item.uniqueKey].text == null || _itemResultDataMap[item.uniqueKey].text.isEmpty)) {
          HiddenDangerFound.popUpMsg('有未提交的数据项！');
          return;
        }
      }
    }
    for (var item in _checkItem) {
      int picCount = item.pictureInfo.where((f) => f.isMust == "是").length;
      if (picCount > 0) {
        //mustPicCount = mustPicCount + picCount;
        if (_itemResultDataMap[item.uniqueKey] != null) {
          if (_itemResultDataMap[item.uniqueKey].img == null ||
              picCount > _itemResultDataMap[item.uniqueKey].img.length) {
            HiddenDangerFound.popUpMsg('有未上传的图片！');
            return;
          }
        }
      }
    }

    print('check result=====================================================');

    // 需要上传的分类数据
    List<String> classifyIds = [];
    commitClassifies.forEach((k, v) {
      if (v == true) {
        classifyIds.add(k);
      }
    });

    if (classifyIds.isEmpty && initConfig.extClass != null && initConfig.extClass.isNotEmpty) {
      setState(() {
        issaving = false;
        isAnimating = false;
        HiddenDangerFound.popUpMsg('没有数据可以提交！');
        return;
      });
    } else {
      //
      if (classifyIds.isEmpty && (initConfig.extClass == null || initConfig.extClass.isEmpty)) {
        // check data
        String error = checkData(null);
        if (error.isNotEmpty) {
          MsgBox.showMessageOnly(error, context);
          return;
        }
      }

      setState(() {
        issaving = true;
        isAnimating = true;
      });

      // 组装要保存的数据
      CheckRecordDto checkRecord = CheckRecordDto.fromJson({});
      // 要上传的文件
      List<Attachment> fileData = [];
      if (null != imageList && imageList.isNotEmpty) {
        imageList.forEach((f) {
          fileData.add(Attachment.fromParams(file: f));
        });
      }

      checkRecord.planTaskId = widget.planId;
      checkRecord.pointId = widget.pointId;
      checkRecord.remark = _remarkController.text;
      checkRecord.checkMode = widget.checkMode ?? 'OTHER';
      checkRecord.checkItems = [];

      _itemResultDataMap.forEach((k, v) {
        if (k != null && k != '') {
          CheckItemDto item = CheckItemDto.fromJson({});
          // 检查项ID
          num itemId; //= _checkItem.singleWhere((f)=>f.uniqueKey == v.uniqueKey).id;
          for (var i = 0; i < _checkItem.length; i++) {
            if (_checkItem[i].uniqueKey == k) {
              itemId = _checkItem[i].id;
              item.classifyIds = _checkItem[i].classifyIds;
              break;
            }
          }

          item.inputItemId = itemId;
          // 检查项的值，数字，文本：放具体输入的值，选择：放选项的名字
          item.inputValue = v.value != null ? v.value.trim() : "";
          // 备注
          item.remark = v.text;
          item.routePointItemId = v.routePointItemId;

          checkRecord.checkItems.add(item);
          // 组装图片信息
          if (null != v && null != v.img) {
            v.img.forEach((key, val) {
              Attachment attach = Attachment.fromParams(itemId: itemId, file: val, name: key);
              attach.classifyIds = v.classifyIds;
              fileData.add(attach);
            });
          }
        }
      });

      // 将没有内容的检查项也上传
      List<String> keys = _itemResultDataMap.keys.toList();
      for (int i = 0; i < _checkItem.length; i++) {
        bool dataExist = false;
        for (int j = 0; j < keys.length; j++) {
          if (_checkItem[i].uniqueKey == keys[j]) {
            dataExist = true;
            break;
          }
        }
        if (!dataExist) {
          classifyIds.forEach((id) {
            if (id == 'null' && _checkItem[i].classifyIds == null) {
              CheckItemDto item = CheckItemDto.fromJson({});
              item.inputItemId = _checkItem[i].id;
              item.classifyIds = _checkItem[i].classifyIds;
              item.routePointItemId = _checkItem[i].routePointItemId;
              checkRecord.checkItems.add(item);
            } else if (id == _checkItem[i].classifyIds) {
              CheckItemDto item = CheckItemDto.fromJson({});
              item.inputItemId = _checkItem[i].id;
              item.classifyIds = _checkItem[i].classifyIds;
              item.routePointItemId = _checkItem[i].routePointItemId;
              checkRecord.checkItems.add(item);
            }
          });
        }
      }

      showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, state) {
            return SimpleDialog(
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(top: 20),
                  padding: const EdgeInsets.only(left: 15, bottom: 15),
                  child: const Text(
                    '提交后不可修改，请确认检查结果准确无误？',
                    style: TextStyle(fontSize: 16),
                  ),
                  alignment: Alignment.centerLeft,
                ),
                const Divider(
                  height: 1,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                      child: Container(
                          child: FlatButton(
                              child: const Text(
                                "确定",
                                style: TextStyle(fontSize: 16, color: Colors.blue),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                                saveCheckRecordData(checkRecord, fileData);
                              })),
                    ),
                    Expanded(
                      child: Container(
                          child: FlatButton(
                              child: const Text(
                                "取消",
                                style: TextStyle(fontSize: 16),
                              ),
                              onPressed: () {
                                setState(() {
                                  issaving = false;
                                  isAnimating = false;
                                });

                                Navigator.pop(context);
                              })),
                    ),
                  ],
                )
              ],
            );
          });
        },
      );

//    }
    }
  }

  var unCheckInputList;

  void saveCheckRecordData(recordData, fileData) async {
    // 保存数据
    await saveCheckRecord(recordData).then((result) {
      setState(() {
        isAnimating = false;
      });
      if (result.isOk()) {
        int checkRecordId = int.tryParse(result.dataList['checkId'].toString());
        unCheckInputList = result.dataList['unCheckInputList'];
        // 如果返回的不是ID，那么认为是提示信息
        if (null == checkRecordId) {
          MsgBox.showMessageOnly(result.dataList.toString(), context);
          setState(() {
            issaving = false;
          });
        } else {}
      } else {
        MsgBox.showMessageOnly(result.message ?? '数据保存失败！', context);
        setState(() {
          issaving = false;
        });
      }
    });
  }

  checkData(ExtClass classifySelected) {
    List<CheckItem> needCheckItems = [];
    Map<String, ItemResultData> _needCheckItemResultDataMap = {};
    if (classifySelected == null) {
      needCheckItems = _checkItem;
    } else {
      if (classifySelected.id == null) {
        needCheckItems.addAll(_checkItem.where((f) => f.classifyIds == null).toList());
      } else {
        needCheckItems.addAll(_checkItem.where((f) => f.classifyIds == classifySelected.id.toString()).toList());
      }
    }

    needCheckItems.forEach((f) {
      if (f.itemType == "文本") {
      } else if (f.itemType == "选择") {
        radioCheck(f.uniqueKey, f);
      } else if (f.itemType == "数字") {
        numberCheck(f.uniqueKey, f);
      }

      // 检查照片是否上传
      f.pictureInfo.forEach((p) {
        // 照片没有传
        if (p.isMust == "是") {
          if (_itemResultDataMap[f.uniqueKey] == null) {
            _itemResultDataMap[f.uniqueKey] = ItemResultData.fromParams(uniqueKey: f.uniqueKey, value: "");
          }

          if (_itemResultDataMap[f.uniqueKey].img != null) {
            if (_itemResultDataMap[f.uniqueKey].img[p.name] == null) {
              // 必须项未拍照
              _itemResultDataMap[f.uniqueKey].hasError = true;
              if ((_itemResultDataMap[f.uniqueKey].errorInfo ?? "") != "") {
                _itemResultDataMap[f.uniqueKey].errorInfo += "\r\n" + p.name + "未上传照片";
              } else {
                _itemResultDataMap[f.uniqueKey].errorInfo = p.name + "未上传照片";
              }
            }
          } else {
            // 必须项未拍照
            _itemResultDataMap[f.uniqueKey].hasError = true;
            if ((_itemResultDataMap[f.uniqueKey].errorInfo ?? "") != "") {
              _itemResultDataMap[f.uniqueKey].errorInfo += "\r\n" + p.name + "未上传照片";
            } else {
              _itemResultDataMap[f.uniqueKey].errorInfo = p.name + "未上传照片";
            }
          }
        } else {
          // 无需检查
        }
      });

      _needCheckItemResultDataMap[f.uniqueKey] = _itemResultDataMap[f.uniqueKey];
    });

    // 打印检查项
    String error = "";
    /*_itemResultDataMap*/
    _needCheckItemResultDataMap.forEach((k, v) {
      if (null != v && null != v.hasError && v.hasError) {
        error = error + v.errorInfo + "\r\n";
        _needCheckItemResultDataMap[k].errorInfo = "";
      }
    });
    return error;
  }

  textCheck(String key, CheckItem checkItem) {
    if (_itemResultDataMap[key] == null) {
      _itemResultDataMap[key] = ItemResultData.fromParams(routePointItemId: checkItem.routePointItemId, value: '');
    }
  }

  numberCheck(String key, CheckItem checkItem) {
    num value = num.tryParse(
      _itemResultDataMap[key] == null || _itemResultDataMap[key].value == null ? "" : _itemResultDataMap[key].value,
    );
    if (checkItem.isMust == '是') {
      if (_itemResultDataMap[key] == null) {
        _itemResultDataMap[key] = ItemResultData.fromParams(routePointItemId: checkItem.routePointItemId, value: "");
      }

      _itemResultDataMap[key].hasError = false;
      if (_itemResultDataMap[key] == null || _itemResultDataMap[key].value.isEmpty) {
        _itemResultDataMap[key].hasError = true;
        _itemResultDataMap[key].errorInfo = '请输入：' + checkItem.name;
      } else {
        NumberCheckInfo checkInfo = NumberCheckInfo.fromJson(json.decode(checkItem.dataJson));
        if (checkInfo.CheckValidDown) {
          if (value == null) {
            _itemResultDataMap[key].hasError = true;
            _itemResultDataMap[key].errorInfo = checkItem.name + ':请输入数字';
          } else {
            if (value < checkInfo.ValidDown) {
              _itemResultDataMap[key].hasError = true;
              _itemResultDataMap[key].errorInfo = checkItem.name + ':最小值不能小于' + checkInfo.ValidDown.toString();
            }
          }
        }
        if (checkInfo.CheckValidUp) {
          if (value == null) {
            _itemResultDataMap[key].hasError = true;
            _itemResultDataMap[key].errorInfo = checkItem.name + ':请输入数字';
          } else {
            if (value > checkInfo.ValidUp) {
              _itemResultDataMap[key].hasError = true;
              _itemResultDataMap[key].errorInfo = checkItem.name + ':最大值不能大于' + checkInfo.ValidUp.toString();
            }
          }
        }
      }
    } else {
      if (_itemResultDataMap[key].value.isNotEmpty) {
        if (value == null) {
          _itemResultDataMap[key].hasError = true;
          _itemResultDataMap[key].errorInfo = checkItem.name + ':请输入数字';
          return;
        }
      } else {
        _itemResultDataMap[key].hasError = false;
        _itemResultDataMap[key].errorInfo = '';
      }
    }
  }

  radioCheck(String key, CheckItem checkItem) {
    if (checkItem.isMust == "是") {
      if (_itemResultDataMap[key] == null) {
        _itemResultDataMap[key] = ItemResultData.fromParams(routePointItemId: checkItem.routePointItemId, value: '');
      }
      if (_itemResultDataMap[key].value.isEmpty) {
        setState(() {
          _itemResultDataMap[key].hasError = true;
          _itemResultDataMap[key].errorInfo = '请输入：' + checkItem.name;
        });
      } else {
        setState(() {
          _itemResultDataMap[key].hasError = false;
          _itemResultDataMap[key].errorInfo = '';
        });
      }
    }
  }
}

class ItemResultData {
  num routePointItemId;
  num id;
  String value;
  Map<String, File> img = {};
  String text;
  String errorInfo;
  bool hasError = false;
  String uniqueKey;
  num classifyIds;
  bool hasDone = false;

  ItemResultData.fromParams(
      {this.id,
      this.value,
      this.img,
      this.errorInfo,
      this.hasError,
      this.routePointItemId,
      this.uniqueKey,
      this.classifyIds,
      this.text});

  @override
  String toString() {
    return '{"id": $id,"value":${value != null ? '${json.encode(value)}' : 'null'},'
        '"text":${text != null ? '${json.encode(text)}' : 'null'},'
        '"errorInfo":${errorInfo != null ? '${json.encode(errorInfo)}' : 'null'},"hasError":$hasError,'
        '"img":${img != null ? '${json.encode(img)}' : 'null'}}';
  }
}

class RadioWidgetInfo {
  int score;
  String name;
  String isChecked;
  String isOk;

  RadioWidgetInfo.fromJson(jsonRes) {
    score = jsonRes['score'];
    name = jsonRes['name'];
    isChecked = jsonRes['isChecked'];
    isOk = jsonRes['isOk'];
  }
}

class NumberCheckInfo {
  num OkScore;
  num NoScore;
  num ValidUp;
  num ValidDown;
  num OkUp;
  num OkDown;
  bool CheckValidUp;
  bool CheckValidDown;
  bool CheckOkUp;
  bool CheckOkDown;
  num Precision;

  NumberCheckInfo.fromJson(jsonRes) {
    OkScore = jsonRes['OkScore'];
    NoScore = jsonRes['NoScore'];
    ValidUp = jsonRes['ValidUp'];
    ValidDown = jsonRes['ValidDown'];
    OkUp = jsonRes['OkUp'];
    OkDown = jsonRes['OkDown'];
    CheckValidUp = jsonRes['CheckValidUp'];
    CheckValidDown = jsonRes['CheckValidDown'];
    CheckOkUp = jsonRes['CheckOkUp'];
    CheckOkDown = jsonRes['CheckOkDown'];
    Precision = jsonRes['Precision'];
  }
}

class UNCheckInput {
  num itemId;
  String name;
  num value;
  num routePointItemId;
  String limitDate = '';
  num dangerLevel;
  bool isSelected = false;
  String remark = '';
  String inputValue = '';

  TextEditingController limitedDate = TextEditingController();

  UNCheckInput.fromJson(jsonRes) {
    itemId = jsonRes['itemId'];
    name = jsonRes['name'];
    value = jsonRes['value'];
    routePointItemId = jsonRes['routePointItemId'];
    isSelected = jsonRes['isSelected'] ?? false;
    dangerLevel = jsonRes['dangerLevel'];
    limitDate = jsonRes['limitDate'];
    remark = jsonRes['remark'];
    inputValue = jsonRes['inputValue'];
  }

  UNCheckInput.fromParams(
      {this.name,
      this.itemId,
      this.value,
      this.routePointItemId,
      this.isSelected,
      this.dangerLevel,
      this.limitDate,
      this.remark});
}
