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/CheckItem.dart';
import '../../model/MovePointAddModel.dart';
import '../../services/check_point_service.dart';
import '../../view/move_inspection/check_item_list.dart';
import '../../view/move_inspection/check_item_set.dart';

class MoveSpotAdd extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MoveSpotAddState();
}

class _MoveSpotAddState extends State<MoveSpotAdd> {
  String _noControllerErrorText = '';
  String _nameControllerErrorText = '';
  String _checkItemErrorText = '';
  final TextEditingController _noController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _noteController = TextEditingController();

  // 数据对象
  MovePointAddModel movePoint;

  List<CheckItem> selectedCheckItem = [];

  // 是否保存中
  bool isSaving = false;

  String theme = '';

  @override
  void initState() {
    super.initState();
    setState(() {
      movePoint = MovePointAddModel.fromJson({});
      movePoint.offline = false;
    });
    initConfig();
  }

  initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme = preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  saveMovePoint() async {
    setState(() {
      isSaving = true;
    });

    // 验证巡检点编号
    await _noControllerValidation().then((result) {
      // 验证巡检点名称
      _nameControllerValidation();
      // 验证检查项
      _checkItemValidation();

      if (this._noControllerErrorText.isEmpty &&
          this._nameControllerErrorText.isEmpty &&
          this._checkItemErrorText.isEmpty) {
        List<int> inputItemIds = List();
        this.selectedCheckItem.forEach((f) {
          inputItemIds.add(f.id);
        });
        movePoint.inputItems = inputItemIds.join(",");
        // 默认值
        movePoint.shotMaxNumber = 10;
        movePoint.shotMinNumber = 1;
        saveData(movePoint);
      }
    });
  }

  saveData(MovePointAddModel movePoint) async {
    await addMovePoint(movePoint).then((result) {
      setState(() {
        isSaving = false;
      });
      if (result.isOk()) {
        MsgBox.showMessageAndExitCurrentPage('保存成功！', true, context);
      } else {
        MsgBox.showMessageOnly('保存失败！', context);
      }
    });
  }

  // 巡检编号验证
  Future<bool> _noControllerValidation() async {
    if (null == movePoint.pointNo || movePoint.pointNo == '') {
      setState(() {
        isSaving = false;
        _noControllerErrorText = '巡检点编号不能为空';
      });
      return false;
    }

    String noReg = r'.*[\u4e00-\u9fa5]{1,}.*';
    RegExp regExp = RegExp(noReg);
    if (regExp.hasMatch(movePoint.pointNo)) {
      setState(() {
        isSaving = false;
        _noControllerErrorText = '巡检点编号不能输入中文';
      });
      return false;
    }

    // 验证是否重复
    await queryAllPotinNos().then((pointNos) {
      // 编号已存在
      if (pointNos.contains(movePoint.pointNo)) {
        setState(() {
          isSaving = false;
          _noControllerErrorText = '巡检点编号已存在';
        });
        return false;
      } else {
        setState(() {
          _noControllerErrorText = '';
        });
        return true;
      }
    }).then((result) {
      return result;
    });
  }

  // 检查项验证
  void _checkItemValidation() {
    if (null == selectedCheckItem || selectedCheckItem.isEmpty) {
      setState(() {
        isSaving = false;
        _checkItemErrorText = '至少选择一个检查项';
      });
    } else {
      setState(() {
        _checkItemErrorText = '';
      });
    }
  }

  // 巡检名称验证
  void _nameControllerValidation() {
    if (null == movePoint.name || movePoint.name == '') {
      setState(() {
        isSaving = false;
        _nameControllerErrorText = '巡检点名称不能为空';
      });
    } else {
      setState(() {
        _nameControllerErrorText = '';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果还未初始化
    if (null == movePoint) {
      return Scaffold(
          appBar: AppBar(
        title: const Text(
          '移动巡检点添加',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ));
    }

    return ModalProgressHUD(
        inAsyncCall: isSaving,
        opacity: 0.2,
        progressIndicator: const CircularProgressIndicator(),
        child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: const Text(
              '移动巡检点添加',
            ),
            centerTitle: true,
            elevation: 0.2,
            brightness: Brightness.light,
          ),
          body: Padding(
              padding: const EdgeInsets.only(left: 10, top: 10),
              child: ListView.builder(
                itemCount: 1,
                itemBuilder: (BuildContext context, int index) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text.rich(TextSpan(children: [
                        const TextSpan(
                          text: '*',
                          style: TextStyle(color: Colors.red),
                        ),
                        const TextSpan(
                          text: '巡检点编号',
                        ),
                        TextSpan(
                          text: _noControllerErrorText,
                          style: const TextStyle(color: Colors.red, fontSize: 12),
                        ),
                      ])),
                      const Padding(
                        padding: EdgeInsets.only(top: 5),
                      ),
                      Container(
                          height: 40,
                          width: MediaQuery.of(context).size.width - 20,
                          padding: const EdgeInsets.only(bottom: 5),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                          ),
                          child: Container(
                            child: TextField(
                              controller: _noController,
                              autofocus: false,
                              style: const TextStyle(fontSize: 16.0, color: Colors.black),
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                              ),
                              onChanged: (val) {
                                // 编辑事件赋值
                                setState(() {
                                  movePoint.pointNo = val;
                                });
                              },
                            ),
                          )),
                      const Padding(
                        padding: EdgeInsets.only(top: 15),
                      ),
                      Text.rich(
                        TextSpan(children: [
                          const TextSpan(
                            text: '*',
                            style: TextStyle(color: Colors.red),
                          ),
                          const TextSpan(text: '巡检点名称'),
                          TextSpan(
                            text: _nameControllerErrorText,
                            style: const TextStyle(color: Colors.red, fontSize: 12),
                          )
                        ]),
                      ),
                      const Padding(
                        padding: EdgeInsets.only(top: 5),
                      ),
                      Container(
                          height: 40,
                          width: MediaQuery.of(context).size.width - 20,
                          padding: const EdgeInsets.only(bottom: 5),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                          ),
                          child: Container(
                            child: TextField(
                              controller: _nameController,
                              autofocus: false,
                              style: const TextStyle(fontSize: 16.0, color: Colors.black),
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                              ),
                              onChanged: (val) {
                                setState(() {
                                  // 编辑事件赋值
                                  movePoint.name = val;
                                });
                              },
                            ),
                          )),
                      const Padding(
                        padding: EdgeInsets.only(top: 15),
                      ),
                      const Text('是否允许离线巡检'),
                      const Padding(
                        padding: EdgeInsets.only(top: 5),
                      ),
                      Row(
                        children: <Widget>[
                          Radio(
                            groupValue: movePoint.offline,
                            activeColor: Theme.of(context).primaryColor,
                            value: true,
                            onChanged: (bool val) {
                              // val 与 value 的类型对应
                              setState(() {
                                movePoint.offline = val;
                              });
                            },
                          ),
                          const Text('允许'),
                          Radio(
                            groupValue: movePoint.offline,
                            activeColor: Theme.of(context).primaryColor,
                            value: false,
                            onChanged: (val) {
                              // val 与 value 的类型对应
                              setState(() {
                                movePoint.offline = val;
                              });
                            },
                          ),
                          const Text('不允许')
                        ],
                      ),
                      const Padding(
                        padding: EdgeInsets.only(top: 15),
                      ),
                      Text.rich(
                        TextSpan(children: [
                          const TextSpan(
                            text: '*',
                            style: TextStyle(color: Colors.red),
                          ),
                          const TextSpan(text: "检查项目"),
                          TextSpan(
                            text: _checkItemErrorText,
                            style: const TextStyle(color: Colors.red, fontSize: 12),
                          )
                        ]),
                      ),
                      const Padding(
                        padding: EdgeInsets.only(top: 5),
                      ),
                      Container(
                          height: 40,
                          width: MediaQuery.of(context).size.width - 20,
                          padding: const EdgeInsets.only(bottom: 5),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                          ),
                          child: Container(
                            child: InkWell(
                              child: Container(
                                padding: const EdgeInsets.only(top: 7, bottom: 7),
                                decoration: BoxDecoration(
                                  color: Colors.grey[100],
                                  borderRadius: const BorderRadius.all(Radius.circular(25.0)),
                                ),
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      width: MediaQuery.of(context).size.width - 60,
                                      child: Row(
                                          children: (selectedCheckItem.length > 2
                                                  ? selectedCheckItem.sublist(0, 2).toList()
                                                  : selectedCheckItem)
                                              .map((f) {
                                        return Text(
                                          f.name + ';',
                                          overflow: TextOverflow.ellipsis,
                                        );
                                      }).toList()),
                                    ),
                                    Icon(
                                      Icons.keyboard_arrow_right,
                                      color: Theme.of(context).primaryColor,
                                    )
                                  ],
                                ),
                              ),
                              onTap: () {
                                if (null == selectedCheckItem || selectedCheckItem.isEmpty) {
                                  // 去添加节点页面
                                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                                    return CheckItemList([]);
                                  })).then((data) {
                                    setState(() {
                                      selectedCheckItem = data ?? [];
                                    });
                                    _checkItemValidation();
                                  });
                                } else {
                                  // 去节点维护页面
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(builder: (context) => CheckItemSet(selectedCheckItem)),
                                  ).then((data) {
                                    setState(() {
                                      selectedCheckItem = data ?? [];
                                    });
                                    _checkItemValidation();
                                  });
                                }
                              },
                            ),
                          )),
                      const Padding(
                        padding: EdgeInsets.only(top: 15),
                      ),
                      const Text('备注说明'),
                      const Padding(
                        padding: EdgeInsets.only(top: 5),
                      ),
                      Container(
                          height: 120,
                          width: MediaQuery.of(context).size.width - 20,
                          padding: const EdgeInsets.only(bottom: 5),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                          ),
                          child: Container(
                            child: TextField(
                              maxLines: 20,
                              controller: _noteController,
                              autofocus: false,
                              style: const TextStyle(fontSize: 16.0, color: Colors.black),
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                              ),
                              onChanged: (val) {
                                setState(() {
                                  // 编辑事件赋值
                                  movePoint.remark = val;
                                });
                              },
                            ),
                          )),
                    ],
                  );
                },
              )),
          persistentFooterButtons: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  width: (MediaQuery.of(context).size.width / 2) - 10,
                  height: 50,
                  color: const Color.fromRGBO(245, 245, 245, 1),
                  child: MaterialButton(
                      onPressed: () {
                        if (isSaving) {
                          return;
                        }
                        setState(() {
                          _noController.text = '';
                          _nameController.text = '';
                          // 清空检查项
                          selectedCheckItem = [];
                          _noteController.text = '';
                        });
                      },
                      child: const Text('重置', style: TextStyle(color: Colors.black, fontSize: 18))),
                ),
                Container(
                  width: (MediaQuery.of(context).size.width / 2) - 10,
                  height: 50,
                  color: Theme.of(context).primaryColor,
                  child: MaterialButton(
                    onPressed: () {
                      if (isSaving) {
                        return;
                      }
                      saveMovePoint();
                    },
                    child: const Text('确定', style: TextStyle(color: Colors.white, fontSize: 18)),
                  ),
                )
              ],
            )
          ],
          resizeToAvoidBottomPadding: false,
        ));
  }
}
