import 'dart:convert';
import 'dart:io';
import 'package:jcs_airport/view/defect/hidden_defect_found.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_api/logutils.dart';
import 'package:amos_flutter_ui/media/image_view.dart';

import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:base/utils/request.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:uuid/uuid.dart';

import '../../model/CheckItem.dart';
import '../../model/CheckRecordDto.dart';
import '../../model/ExtClass.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/hidedanger_manage/hidden_Inspection_danger_add.dart';
import 'checkexec_inspection_list.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

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

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

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

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

  // 页面配置信息
  PlanTaskInitConfig initConfig;

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

  int select = 0;

  // 点备注
  final TextEditingController _remarkController = TextEditingController();
  Map<String, TextEditingController> txtControllers = {};
  File img;

  // 正在保存
  bool isSaving = false;
  List<bool> unCheckInputMap = [];
  int selectClass = -1;

  //项目检查点图片
  List<updataModel> updatelist = [];

  // 过滤后的检查项
  final Map<String, List<CheckItem>> _filtercheckItem = {};
  bool isAnimating = false;
  String theme = 'blue';
  ExtClass classifySelected;



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

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

  Future<void> getInitConfig() async {
    // 调用接口获取配置
    await getInitPlanTaskConfig(widget.planId, widget.pointId).then((data) {
      LogUtil.d(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 (final item in initConfig.checkItem) {
        List<ItemPictureInfo> pics = [];
        if (item.pictureJson != null) {
          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 &&
            classifySelected.id.toString() == item.classifyIds.toString()) {
          if (_filtercheckItem.containsKey(item.riskDesc)) {
            _filtercheckItem[item.riskDesc].add(item);
          } else {
            if (item.riskDesc.isEmpty) {
              item.riskDesc = '其他';
            }
            if (_filtercheckItem[item.riskDesc] == null) {
              _filtercheckItem[item.riskDesc] = [];
            }
            _filtercheckItem[item.riskDesc].add(item);
          }
        } else if (classifySelected == null) {
          if (item.riskDesc.isEmpty) {
            item.riskDesc = '其他';
          }
          if (_filtercheckItem[item.riskDesc] == null) {
            _filtercheckItem[item.riskDesc] = [];
          }
          _filtercheckItem[item.riskDesc].add(item);
        }
        if (item.itemType == '文本' || item.itemType == '数字') {
          txtControllers[item.uniqueKey.toString()] =
              TextEditingController(text: item.defaultValue);
          ItemResultData itemResultData = ItemResultData.fromParams();
          itemResultData.uniqueKey = item.uniqueKey;
          itemResultData.value = item.defaultValue;
          _itemResultDataMap[item.uniqueKey] = itemResultData;
        }
        if (item.itemType == '选择') {
          List<RadioWidgetInfo> rds = [];
          for (final 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;
              _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(
          '巡检点名称',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ));
    }

    return Scaffold(
      appBar: AppBar(
        title: widget.planId == null
            ? Text(
                null != initConfig.point ? initConfig.point.name ?? '' : '',
              )
            : Text(
                null != initConfig.planTask
                    ? initConfig.planTask.pointName ?? ''
                    : '',
              ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        actions: <Widget>[
          IconButton(
            icon: const Icon(
              Icons.save,
              size: 22,
            ),
            color: Colors.white,
            onPressed: () {
              print(initConfig);
              if (initConfig.extClass == null || initConfig.extClass.isEmpty) {
                FlutterToast.toastBottom('不能提交检查项为空的数据');
                return;
              }
              if (!isSaving) {
                saveData();
              }
            },
          )
        ],
      ),
      body: ModalProgressHUD(
        inAsyncCall: isAnimating,
        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,
                                      fontSize: 16,
                                    ),
                                  )
                                : Text(
                                    null != initConfig.planTask
                                        ? initConfig.planTask.pointNo ?? ''
                                        : '',
                                    style: const TextStyle(
                                      color: Colors.grey,
                                      fontSize: 16,
                                    ),
                                  )
                          ],
                        ),
                        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),
                              ),
                            ),
                            Text(
                              (null == initConfig.planTask)
                                  ? '计划外'
                                  : initConfig.planTask.planName,
                              style: const TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 16
                              ),
                            ),
                          ],
                        ),
                      ],
                    )),
                Container(
                  height: 10.0,
                  color: const Color.fromRGBO(242, 246, 249, 1),
                ),
                //TOOL listView
                ListView.builder(
                  itemCount: initConfig.extClass.length,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index) {
                    return getExtClass(context, initConfig.extClass[index]);
                  },
                ),
                Container(
                  color: Colors.white,
                  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 Text(
                                    '现场照片',
                                    style: TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.w500),
                                  ),
                                  Expanded(
                                      child: Container(
                                          margin:
                                              const EdgeInsets.only(right: 20),
                                          alignment: Alignment.centerRight,
                                          child: Icon(
                                            Icons.camera_alt,
                                            color:
                                                Theme.of(context).primaryColor,
                                          ))),
                                ],
                              ),
                              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(
                  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 Text(
                                    '备注说明',
                                    style: TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.w500),
                                  ),
                                  Expanded(
                                      child: Container(
                                          margin:
                                              const EdgeInsets.only(right: 20),
                                          alignment: Alignment.centerRight,
                                          child: Icon(
                                            Icons.message_outlined,
                                            color:
                                                Theme.of(context).primaryColor,
                                          ))),
                                ],
                              ),
                            ])),
                    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),
                ),
                initConfig.extClass != null && initConfig.extClass.isNotEmpty
                    ? commitClassifies[classifySelected.id.toString()]
                        ? Container(
                            margin: const EdgeInsets.only(
                                left: 15.0, right: 15.0, top: 5, bottom: 5),
                            color: Theme.of(context).primaryColor,
                            width: double.infinity,
                            height: 40,
                            child: MaterialButton(
                              onPressed: () {
                                setState(() {
                                  commitClassifies[
                                      classifySelected.id.toString()] = false;
                                });
                              },
                              child: const Text(
                                '取消',
                                style: TextStyle(
                                    fontSize: 18, color: Colors.white),
                              ),
                            ),
                          )
                        : Container(
                            margin: const EdgeInsets.only(
                                left: 15.0, right: 15.0, top: 5, bottom: 5),
                            width: double.infinity,
                            height: 40,
                            child: MaterialButton(
                              color: Theme.of(context).primaryColor,
                              onPressed: () {
                                FocusScope.of(context)
                                    .requestFocus(FocusNode());
                                /* if (initConfig.checkItem.isEmpty) {
                                  FlutterToast.toastBottom('检查项为空');
                                  return;
                                }*/
                                String error = checkData(classifySelected);
                                if (error.isEmpty) {
                                  setState(() {
                                    commitClassifies[
                                        classifySelected.id.toString()] = true;
                                  });
                                } else {
                                  MsgBox.showMessageOnly(error, context);
                                }
                              },
                              child: const Text(
                                '保存',
                                style: TextStyle(
                                    fontSize: 18, color: Colors.white),
                              ),
                            ),
                          )
                    : Container()
              ],
            ),
          ),
        ),
      ),
      resizeToAvoidBottomPadding: false,
    );
  }

  Widget getExtClass(BuildContext context, ExtClass extClass) {
    Map<String, List<CheckItem>> filtercheck = {};
    for (final item in initConfig.checkItem) {
      if (extClass != null &&
          extClass.id.toString() == item.classifyIds.toString()) {
        if (filtercheck.containsKey(item.riskDesc)) {
          filtercheck[item.riskDesc].add(item);
        } else {
          if (item.riskDesc.isEmpty) {
            item.riskDesc = '其他';
          }

          if (filtercheck[item.riskDesc] == null) {
            filtercheck[item.riskDesc] = [];
          }
          filtercheck[item.riskDesc].add(item);
        }
      } else if (extClass == null) {
        if (item.riskDesc.isEmpty) {
          item.riskDesc = '其他';
        }
        if (filtercheck[item.riskDesc] == null) {
          filtercheck[item.riskDesc] = [];
        }

        filtercheck[item.riskDesc].add(item);
      }
    }
    return Column(children: <Widget>[
      Padding(
        padding: const EdgeInsets.only(left: 10, top: 10, bottom: 10),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                extClass == null ? '' : extClass.name,
                style:
                    const TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
      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(
        color: Colors.white,
        child: Column(
          children: filtercheck.keys.map((t) {
            return Column(
              children: <Widget>[
                (filtercheck.keys.length > 1 && t.isNotEmpty) ||
                        (filtercheck.keys.isEmpty && t.isNotEmpty && t != '其他')
                    ? Container(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Image.asset(
                                  'assets/images/risk_flag_' + theme + '.png',
                                  package: ExternalAssetsPackageKey.BASE,
                                  width: 15,
                                ),
                                Container(
                                  width: MediaQuery.of(context).size.width - 45,
                                  padding: const EdgeInsets.only(left: 10),
                                  child: Text(
                                    t,
                                    style: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.w600,
                                        fontFamily: 'Courier'),
                                  ),
                                )
                              ],
                            ),
                            const Divider()
                          ],
                        ),
                        margin: const EdgeInsets.only(
                            top: 10, bottom: 10, left: 10),
                      )
                    : Container(),
                Column(
                    children: filtercheck[t].map((itemData) {
                  if (itemData.itemType == '文本') {
                    return Container(
                      child: getTextFiled(itemData),
                    );
                  } else if (itemData.itemType == '数字') {
                    return Container(
                      child: getNumberFiled(itemData),
                    );
                  } else if (itemData.itemType == '选择') {
                    return Container(
                      child: getRadioBoxField(itemData),
                    );
                  }
                }).toList())
              ],
            );
          }).toList(),
        ),
      ),
    ]);
  }

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

  Widget getTextFiled(CheckItem _checkItem) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          GestureDetector(
            child: Container(
              child: Row(
                children: <Widget>[
                  _checkItem.isMust == '是'
                      ? const Text(
                          '*',
                          style: TextStyle(color: Colors.red),
                        )
                      : const Text(''),
                  Container(
                    child: Text(
                      _checkItem.name,
                      overflow: TextOverflow.ellipsis,
                    ),
                    width: MediaQuery.of(context).size.width - 60,
                  ),
                  Expanded(
                    child: Container(
                      color: Colors.white,
                      padding: const EdgeInsets.only(left: 10, right: 20),
                      child: _checkItem.basisJson == null
                          ? Container()
                          : Container(
                              alignment: Alignment.centerRight,
                              child: const Icon(
                                Icons.info_outline,
                                size: 16,
                                color: Colors.grey,
                              )),
                    ),
                  ),
                ],
              ),
              padding: const EdgeInsets.only(left: 10, top: 3),
            ),
            onTap: () {
              _checkItem.basisJson == null
                  ? null
                  : MsgBox.showMessageBase(_checkItem.basisJson, context);
            },
          ),
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.only(bottom: 10, left: 10, right: 20),
            child: TextField(
              controller: txtControllers[_checkItem.uniqueKey.toString()],
              onChanged: (value) {
                setState(() {
                  if (_itemResultDataMap[_checkItem.uniqueKey] == null) {
                    _itemResultDataMap[_checkItem.uniqueKey] =
                        ItemResultData.fromParams(
                            uniqueKey: _checkItem.uniqueKey, value: '');
                  }
                  _itemResultDataMap[_checkItem.uniqueKey].value = value;
                });
              },
              onEditingComplete: () {
                txtControllers[_checkItem.uniqueKey.toString()].text =
                    _itemResultDataMap[_checkItem.uniqueKey].value;
              },
            ),
          ),
          const Divider(
            height: 1,
          ),
          Container(
            child: Column(
                children: _checkItem.pictureInfo.map((f) {
              return Column(
                children: <Widget>[
                  Container(
                    child: GestureDetector(
                      child: Row(
                        children: <Widget>[
                          f.isMust == '是'
                              ? const Text(
                                  '*',
                                  style: TextStyle(color: Colors.red),
                                )
                              : const Text(''),
                          Container(
                            child: Text(
                              f.name,
                              overflow: TextOverflow.ellipsis,
                            ),
                            width: MediaQuery.of(context).size.width - 60,
                          ),
                          Expanded(
                              child: Container(
                            padding:
                                const EdgeInsets.only(bottom: 10, right: 20),
                            width: 40,
                            child: Icon(
                              Icons.camera_alt,
                              color: Theme.of(context).primaryColor,
                            ),
                            alignment: Alignment.centerRight,
                          )),
                        ],
                      ),
                      onTap: () {
                        setState(() {
                          ImagePicker.pickImage(source: ImageSource.camera)
                              .then((c) {
                            if (c != null) {
                              uploadImage([c]).then((value) {
                                updataModel bean = updataModel.fromParams();
                                bean.imageUrl = value[0];
                                bean.classifyIds = _checkItem.classifyIds;
                                bean.inputItemId = _checkItem.id;
                                int e = updatelist.length;
                                for (int i = 0; i < updatelist.length; i++) {
                                  updataModel bea = updatelist[i];
                                  if (bea.inputItemId == bean.inputItemId &&
                                      bean.classifyIds == bea.classifyIds) {
                                    e = i;
                                  }
                                }
                                if (e < updatelist.length) {
                                  updatelist.removeAt(e);
                                }
                                updatelist.add(bean);
                              });
                            }
                            setState(() {
                              if (c != null) {
                                if (_itemResultDataMap[_checkItem.uniqueKey] ==
                                    null) {
                                  _itemResultDataMap[_checkItem.uniqueKey] =
                                      ItemResultData.fromParams(
                                          uniqueKey: _checkItem.uniqueKey,
                                          value: "");
                                }
                                Map<String, File> m = {};
                                m[f.name] = c;
                                if (_itemResultDataMap[_checkItem.uniqueKey]
                                        .img ==
                                    null) {
                                  _itemResultDataMap[_checkItem.uniqueKey].img =
                                      {};
                                }
                                _itemResultDataMap[_checkItem.uniqueKey]
                                    .img
                                    .addAll(m);
                              }
                            });
                          });
                        });
                      },
                    ),
                    padding: const EdgeInsets.only(left: 10, top: 10),
                  ),
                  const Divider(
                    height: 1,
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: GestureDetector(
                      child: Container(
                          padding: const EdgeInsets.only(left: 10, right: 10),
                          child: _itemResultDataMap[_checkItem.uniqueKey] ==
                                      null ||
                                  _itemResultDataMap[_checkItem.uniqueKey]
                                          .img ==
                                      null ||
                                  _itemResultDataMap[_checkItem.uniqueKey]
                                          .img[f.name] ==
                                      null
                              ? Container()
                              : CircleAvatar(
                                  radius: 26,
                                  backgroundColor: Colors.black12,
                                  child: Image.file(
                                    _itemResultDataMap[_checkItem.uniqueKey]
                                        .img[f.name],
                                    height: 40,
                                  ),
                                )),
                      onTap: () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) {
                          return ImageView(Image.file(
                            _itemResultDataMap[_checkItem.uniqueKey]
                                .img[f.name],
                          ));
                        }));
                      },
                    ),
                    padding: const EdgeInsets.only(left: 10, top: 10),
                  ),
                ],
              );
            }).toList()),
          ),
          Container(
            height: 10,
            color: const Color.fromRGBO(242, 246, 249, 1),
          )
        ],
      ),
    );
  }

  Widget getNumberFiled(CheckItem _checkItem) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        GestureDetector(
          child: Container(
            child: Row(
              children: <Widget>[
                _checkItem.isMust == '是'
                    ? const Text(
                        '*',
                        style: TextStyle(color: Colors.red),
                      )
                    : const Text(''),
                Container(
                  child: Text(
                    _checkItem.name,
                    overflow: TextOverflow.ellipsis,
                  ),
                  width: MediaQuery.of(context).size.width - 60,
                ),
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.only(left: 10, right: 20),
                    alignment: Alignment.centerRight,
                    child: _checkItem.basisJson == null
                        ? null
                        : Container(
                            alignment: Alignment.centerRight,
                            child: const Icon(
                              Icons.info_outline,
                              size: 16,
                              color: Colors.grey,
                            )),
                  ),
                ),
              ],
            ),
            padding: const EdgeInsets.only(left: 10, top: 3),
          ),
          onTap: () {
            _checkItem.basisJson == null
                ? null
                : MsgBox.showMessageBase(_checkItem.basisJson, context);
          },
        ),
        Container(
          padding: const EdgeInsets.only(bottom: 10, left: 10, right: 20),
          alignment: Alignment.centerLeft,
          // width: 280,
          child: TextField(
            controller: txtControllers[_checkItem.uniqueKey.toString()],
            onChanged: (value) {
              setState(() {
                if (_itemResultDataMap[_checkItem.uniqueKey] == null) {
                  _itemResultDataMap[_checkItem.uniqueKey] =
                      ItemResultData.fromParams(
                          uniqueKey: _checkItem.uniqueKey, value: "");
                }
                _itemResultDataMap[_checkItem.uniqueKey].value = value;
              });
            },
            onEditingComplete: () {
              setState(() {
                txtControllers[_checkItem.uniqueKey.toString()].text =
                    _itemResultDataMap[_checkItem.uniqueKey].value;
              });
            },
          ),
        ),
        const Divider(
          height: 1,
        ),
        Container(
          child: Column(
              children: _checkItem.pictureInfo.map((f) {
            return Column(
              children: <Widget>[
                GestureDetector(
                  child: Container(
                    child: Row(
                      children: <Widget>[
                        f.isMust == '是'
                            ? const Text(
                                '*',
                                style: TextStyle(color: Colors.red),
                              )
                            : const Text(''),
                        Container(
                          child: Text(
                            f.name,
                            overflow: TextOverflow.ellipsis,
                          ),
                          width: MediaQuery.of(context).size.width - 60,
                        ),
                        Expanded(
                            child: Container(
                          padding: const EdgeInsets.only(bottom: 10, right: 20),
                          // width: 40,
                          child: Icon(
                            Icons.camera_alt,
                            color: Theme.of(context).primaryColor,
                          ),
                          alignment: Alignment.centerRight,
                        )),
                      ],
                    ),
                    padding: const EdgeInsets.only(left: 10, top: 10),
                  ),
                  onTap: () {
                    setState(() {
                      ImagePicker.pickImage(source: ImageSource.camera)
                          .then((c) {
                        if (c != null) {
                          uploadImage([c]).then((value) {
                            updataModel bean = updataModel.fromParams();
                            bean.imageUrl = value[0];
                            bean.classifyIds = _checkItem.classifyIds;
                            bean.inputItemId = _checkItem.id;
                            int e = updatelist.length;
                            for (int i = 0; i < updatelist.length; i++) {
                              updataModel bea = updatelist[i];
                              if (bea.inputItemId == bean.inputItemId &&
                                  bean.classifyIds == bea.classifyIds) {
                                e = i;
                              }
                            }
                            if (e < updatelist.length) {
                              updatelist.removeAt(e);
                            }
                            updatelist.add(bean);
                          });
                        }
                        setState(() {
                          if (c != null) {
                            if (_itemResultDataMap[_checkItem.uniqueKey] ==
                                null) {
                              _itemResultDataMap[_checkItem.uniqueKey] =
                                  ItemResultData.fromParams(
                                      uniqueKey: _checkItem.uniqueKey,
                                      value: "");
                            }
                            Map<String, File> m = {};
                            m[f.name] = c;
                            if (_itemResultDataMap[_checkItem.uniqueKey].img ==
                                null) {
                              _itemResultDataMap[_checkItem.uniqueKey].img = {};
                            }
                            _itemResultDataMap[_checkItem.uniqueKey]
                                .img
                                .addAll(m);
                          }
                        });
                      });
                    });
                  },
                ),
                const Divider(
                  height: 1,
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  child: GestureDetector(
                    child: Container(
                        padding: const EdgeInsets.only(left: 10, right: 10),
                        child: _itemResultDataMap[_checkItem.uniqueKey] ==
                                    null ||
                                _itemResultDataMap[_checkItem.uniqueKey].img ==
                                    null ||
                                _itemResultDataMap[_checkItem.uniqueKey]
                                        .img[f.name] ==
                                    null
                            ? Container()
                            : CircleAvatar(
                                radius: 26,
                                backgroundColor: Colors.black12,
                                child: Image.file(
                                  _itemResultDataMap[_checkItem.uniqueKey]
                                      .img[f.name],
                                  height: 40,
                                ),
                              )),
                    onTap: () {
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                        return ImageView(Image.file(
                          _itemResultDataMap[_checkItem.uniqueKey].img[f.name],
                        ));
                      }));
                    },
                  ),
                  padding: const EdgeInsets.only(left: 10, top: 10),
                ),
              ],
            );
          }).toList()),
        ),
        Container(
          height: 10,
          color: const Color.fromRGBO(242, 246, 249, 1),
        )
      ],
    );
  }

  Widget getRadioBoxField(CheckItem _checkItem) {
    List<RadioWidgetInfo> rds = [];
    for (final rd in jsonDecode(_checkItem.dataJson)) {
      rds.add(RadioWidgetInfo.fromJson(rd));
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        GestureDetector(
          child: Container(
            child: Row(
              children: <Widget>[
                _checkItem.isMust == '是'
                    ? const Text(
                        '*',
                        style: TextStyle(color: Colors.red),
                      )
                    : const Text(''),
                Container(
                  width: MediaQuery.of(context).size.width - 60,
                  child: Text(
                    _checkItem.name,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.only(left: 10, right: 20),
                    alignment: Alignment.topRight,
                    child: _checkItem.basisJson == null
                        ? null
                        : Container(
                            alignment: Alignment.centerRight,
                            child: const Icon(
                              Icons.info_outline,
                              size: 16,
                              color: Colors.grey,
                            )),
                  ),
                ),
              ],
            ),
            padding: const EdgeInsets.only(left: 10, top: 10),
          ),
          onTap: () {
            _checkItem.basisJson == null
                ? null
                : MsgBox.showMessageBase(_checkItem.basisJson, context);
          },
        ),
        Container(
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: Column(
              children: rds.map((f) {
            return Row(
              children: <Widget>[
                Radio(
                    activeColor: Theme.of(context).primaryColor,
                    value: f.name,
                    groupValue: _itemResultDataMap[_checkItem.uniqueKey] ==
                                null ||
                            _itemResultDataMap[_checkItem.uniqueKey].value ==
                                null
                        ? ''
                        : _itemResultDataMap[_checkItem.uniqueKey].value,
                    onChanged: (String val) {
                      setState(() {
                        if (_itemResultDataMap[_checkItem.uniqueKey] == null) {
                          _itemResultDataMap[_checkItem.uniqueKey] =
                              ItemResultData.fromParams(
                                  uniqueKey: _checkItem.uniqueKey, value: "");
                        }
                        _itemResultDataMap[_checkItem.uniqueKey].value = val;
                      });
                    }),
                Text(f.name ?? ''),
              ],
            );
          }).toList()),
        ),
        const Divider(
          height: 1,
        ),
        Container(
          child: Column(
              children: _checkItem.pictureInfo.map((f) {
            return Column(
              children: <Widget>[
                GestureDetector(
                  child: Container(
                    child: Row(
                      children: <Widget>[
                        f.isMust == '是'
                            ? const Text(
                                '*',
                                style: TextStyle(color: Colors.red),
                              )
                            : const Text(''),
                        Container(
                          child: Text(
                            f.name,
                            overflow: TextOverflow.ellipsis,
                          ),
                          width: MediaQuery.of(context).size.width - 60,
                        ),
                        Expanded(
                            child: Container(
                          padding: const EdgeInsets.only(bottom: 10, right: 20),
                          width: 40,
                          child: Icon(
                            Icons.camera_alt,
                            color: Theme.of(context).primaryColor,
                          ),
                          alignment: Alignment.centerRight,
                        )),
                      ],
                    ),
                    padding: const EdgeInsets.only(left: 10, top: 10),
                  ),
                  onTap: () {
                    setState(() {
                      ImagePicker.pickImage(source: ImageSource.camera)
                          .then((c) {
                        if (c != null) {
                          uploadImage([c]).then((value) {
                            updataModel bean = updataModel.fromParams();
                            bean.imageUrl = value[0];
                            bean.classifyIds = _checkItem.classifyIds;
                            bean.inputItemId = _checkItem.id;
                            int e = updatelist.length;
                            for (int i = 0; i < updatelist.length; i++) {
                              updataModel bea = updatelist[i];
                              if (bea.inputItemId == bean.inputItemId &&
                                  bean.classifyIds == bea.classifyIds) {
                                e = i;
                              }
                            }
                            if (e < updatelist.length) {
                              updatelist.removeAt(e);
                            }
                            updatelist.add(bean);
                          });
                        }
                        setState(() {
                          if (c != null) {
                            if (_itemResultDataMap[_checkItem.uniqueKey] ==
                                null) {
                              _itemResultDataMap[_checkItem.uniqueKey] =
                                  ItemResultData.fromParams(
                                      uniqueKey: _checkItem.uniqueKey,
                                      value: '');
                            }
                            Map<String, File> m = {};
                            m[f.name] = c;
                            if (_itemResultDataMap[_checkItem.uniqueKey].img ==
                                null) {
                              _itemResultDataMap[_checkItem.uniqueKey].img = {};
                            }
                            _itemResultDataMap[_checkItem.uniqueKey]
                                .img
                                .addAll(m);
                          }
                        });
                      });
                    });
                  },
                ),
                const Divider(
                  height: 1,
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  child: GestureDetector(
                    child: Container(
                        padding: const EdgeInsets.only(
                            left: 10, right: 10, bottom: 5),
                        child: _itemResultDataMap[_checkItem.uniqueKey] ==
                                    null ||
                                _itemResultDataMap[_checkItem.uniqueKey].img ==
                                    null ||
                                _itemResultDataMap[_checkItem.uniqueKey]
                                        .img[f.name] ==
                                    null
                            ? Container()
                            : CircleAvatar(
                                radius: 26,
                                backgroundColor: Colors.black12,
                                child: Image.file(
                                  _itemResultDataMap[_checkItem.uniqueKey]
                                      .img[f.name],
                                  height: 40,
                                ),
                              )),
                    onTap: () {
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                        return ImageView(Image.file(
                          _itemResultDataMap[_checkItem.uniqueKey].img[f.name],
                        ));
                      }));
                    },
                  ),
                  padding: const EdgeInsets.only(left: 10, top: 10),
                ),
              ],
            );
          }).toList()),
        ),
        Container(
          height: 10,
          color: const Color.fromRGBO(242, 246, 249, 1),
        )
      ],
    );
  }

  Future<void> saveData() async {
    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;
        MsgBox.showMessageOnly('没有数据可以提交！', context);
        return;
      });
    } else {
      if (classifyIds.isEmpty &&
          (initConfig.extClass == null || initConfig.extClass.isEmpty)) {
        String error = checkData(null);
        if (error.isNotEmpty) {
          MsgBox.showMessageOnly(error, context);
          return;
        }
      }
      setState(() {
        isSaving = true;
        isAnimating = true;
      });
      // 组装要保存的数据
      CheckRecordDto checkRecord = CheckRecordDto.fromJson({});
      if (imageList != null && imageList.isNotEmpty) {
        List<File> image = [];
        imageList.forEach((f) {
          image.add(f);
        });
        await uploadImage(image).then((value) {
          checkRecord.checkRecordImg = json.encode(value);
          checkRecords(checkRecord);
        });
      } else {
        checkRecords(checkRecord);
      }
    }
  }

  Future<void> checkRecords(CheckRecordDto checkRecords) async {
    CheckRecordDto checkRecord = checkRecords;
    checkRecord.planTaskId = widget.planId;
    checkRecord.pointId = widget.pointId;
    checkRecord.remark = _remarkController.text;
    checkRecord.checkMode = widget.checkMode ?? 'OTHER';
    checkRecord.checkItems = [];
    checkRecord.checkTime =
        '\"' + DateTime.now().toString().substring(0, 19) + '\"';
    _itemResultDataMap.forEach((k, v) {
      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;
      // 检查项的值，数字，文本：放具体输入的值，选择：放选项的名字
      if(v.value != null){
        item.inputValue = v.value.trim();
      }else {
        item.inputValue = v.value;
      }
      // 备注
      item.remark = v.text;
      item.routePointItemId = v.routePointItemId;
      item.checkInputImg = '';
      checkRecord.checkItems.add(item);
    });
    for (int i = 0; i < updatelist.length; i++) {
      updataModel bean = updatelist[i];
      checkRecord.checkItems.forEach((element) {
        if (bean.classifyIds == element.classifyIds &&
            bean.inputItemId == element.inputItemId) {
          element.checkInputImg = (element.checkInputImg.isEmpty
                  ? ''
                  : (element.checkInputImg + '&')) +
              bean.imageUrl.replaceFirst(',', '');
        }
      });
    }
    checkRecord.checkItems.forEach((element) {
      if (element.checkInputImg.isNotEmpty) {
        List<String> sss = element.checkInputImg.split('&');
        element.checkInputImg = json.encode(sss);
      } else {
        element.checkInputImg = null;
      }
    });
    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) {
        CheckItemDto item = CheckItemDto.fromJson({});
        item.inputItemId = _checkItem[i].id;
        item.classifyIds = _checkItem[i].classifyIds;
        item.routePointItemId = _checkItem[i].routePointItemId;
        checkRecord.checkItems.add(item);
      }
    }

    saveCheckRecordData(checkRecord);
  }

  Future<List> uploadImage(images) async {
    bool uploadSuccess = true;
    List imageUrls = [];
    try {
      for (int i = 0; i < images.length; i++) {
        File file = images[i];
        File result = await FlutterImageCompress.compressAndGetFile(
          file.absolute.path,
          file.absolute.path +
              '/' +
              file.path.substring(file.path.lastIndexOf('/')),
          minWidth: 1024,
          minHeight: 768,
          quality: 94,
        );

        String path = file.path;
        var name = path.substring(path.lastIndexOf('/') + 1, path.length);
        var image = await MultipartFile.fromFile(
          path,
          filename: name,
        );
        FormData formData = FormData.fromMap({'files': image});
        var response = await HttpRequest.uploadImage(data: formData);
        if (response['status'] == 200) {
          String url = response['result']['url'].toString().replaceAll(',', '');
          imageUrls.add(url);
        } else {
          uploadSuccess = false;
          break;
        }
      }
    } on DioError {
      return null;
    }

    return imageUrls;
  }

  var unCheckInputList;

  checkPermission(String permission, String permissionList) {
    if (permissionList == null || permissionList.isEmpty) return false;
    bool hasPermission = false;
    List permissions = permissionList.split(",");
    if (permissions.length <= 0) {
      hasPermission = false;
    } else {
      permissions.forEach((f) {
        print(f);
        if (f == permission) {
          hasPermission = true;
        }
      });
    }

    return hasPermission;
  }

  Future<void> saveCheckRecordData(CheckRecordDto recordData) async {
    // 保存数据
    await saveCheckRecord(recordData).then((result) {
      setState(() {
        isAnimating = false;
      });
      if (result.isOk()) {
        int checkRecordId = int.tryParse(result.dataList['checkId'].toString());
        unCheckInputList = result.dataList['unCheckInputList'];
        if (null == checkRecordId) {
          MsgBox.showMessageOnly(result.dataList.toString(), context);
          setState(() {
            isSaving = false;
          });
        } else {
          var unCheckInputList = result.dataList['unCheckInputList'];
          if (unCheckInputList != null) {
            List<UNCheckInput> dataList = [];
            for (final unCheckInput in unCheckInputList) {
              UNCheckInput _uNCheckInput = UNCheckInput.fromJson(unCheckInput);
              dataList.add(_uNCheckInput);
              unCheckInputMap.add(false);
            }
            if (dataList.isNotEmpty) {
              SharedPreferences.getInstance().then((sp) {
                String str = sp.get('permissionList');
                if (checkPermission('/hiddenAdd', str) &&
                    checkPermission('/latentDangerSave', str)) {
                  resultChooseDialog(dataList, checkRecordId);
                } else if (checkPermission('/hiddenAdd', str)) {
                  resultTaskDefectDialog(dataList, checkRecordId);
                } else if (checkPermission('/latentDangerSave', str)) {
                  resultTaskDialog(dataList, checkRecordId);
                }
              });
            } else {
              MsgBox.showMessageAndExitCurrentPage('保存成功！', true, context);
            }
          } else {
            MsgBox.showMessageAndExitCurrentPage('保存成功！', true, context);
          }
        }
      } else {
        MsgBox.showMessageOnly(result.message ?? '数据保存失败！', context);
        setState(() {
          isSaving = false;
        });
      }
    });
  }

  checkData(ExtClass classifySelected) {
    try {
      List<CheckItem> needCheckItems = [];
      Map<String, ItemResultData> _needCheckItemResultDataMap = {};
      needCheckItems = _checkItem;

      needCheckItems.forEach((f) {
        if (f.itemType == '文本') {
        } else if (f.itemType == '选择') {
          radioCheck(f.uniqueKey, f);
          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 = '';
      _needCheckItemResultDataMap.forEach((k, v) {
        if (null != v && null != v.hasError && v.hasError) {
          if (v.errorInfo.isNotEmpty) {
            error = error + v.errorInfo + '\r\n';
          }
          _needCheckItemResultDataMap[k].errorInfo = '';
        }
      });
      CheckPoint poin = initConfig.point;
      PlanTask plantask = initConfig.planTask;
      if (poin != null) {

        // if (poin.shotMaxNumber != null && poin.shotMaxNumber == 0 ) {
        //   if (imageList.length > 3) {
        //     return error = error + '现场照片上传数量不得大于3张' + '\r\n';
        //   }else {
        //     return error;
        //   }
        // }
        if (poin.shotMinNumber != null) {
          if (imageList.length < poin.shotMinNumber) {
            error = error + '现场照片上传数量不得小于${poin.shotMinNumber}张' + '\r\n';
          }
        }

        if (poin.shotMaxNumber != null) {
          if (imageList.length > poin.shotMaxNumber) {
            error = error + '现场照片上传数量不得大于${poin.shotMaxNumber}张' + '\r\n';
          }
        }

      } else {
        if (plantask != null) {
          //
          // if (plantask.shotMaxNumber != null && plantask.shotMaxNumber == 0 ) {
          //   if (imageList.length > 3) {
          //     return error = error + '现场照片上传数量不得大于3张' + '\r\n';
          //   }else {
          //     return error;
          //   }
          // }
          if (plantask.shotMinNumber != null) {
            if (imageList.length < plantask.shotMinNumber) {
              error = error + '现场照片上传数量不得小于${plantask.shotMinNumber}张' + '\r\n';
            }
          }
          if (plantask.shotMaxNumber != null) {
            if (imageList.length > plantask.shotMaxNumber) {
              error = error + '现场照片上传数量不得大于${plantask.shotMaxNumber}张' + '\r\n';
            }
          }
        }
      }
      return error;
    } catch (e) {
      return e;
    }
  }

  void 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 (value == null) {
      if (_itemResultDataMap[key] == null) {
        _itemResultDataMap[key] = ItemResultData.fromParams(
            routePointItemId: checkItem.routePointItemId, value: "");
      }
      _itemResultDataMap[key].hasError = true;
      _itemResultDataMap[key].errorInfo = checkItem.name + ':请输入数字';
      return;
    }

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

  void 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 = '';
        });
      }
    }
  }

  Future<void> saveSelectClassifyDialog() {
    showDialog<Null>(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, state) {
          return SimpleDialog(
            children: <Widget>[
              Container(
                child: const Text('请选择要提交的扩展分类'),
                alignment: Alignment.center,
              ),
              const Divider(
                height: 1,
              ),
              Column(
                children: initConfig.extClass.map((f) {
                  return Column(
                    children: <Widget>[
                      CheckboxListTile(
                        title: Text(f.name),
                        value: commitClassifies[f.id.toString()],
                        onChanged: (bool value) {
                          state(() {
                            commitClassifies[f.id.toString()] =
                                !commitClassifies[f.id.toString()];
                          });
                        },
                      ),
                      const Divider(
                        height: 1,
                      )
                    ],
                  );
                }).toList(),
              ),
              commitClassifies.values.where((f) => f == true).isNotEmpty
                  ? FlatButton(
                      child: const Text(
                        '提交',
                        style: TextStyle(fontSize: 16),
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                        saveData();
                      })
                  : FlatButton(
                      child: const Text(
                        '提交',
                        style: TextStyle(fontSize: 16, color: Colors.grey),
                      ),
                      onPressed: () {})
            ],
          );
        });
      },
    );
  }

  /// 任务创建
  Future<void> resultChooseDialog(List<UNCheckInput> data, num checkId) {
     StateSetter _reloadTextSetter;
    try {
      showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, state) {
            _reloadTextSetter = state;
            return SimpleDialog(
              children: <Widget>[
                Container(
                  child: const Text('请选择创建缺陷或者隐患'),
                  alignment: Alignment.center,
                ),
                const Divider(
                  height: 1,
                ),
                Container(
                    width: double.maxFinite,
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: Row(
                              children: <Widget>[
                                Radio(
                                  value: 0,
                                  groupValue: select,
                                  onChanged: (val) {
                                    setState(() {
                                      select = val;
                                      _reloadTextSetter(() {});
                                    });
                                  },
                                ),
                                GestureDetector(
                                  child: const Text('隐患'),
                                  onTap: () {
                                    setState(() {
                                      select = 0;
                                      _reloadTextSetter(() {});
                                    });
                                  },
                                )
                              ],
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: Row(
                              children: <Widget>[
                                Radio(
                                  value: 1,
                                  groupValue: select,
                                  onChanged: (val) {
                                    setState(() {
                                      select = val;
                                      _reloadTextSetter(() {});
                                    });
                                  },
                                ),
                                GestureDetector(
                                  child: const Text('缺陷'),
                                  onTap: () {
                                    setState(() {
                                      select = 1;
                                      _reloadTextSetter(() {});
                                    });
                                  },
                                )
                              ],
                            ),
                          ),
                          const Divider(
                            height: 1,
                          )
                        ])

                    // ListView.builder(
                    //     primary: false,
                    //     shrinkWrap: true,
                    //     // itemCount: 2,
                    //     itemBuilder: (context, index) {
                    //       return Column(
                    //         children: <Widget>[
                    //
                    //         ],
                    //       );
                    //     }),
                    ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                        width: 200,
                        child: FlatButton(
                            child: const Text(
                              '创建',
                              style: TextStyle(fontSize: 16),
                            ),
                            onPressed: () {
                              if (select == 0) {
                                Navigator.pop(context);
                                resultTaskDialog(data, checkId);
                              } else {
                                Navigator.pop(context);
                                resultTaskDefectDialog(data, checkId);
                              }
                            })),
                    // Container(
                    //     width: 100,
                    //     child: FlatButton(
                    //         child: const Text(
                    //           '返回',
                    //           style: TextStyle(fontSize: 16),
                    //         ),
                    //         onPressed: () {
                    //           Navigator.pop(context);
                    //           Navigator.pop(context);
                    //         }))
                  ],
                )
              ],
            );
          });
        },
      );
    } catch (e) {
      LogUtil.d(e);
    }
  }

  /// 任务创建
  Future<void> resultTaskDialog(List<UNCheckInput> data, num checkId) {
    try {
      showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, state) {
            return SimpleDialog(
              children: <Widget>[
                Container(
                  child: const Text('有不合格项是否创建任务？'),
                  alignment: Alignment.center,
                ),
                const Divider(
                  height: 1,
                ),
                Container(
                  width: double.maxFinite,
                  child: ListView.builder(
                      primary: false,
                      shrinkWrap: true,
                      itemCount: data.length,
                      itemBuilder: (context, index) {
                        UNCheckInput f = data[index];
                        return Column(
                          children: <Widget>[
                            CheckboxListTile(
                              title: Text(f.name),
                              value: unCheckInputMap[index],
                              onChanged: (bool value) {
                                state(() {
                                  unCheckInputMap[index] =
                                      !unCheckInputMap[index];
                                });
                              },
                            ),
                            const Divider(
                              height: 1,
                            )
                          ],
                        );
                      }),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Container(
                        width: 100,
                        child: FlatButton(
                            child: const Text(
                              '创建任务',
                              style: TextStyle(fontSize: 16),
                            ),
                            onPressed: () {
                              // 导航至任务列表
                              List<UNCheckInput> selectedId = [];
                              for (int e = 0; e < unCheckInputMap.length; e++) {
                                bool v = unCheckInputMap[e];
                                if (v) {
                                  selectedId.add(data[e]);
                                }
                              }
                              if (selectedId.isEmpty) {
                                MsgBox.showMessageAndExitCurrentPage(
                                    '请选择不合格项！', false, context);
                                return;
                              }
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          InspectionHiddenDangerFound(false,
                                              checkId: checkId,
                                              unCheckInputData:
                                                  selectedId))).then((v) {
                                Navigator.pop(context);
                                Navigator.pop(context);
                              });
                            })),
                    Container(
                        width: 100,
                        child: FlatButton(
                            child: const Text(
                              '返回',
                              style: TextStyle(fontSize: 16),
                            ),
                            onPressed: () {
                              Navigator.pop(context);
                              Navigator.pop(context);
                            }))
                  ],
                )
              ],
            );
          });
        },
      );
    } catch (e) {
      LogUtil.d(e);
    }
  }

  /// 任务创建
  Future<void> resultTaskDefectDialog(List<UNCheckInput> data, num checkId) {
    String equipmentId = '';
    String equipmentName = '';
    String dataSourceCode = '';
    String defectEquipmentCode = '';
    initConfig.extClass.forEach((f) {
      equipmentId = equipmentId + ( f.equipmentId == null ? '' : f.equipmentId + ',' ) ;
      equipmentName = equipmentName + f.name + ',';
      dataSourceCode = f.dataSourceCode;
      defectEquipmentCode = f.code;
    });
    if(equipmentId.contains(",")) {
      equipmentId = equipmentId.substring(0,equipmentId.length -1);
    }
    if(equipmentName.contains(",")) {
      equipmentName = equipmentName.substring(0,equipmentName.length -1);
    }
    try {
      showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, state) {
            return SimpleDialog(
              children: <Widget>[
                Container(
                  child: const Text('有不合格项是否创建任务？'),
                  alignment: Alignment.center,
                ),
                const Divider(
                  height: 1,
                ),
                Container(
                  width: double.maxFinite,
                  child: ListView.builder(
                      primary: false,
                      shrinkWrap: true,
                      itemCount: data.length,
                      itemBuilder: (context, index) {
                        UNCheckInput f = data[index];
                        return Column(
                          children: <Widget>[
                            CheckboxListTile(
                              title: Text(f.name),
                              value: unCheckInputMap[index],
                              onChanged: (bool value) {
                                state(() {
                                  unCheckInputMap[index] =
                                      !unCheckInputMap[index];
                                });
                              },
                            ),
                            const Divider(
                              height: 1,
                            )
                          ],
                        );
                      }),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Container(
                        width: 100,
                        child: FlatButton(
                            child: const Text(
                              '创建任务',
                              style: TextStyle(fontSize: 16),
                            ),
                            onPressed: () {
                              // 导航至任务列表
                              List<UNCheckInput> selectedId = [];
                              for (int e = 0; e < unCheckInputMap.length; e++) {
                                bool v = unCheckInputMap[e];
                                if (v) {
                                  selectedId.add(data[e]);
                                }
                              }
                              if (selectedId.isEmpty) {
                                MsgBox.showMessageAndExitCurrentPage(
                                    '请选择不合格项！', false, context);
                                return;
                              }
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          HiddenDefectFound(equipmentName: equipmentName,
                                              equipmentId: equipmentId,
                                              dataSourceCode: dataSourceCode,
                                              defectEquipmentCode:defectEquipmentCode,
                                              checkId: checkId,
                                              unCheckInputData:
                                                  selectedId))).then((v) {
                                Navigator.pop(context);
                                Navigator.pop(context);
                              });
                            })),
                    Container(
                        width: 100,
                        child: FlatButton(
                            child: const Text(
                              '返回',
                              style: TextStyle(fontSize: 16),
                            ),
                            onPressed: () {
                              Navigator.pop(context);
                              Navigator.pop(context);
                            }))
                  ],
                )
              ],
            );
          });
        },
      );
    } catch (e) {
      LogUtil.d(e);
    }
  }
}

class updataModel {
  String classifyIds;
  int inputItemId;
  String imageUrl;

  updataModel.fromParams({
    this.classifyIds,
    this.inputItemId,
    this.imageUrl,
  });
}

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

//  String classifyIds;

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

  @override
  String toString() {
    return '{"id": $id,"value":$value,"text":$text,"errorInfo":$errorInfo,"hasError":$hasError,"img":$img}';
  }
}

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

  RadioWidgetInfo.fromJson(jsonRes) {
    score = jsonRes['score'].toString();
    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'] == "" || jsonRes['OkScore'] == null
        ? null
        : jsonRes['OkScore'];
    NoScore = jsonRes['NoScore'] == "" || jsonRes['NoScore'] == null
        ? null
        : jsonRes['NoScore'];
    ValidUp = jsonRes['ValidUp'] == "" || jsonRes['ValidUp'] == null
        ? null
        : jsonRes['ValidUp'];
    ValidDown = jsonRes['ValidDown'] == "" || jsonRes['ValidDown'] == null
        ? null
        : jsonRes['ValidDown'];
    OkUp = jsonRes['OkUp'] == "" || jsonRes['OkUp'] == null
        ? null
        : jsonRes['OkUp'];
    OkDown = jsonRes['OkDown'] == "" || jsonRes['OkDown'] == null
        ? null
        : jsonRes['OkDown'];
    CheckValidUp = jsonRes['CheckValidUp'];
    CheckValidDown = jsonRes['CheckValidDown'];
    CheckOkUp = jsonRes['CheckOkUp'];
    CheckOkDown = jsonRes['CheckOkDown'];
    Precision = jsonRes['Precision'] == "" || jsonRes['Precision'] == null
        ? null
        : jsonRes['Precision'];
  }
}
