import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:base/consts/color.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 '../../model/Task/TaskAddModel.dart';
import '../../services/HiddenDanger.dart';
import '../../view/CheckExecute/checkexec_inspection_list.dart';
import '../../view/hidedanger_manage/hidden_danger_found.dart';

class InspectionHiddenDangerFound extends StatefulWidget {
  final num checkId;
  final num planId;

  List<UNCheckInput> unCheckInputData;

  final bool isGetQueryUnqualifiedInputItemFlag;

  InspectionHiddenDangerFound(this.isGetQueryUnqualifiedInputItemFlag, {this.checkId, this.unCheckInputData, this.planId});

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

class _InspectionHiddenDangerFound extends State<InspectionHiddenDangerFound> {
  List<TaskErrorItem> items = [];
  List<TaskErrorItem> olditems = [];
  bool isAnimating = false;
  bool canOperate = true;
  String theme = '';
  List<UNCheckInput> oldCheckInputData = [];

  Future<void> reSetValue() async {
    setState(() {
      if (widget.unCheckInputData != null) {
        for (int i = 0; i < widget.unCheckInputData.length; i++) {
          var f = widget.unCheckInputData[i];
          var c = oldCheckInputData[i];
          f.name = c.name;
          f.remark = c.remark;
          f.dangerLevel = 0;
          f.isSelected = false;
        }
      } else if (items != null) {
        for (int i = 0; i < items.length; i++) {
          var f = items[i];
          var c = olditems[i];
          f.name = c.name;
          f.remark = c.remark;
          f.dangerLevel = 0;
          f.selected = false;
        }
      }
    });
  }

  bool _checkNeed() {
    if (widget.unCheckInputData != null) {
      for (final UNCheckInput item in widget.unCheckInputData) {
        if (item.dangerLevel == null) {
          HiddenDangerFound.popUpMsg('请选择：  “' + item.name + '”  巡检项的隐患等级');
          return false;
        }
        if (item.remark == null || item.remark.isEmpty) {
          HiddenDangerFound.popUpMsg('请填写：  “' + item.name + '”  问题描述');
          return false;
        }
      }
    } else if (items != null) {
      for (final TaskErrorItem item in items) {
        if (item.dangerLevel == null || item.dangerLevel == -1) {
          HiddenDangerFound.popUpMsg('请选择：  “' + item.name + '”  巡检项的隐患等级');
          return false;
        }
        if (item.remark == null || item.remark.isEmpty) {
          HiddenDangerFound.popUpMsg('请填写：  “' + item.name + '”  问题描述');
          return false;
        }
      }
    }
    return true;
  }

  Future<void> _saveData(num checkId, List<TaskDetailForAdd> details) async {
    setState(() {
      isAnimating = true;
      canOperate = false;
    });
    await saveInspectionDangerInfo(checkId, details).then((data) {
      if (data.success) {
        MsgBox.showMessageAndExitCurrentPage('隐患提交成功！', true, context);
      } else {
        HiddenDangerFound.popUpMsg(data.message ?? '隐患提交失败！');
      }
      setState(() {
        isAnimating = false;
        canOperate = true;
      });
    }).catchError((e) {
      HiddenDangerFound.popUpMsg('隐患提交失败！');
      setState(() {
        isAnimating = false;
        canOperate = true;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    initInfo();
    if (widget.unCheckInputData != null) {
      for (UNCheckInput asd in widget.unCheckInputData) {
        if (widget.unCheckInputData != null) {
          for (final UNCheckInput asd in widget.unCheckInputData) {
            UNCheckInput item = UNCheckInput.fromParams(
              name: asd.name,
              isSelected: asd.isSelected,
              value: asd.value,
              routePointItemId: asd.routePointItemId,
              itemId: asd.itemId,
              limitDate: asd.limitDate,
              dangerLevel: asd.dangerLevel,
              remark: asd.remark,
            );
            oldCheckInputData.add(item);
          }
        }
      }
    }
  }

  Future<void> initInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        setState(() {
          theme = data.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        });
      }
    }).then((data) {
      if (widget.isGetQueryUnqualifiedInputItemFlag) {
        getQueryUnqualifiedInputItem();
      }
    });
  }

  Future<void> getQueryUnqualifiedInputItem() async {
    if (widget.unCheckInputData == null && widget.checkId >= 0) {
      await queryUnqualifiedInputItem(widget.checkId).then((data) {
        setState(() {
          items = data;

          if (data != null) {
            for (final TaskErrorItem asd in data) {
              TaskErrorItem item = TaskErrorItem.fromParams(
                name: asd.name,
                checkId: asd.checkId,
                inputValue: asd.inputValue,
                pointId: asd.pointId,
                routeId: asd.routeId,
                itemId: asd.itemId,
                limitDate: asd.limitDate,
                dangerLevel: asd.dangerLevel,
                route_point_item_id: asd.route_point_item_id,
                remark: asd.remark,
              );
              olditems.add(item);
            }
          }
        });
      });
    } else {
      HiddenDangerFound.popUpMsg('数据不存在');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.unCheckInputData == null && (widget.checkId == null || widget.checkId < 0)) {
      return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
            title: const Text(
              '隐患添加',
            ),
            centerTitle: true,
            elevation: 0.2,
            brightness: Brightness.light,
          ),
          body: Container(),
        ),
        onWillPop: () {
          Navigator.pop(context);
        },
      );
    }

    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          title: const Text(
            '隐患添加',
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
        ),
        body: ModalProgressHUD(
          child: Container(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                Container(
                  height: 50.0,
                  margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: const <Widget>[
                      Text('说明:请确定检查不通过的是否转换为隐患任务', style: TextStyle(color: Colors.red, fontWeight: FontWeight.w700))
                    ],
                  ),
                ),
                Container(
                  height: 10,
                  color: const Color.fromRGBO(244, 244, 244, 1),
                ),
                widget.unCheckInputData != null
                    ? Expanded(
                        child: SingleChildScrollView(
                            child: ListView.builder(
                                shrinkWrap: true,
                                // physics: NeverScrollableScrollPhysics(),
                                itemCount: widget.unCheckInputData.length,
                                primary: false,
                                itemBuilder: (context, index) {
                                  TextEditingController controller = TextEditingController();
                                  controller.text = widget.unCheckInputData[index].name;
                                  return Container(
                                      // color: Colors.red,
                                      child: Column(
                                    children: <Widget>[
                                      //巡检项
                                      Container(
                                          width: MediaQuery.of(context).size.width - 20,
                                          margin: const EdgeInsets.only(
                                            left: 10.0,
                                          ),
                                          child: TextField(
                                            textInputAction: TextInputAction.done,
                                            onChanged: (text) {
                                              widget.unCheckInputData[index].name = text;
                                            },
                                            maxLines: 10,
                                            minLines: 1,
                                            controller: controller,
                                            onEditingComplete: () => FocusScope.of(context).requestFocus(FocusNode()),
                                            decoration: InputDecoration(
                                              suffixIcon: Icon(
                                                Icons.border_color,
                                                color: GetConfig.getColor(theme),
                                              ),
                                              enabledBorder: const UnderlineInputBorder(
                                                // 不是焦点的时候颜色
                                                borderSide: BorderSide(color: Color(0x19000000)),
                                              ),
                                              focusedBorder: const UnderlineInputBorder(
                                                // 焦点集中的时候颜色
                                                borderSide: BorderSide(color: Color(0x19000000)),
                                              ),
                                            ),
                                          )),
                                      Container(
                                        margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                                        child: Row(
                                          children: const [
                                            Text(
                                              '*',
                                              style: TextStyle(color: Colors.red),
                                            ),
                                            Text('问题描述：')
                                          ],
                                        ),
                                      ),
                                      Container(
                                        margin: const EdgeInsets.only(top: 10.0),
                                        padding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
                                        width: MediaQuery.of(context).size.width - 30,
                                        color: Colors.black12,
                                        child: TextField(
                                            maxLength: 500,
                                            maxLines: 20,
                                            minLines: 3,
                                            onChanged: (text) {
                                              widget.unCheckInputData[index].remark = text;
                                            },
                                            decoration: const InputDecoration(
                                              // labelText: '问题描述：',
                                              labelStyle: TextStyle(color: Color(0x99000000)),
                                              hintText: '请输入',
                                              // 主要添加以下代码
                                              enabledBorder: UnderlineInputBorder(
                                                // 不是焦点的时候颜色
                                                borderSide: BorderSide(color: Colors.white10),
                                              ),
                                              focusedBorder: UnderlineInputBorder(
                                                // 焦点集中的时候颜色
                                                borderSide: BorderSide(color: Colors.white10),
                                              ),
                                            )),
                                      ),
                                      //巡检项等级
                                      Container(
                                        // color: Colors.yellow,
                                        margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                                        width: MediaQuery.of(context).size.width - 20,
                                        //child:Expanded(
                                        child: Row(
                                          children: <Widget>[
                                            Expanded(
                                              flex: 1,
                                              child: Row(
                                                children: <Widget>[
                                                  Radio(
                                                    value: 0,
                                                    groupValue: widget.unCheckInputData[index].dangerLevel,
                                                    onChanged: (val) {
                                                      setState(() {
                                                        widget.unCheckInputData[index].dangerLevel = val;
                                                      });
                                                    },
                                                  ),
                                                  GestureDetector(
                                                    child: const Text('安全问题'),
                                                    onTap: () {
                                                      setState(() {
                                                        widget.unCheckInputData[index].dangerLevel = 0;
                                                      });
                                                    },
                                                  )
                                                ],
                                              ),
                                            ),
                                            Expanded(
                                              flex: 1,
                                              child: Row(
                                                children: <Widget>[
                                                  Radio(
                                                    value: 1,
                                                    groupValue: widget.unCheckInputData[index].dangerLevel,
                                                    onChanged: (val) {
                                                      setState(() {
                                                        widget.unCheckInputData[index].dangerLevel = val;
                                                      });
                                                    },
                                                  ),
                                                  GestureDetector(
                                                    child: const Text('一般隐患'),
                                                    onTap: () {
                                                      setState(() {
                                                        widget.unCheckInputData[index].dangerLevel = 1;
                                                      });
                                                    },
                                                  )
                                                ],
                                              ),
                                            ),
                                            Expanded(
                                              flex: 1,
                                              child: Row(
                                                children: <Widget>[
                                                  Radio(
                                                    value: 2,
                                                    groupValue: widget.unCheckInputData[index].dangerLevel,
                                                    onChanged: (val) {
                                                      setState(() {
                                                        widget.unCheckInputData[index].dangerLevel = val;
                                                      });
                                                    },
                                                  ),
                                                  GestureDetector(
                                                    child: const Text('重大隐患'),
                                                    onTap: () {
                                                      setState(() {
                                                        widget.unCheckInputData[index].dangerLevel = 2;
                                                      });
                                                    },
                                                  )
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                        // flex: 3,
                                        // ),
                                      ),
                                      Container(
                                        height: 10,
                                        color: const Color.fromRGBO(244, 244, 244, 1),
                                      ),
                                    ],
                                  ));
                                })))
                    : (items != null && items.isNotEmpty
                        ? Expanded(
                            child: SingleChildScrollView(
                                child: ListView.builder(
                                    shrinkWrap: true,
                                    //physics: NeverScrollableScrollPhysics(),
                                    itemCount: items.length,
                                    primary: false,
                                    itemBuilder: (context, index) {
                                      TextEditingController controller = TextEditingController();
                                      controller.text = items[index].name;
                                      return Container(
                                          //color: Colors.cyanAccent,
                                          child: Column(
                                        children: <Widget>[
                                          Container(
                                              width: MediaQuery.of(context).size.width - 20,
                                              margin: const EdgeInsets.only(
                                                left: 10.0,
                                              ),
                                              child: TextField(
                                                textInputAction: TextInputAction.done,
                                                onChanged: (text) {
                                                  items[index].name = text;
                                                },
                                                maxLines: 10,
                                                minLines: 1,
                                                controller: controller,
                                                onEditingComplete: () => FocusScope.of(context).requestFocus(FocusNode()),
                                                decoration: InputDecoration(
                                                  suffixIcon: Icon(
                                                    Icons.border_color,
                                                    color: GetConfig.getColor(theme),
                                                  ),
                                                  enabledBorder: const UnderlineInputBorder(
                                                    // 不是焦点的时候颜色
                                                    borderSide: BorderSide(color: Color(0x19000000)),
                                                  ),
                                                  focusedBorder: const UnderlineInputBorder(
                                                    // 焦点集中的时候颜色
                                                    borderSide: BorderSide(color: Color(0x19000000)),
                                                  ),
                                                ),
                                              )),
                                          Container(
                                            margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                                            child: Row(
                                              children: const [
                                                Text(
                                                  '*',
                                                  style: TextStyle(color: Colors.red),
                                                ),
                                                Text('问题描述：')
                                              ],
                                            ),
                                          ),
                                          Container(
                                            margin: const EdgeInsets.only(top: 10.0),
                                            padding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
                                            width: MediaQuery.of(context).size.width - 30,
                                            //color: Colors.green,
                                            color: Colors.black12,
                                            child: TextField(
                                                maxLength: 500,
                                                maxLines: 20,
                                                minLines: 3,
                                                onChanged: (text) {
                                                  items[index].remark = text;
                                                },
                                                controller: TextEditingController(text: items[index].remark),
                                                decoration: const InputDecoration(
                                                  // labelText: '问题描述：',
                                                  labelStyle: TextStyle(color: Color(0x99000000)),
                                                  hintText: '请输入',
                                                  // 主要添加以下代码
                                                  enabledBorder: UnderlineInputBorder(
                                                    // 不是焦点的时候颜色
                                                    borderSide: BorderSide(color: Colors.white10),
                                                  ),
                                                  focusedBorder: UnderlineInputBorder(
                                                    // 焦点集中的时候颜色
                                                    borderSide: BorderSide(color: Colors.white10),
                                                  ),
                                                )),
                                          ),
                                          //巡检项等级
                                          Container(
                                            margin: const EdgeInsets.only(top: 10.0, left: 10.0),
                                            width: MediaQuery.of(context).size.width - 20,
                                            //child:Expanded(
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.start,
                                              children: <Widget>[
                                                Expanded(
                                                  flex: 1,
                                                  child: Row(
                                                    children: <Widget>[
                                                      Radio(
                                                        value: 0,
                                                        groupValue: items[index].dangerLevel ?? 0,
                                                        onChanged: (val) {
                                                          setState(() {
                                                            items[index].dangerLevel = val;
                                                          });
                                                        },
                                                      ),
                                                      GestureDetector(
                                                        child: const Text('安全问题'),
                                                        onTap: () {
                                                          setState(() {
                                                            items[index].dangerLevel = 0;
                                                          });
                                                        },
                                                      )
                                                    ],
                                                  ),
                                                  //带文字的单选按钮 value值=groupValue值 即选中状态
                                                ),
                                                Expanded(
                                                  flex: 1,
                                                  child: Row(
                                                    children: <Widget>[
                                                      Radio(
                                                        value: 1,
                                                        groupValue: items[index].dangerLevel,
                                                        onChanged: (val) {
                                                          setState(() {
                                                            items[index].dangerLevel = val;
                                                          });
                                                        },
                                                      ),
                                                      GestureDetector(
                                                        child: const Text('一般隐患'),
                                                        onTap: () {
                                                          setState(() {
                                                            items[index].dangerLevel = 1;
                                                          });
                                                        },
                                                      )
                                                    ],
                                                  ),
                                                  //带文字的单选按钮 value值=groupValue值 即选中状态
                                                ),
                                                Expanded(
                                                  flex: 1,
                                                  child: Row(
                                                    children: <Widget>[
                                                      Radio(
                                                        value: 2,
                                                        groupValue: items[index].dangerLevel,
                                                        onChanged: (val) {
                                                          setState(() {
                                                            items[index].dangerLevel = val;
                                                          });
                                                        },
                                                      ),
                                                      GestureDetector(
                                                        child: const Text('重大隐患'),
                                                        onTap: () {
                                                          setState(() {
                                                            items[index].dangerLevel = 2;
                                                          });
                                                        },
                                                      )
                                                    ],
                                                  ),
                                                  //带文字的单选按钮 value值=groupValue值 即选中状态
                                                ),
                                              ],
                                            ),
                                            //   flex: 3,
                                            // ),
                                          ),
                                          Container(
                                            height: 10,
                                            color: const Color.fromRGBO(244, 244, 244, 1),
                                          ),
                                        ],
                                      ));
                                    })))
                        : Container()),
              ],
            ),
          ),
          //),
          inAsyncCall: isAnimating,
          // demo of some additional parameters
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        ),
        persistentFooterButtons: <Widget>[
          Row(
            children: <Widget>[
              Container(
                width: (MediaQuery.of(context).size.width / 2) - 16,
                height: 50,
                margin: const EdgeInsets.only(left: 0),
                child: MaterialButton(
                  color: const Color.fromRGBO(242, 246, 249, 1),
                  height: 50,
                  textColor: Colors.black,
                  child: const Text(
                    '重置',
                    style: TextStyle(fontSize: 24),
                  ),
                  onPressed: () {
                    if (canOperate) {
                      reSetValue();
                    } else {
                      HiddenDangerFound.popUpMsg('正在执行操作！请稍等...');
                    }
                  },
                ),
              ),
              Container(
                width: MediaQuery.of(context).size.width / 2,
                child: MaterialButton(
                    color: GetConfig.getColor(theme),
                    height: 50,
                    textColor: Colors.white,
                    child: const Text('确定', style: TextStyle(fontSize: 24)),
                    onPressed: () {
                      if (_checkNeed()) {
                        if (!canOperate) {
                          HiddenDangerFound.popUpMsg('正在执行操作！请稍等...');
                        } else {
                          List<TaskDetailForAdd> details = [];
                          if (widget.unCheckInputData != null) {
                            widget.unCheckInputData.forEach((f) {
                              details.add(TaskDetailForAdd.fromParams(
                                  checkId: widget.checkId,
                                  itemId: f.itemId,
                                  dangerLevel: f.dangerLevel,
                                  routePointItemId: f.routePointItemId,
                                  name: f.name,
                                  remark: f.remark));
                            });
                          } else {
                            items.forEach((f) {
                              details.add(TaskDetailForAdd.fromParams(
                                  checkId: widget.checkId,
                                  itemId: f.itemId,
                                  dangerLevel: f.dangerLevel,
                                  routePointItemId: f.route_point_item_id,
                                  name: f.name,
                                  remark: f.remark));
                            });
                          }
                          canOperate = false;
                          _saveData(widget.checkId, details);
                        }
                      }
                    }),
              ),
            ],
          ),
        ],
        resizeToAvoidBottomPadding: false,
      ),
      onWillPop: () {
        Navigator.pop(context);
      },
    );
  }
}
