import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:base/consts/color.dart';
import 'package:base/model/ContactInfo.dart';
import 'package:base/view/my/contact/contact_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../model/Task/TaskAddModel.dart';
import '../../../services/TaskServices.dart';

class TaskAdditionScreen extends StatefulWidget {
  final num checkId;
  final List<num> selectedItemId;

  const TaskAdditionScreen({this.checkId, this.selectedItemId});

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

class _TaskAdditionScreenState extends State<TaskAdditionScreen> {
  final TextEditingController _namecontroller = TextEditingController();
  final TextEditingController _statementcontroller = TextEditingController();
  final TextEditingController _timescontroller = TextEditingController();
  final TextEditingController _lowcontroller = TextEditingController(text: '1');
  final TextEditingController _highcontroller = TextEditingController(text: '5');
  bool radioval = true;
  bool radioval2 = true;
  String _completeDate;
  int _completeDateM;
  String _alertDate;
  int _alertDateM;
  String _contactName = '';
  int _contactId = -1;
  int _deptId = -1;
  List<TaskErrorItem> items = [];
  bool isSavedPressed = false;
  bool isAnimating = false;
  String theme = '';

  @override
  void initState() {
    super.initState();
    if (widget.checkId != null && widget.checkId > 0) {
      getQueryUnqualifiedInputItem(widget.checkId);
    }
    _timescontroller.text = '2';
    initConfig();
  }

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text(
          '任务添加',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ),
      body: ModalProgressHUD(
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
        child: Form(
          child: ListView(
            children: <Widget>[
              Container(
                height: 30.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,
                      ),
                    ),
                    Text(
                      '任务名称',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.all(10.0),
                color: Colors.grey[100],
                child: TextField(
                  controller: _namecontroller,
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: '输入',
                    contentPadding: EdgeInsets.all(10.0),
                  ),
                ),
              ),
              //不合格检查项
              items.isNotEmpty
                  ? Container(
                      height: 30.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,
                            ),
                          ),
                          Text(
                            '不合格检查项',
                            style: TextStyle(fontSize: 15.0),
                          ),
                        ],
                      ),
                    )
                  : Container(),
              Container(
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: items.length,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        child: Row(
                          children: <Widget>[
                            Checkbox(
                                value: items[index].selected,
                                onChanged: (bool) {
                                  setState(() {
                                    items[index].selected = !items[index].selected;
                                  });
                                }),
                            Container(
                              width: 260,
                              child: Text(
                                items[index].name,
                                style: const TextStyle(
                                  color: Colors.black,
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    }),
              ),
              //设置完成时间
              Container(
                height: 30.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,
                      ),
                    ),
                    Text(
                      '设置完成时间',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                  margin: const EdgeInsets.all(10.0),
                  child: GestureDetector(
                    child: Container(
                      height: 40,
                      width: 340,
                      padding: const EdgeInsets.only(bottom: 5),
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                      ),
                      child: Stack(
                        children: <Widget>[
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: const EdgeInsets.only(left: 5),
                            child: Text(_completeDate ?? ''),
                          ),
                          Container(
                            alignment: Alignment.centerRight,
                            child:  Icon(
                              Icons.calendar_today_outlined,
                              color: Theme.of(context).primaryColor,
                            ),
                          )
                        ],
                      ),
                    ),
                    onTap: () {
                      DatePicker.showDateTimePicker(context,
                          showTitleActions: true,
                          theme: const DatePickerTheme(),
                          onChanged: (date) {}, onConfirm: (date) {
                        setState(() {
                          _completeDate = date.toString().substring(0, 16);
                          _completeDateM = date.millisecondsSinceEpoch;
                        });
                      }, currentTime: DateTime.now(), locale: LocaleType.zh);
                    },
                  )),
              //是否需要提醒
              Container(
                height: 30.0,
                margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: const <Widget>[
                    Text(
                      '是否需要提醒',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: RadioListTile(
                          activeColor: Theme.of(context).primaryColor,
                          value: true,
                          title: const Text('是'),
                          groupValue: radioval,
                          onChanged: (val) {
                            setState(() {
                              radioval = val;
                            });
                          }),
                    ),
                    Expanded(
                      flex: 1,
                      child: RadioListTile(
                          activeColor: Theme.of(context).primaryColor,
                          value: false,
                          title: const Text('否'),
                          groupValue: radioval,
                          onChanged: (val) {
                            setState(() {
                              radioval = val;
                            });
                          }),
                    ),
                    Expanded(
                      flex: 2,
                      child: Container(),
                    )
                  ],
                ),
              ),
              //设置提醒时间
              Offstage(
                offstage: !radioval,
                child: Container(
                  height: 30.0,
                  margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: const <Widget>[
                      Text(
                        '设置提醒时间',
                        style: TextStyle(fontSize: 15.0),
                      ),
                    ],
                  ),
                ),
              ),
              Offstage(
                offstage: !radioval,
                child: Container(
                    margin: const EdgeInsets.all(10.0),
                    child: GestureDetector(
                      child: Container(
                        height: 40,
                        width: 340,
                        padding: const EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const EdgeInsets.only(left: 5),
                              child: Text(_alertDate ?? ''),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Icon(
                                Icons.calendar_today_outlined,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true,
                            theme: const DatePickerTheme(),
                            onChanged: (date) {}, onConfirm: (date) {
                          setState(() {
                            _alertDateM = date.millisecondsSinceEpoch;
                            _alertDate = date.toString().substring(0, 16);
                          });
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      },
                    )),
              ),
              //任务说明
              Container(
                height: 30.0,
                margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: const <Widget>[
                    Text(
                      '任务说明',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.all(10.0),
                color: Colors.grey[200],
                child: TextField(
                  controller: _statementcontroller,
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: '输入',
                    contentPadding: EdgeInsets.all(10.0),
                  ),
                ),
              ),
              //执行人员
              Container(
                height: 30.0,
                margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: const <Widget>[
                    Text(
                      '执行人员',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.all(10.0),
                color: Colors.grey[200],
                child: GestureDetector(
                  child: Container(
                    height: 40,
                    width: 340,
                    padding: const EdgeInsets.only(bottom: 5),
                    decoration: BoxDecoration(
                      color: Colors.grey[100],
                    ),
                    child: Stack(
                      children: <Widget>[
                        Container(
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 5),
                          child: Text(_contactName),
                        ),
                        Container(
                          alignment: Alignment.centerRight,
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            size: 14,
                            color: Theme.of(context).primaryColor,
                          ),
                        )
                      ],
                    ),
                  ),
                  onTap: () {
                    Navigator.push(context, MaterialPageRoute(builder: (context) {
                      return const ContactPage(
                        type: '1',
                      );
                    })).then((value) {
                      if (value != null) {
                        setState(() {
                          ChildInfo model = value;
                          _contactName = model.name;
                          _contactId = int.parse(model.id);
                          _deptId = int.parse(model.depId);
                        });
                      }
                    });
                  },
                ),
              ),
              //可转发次数
              Container(
                height: 30.0,
                margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: const <Widget>[
                    Text(
                      '可转发次数',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.all(10.0),
                color: Colors.grey[200],
                child: TextField(
                  controller: _timescontroller,
                  inputFormatters: <TextInputFormatter>[
                    WhitelistingTextInputFormatter.digitsOnly,
                  ],
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: '输入框为空，不限制转发次数',
                    contentPadding: EdgeInsets.all(10.0),
                  ),
                ),
              ),
              //是否必需拍照
              Container(
                height: 30.0,
                margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: const <Widget>[
                    Text(
                      '是否必需拍照',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: RadioListTile(
                          activeColor: Theme.of(context).primaryColor,
                          value: true,
                          title: const Text('是'),
                          groupValue: radioval2,
                          onChanged: (val) {
                            setState(() {
                              radioval2 = val;
                              if (null == _lowcontroller.text || _lowcontroller.text == '') {
                                _lowcontroller.text = '1';
                              }
                              if (null == _highcontroller.text || _highcontroller.text == '') {
                                _highcontroller.text = '5';
                              }
                            });
                          }),
                    ),
                    Expanded(
                      flex: 1,
                      child: RadioListTile(
                          activeColor: Theme.of(context).primaryColor,
                          value: false,
                          title: const Text('否'),
                          groupValue: radioval2,
                          onChanged: (val) {
                            setState(() {
                              radioval2 = val;
                            });
                          }),
                    ),
                    Expanded(
                      flex: 2,
                      child: Container(),
                    )
                  ],
                ),
              ),
              //拍照数量
              Container(
                height: 30.0,
                margin: const EdgeInsets.only(left: 10.0, top: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: const <Widget>[
                    Text(
                      '拍照数量',
                      style: TextStyle(fontSize: 15.0),
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.only(bottom: 20.0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                        flex: 5,
                        child: Container(
                            color: Colors.grey[200],
                            margin: const EdgeInsets.all(10.0),
                            child: TextField(
                              controller: _lowcontroller,
                              inputFormatters: <TextInputFormatter>[
                                WhitelistingTextInputFormatter.digitsOnly,
                              ],
                              keyboardType: TextInputType.number,
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                                hintText: '输入',
                                contentPadding: EdgeInsets.all(10.0),
                              ),
                            ))),
                    Expanded(
                        flex: 2,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 30.0),
                          child: Align(
                            alignment: Alignment.center,
                            child: Container(
                              color: Colors.grey[200],
                              width: 50.0,
                              height: 2.0,
                            ),
                          ),
                        )),
                    Expanded(
                        flex: 5,
                        child: Container(
                          margin: const EdgeInsets.all(10.0),
                          color: Colors.grey[200],
                          child: TextField(
                            controller: _highcontroller,
                            inputFormatters: <TextInputFormatter>[
                              WhitelistingTextInputFormatter.digitsOnly,
                            ],
                            keyboardType: TextInputType.number,
                            decoration: const InputDecoration(
                              border: InputBorder.none,
                              hintText: '输入',
                              contentPadding: EdgeInsets.all(10.0),
                            ),
                          ),
                        ))
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      persistentFooterButtons: <Widget>[
        Row(
          children: <Widget>[
            Container(
              width: (MediaQuery.of(context).size.width / 2) - 10,
              height: 50,
              color: const Color.fromRGBO(242, 246, 249, 1),
              child: MaterialButton(
                  onPressed: () {
                    setState(() {
                      _namecontroller.text = '';
                      _statementcontroller.text = '';
                      _completeDate = '';
                      _alertDate = '';
                      _contactName = '';
                      _contactId = -1;
                      radioval = true;
                      radioval2 = true;
                      _lowcontroller.text = '';
                      _highcontroller.text = '';
                    });
                  },
                  child: const Text('重置', style: TextStyle(color: Colors.black, fontSize: 18))),
            ),
            isSavedPressed
                ? Container(
                    width: (MediaQuery.of(context).size.width / 2) - 10,
                    height: 50,
                    color: Theme.of(context).primaryColor,
                    child: MaterialButton(
                      onPressed: () {},
                      child: const Text('确定', style: TextStyle(color: Colors.white, fontSize: 18)),
                    ),
                  )
                : Container(
                    width: (MediaQuery.of(context).size.width / 2) - 10,
                    color: Theme.of(context).primaryColor,
                    child: MaterialButton(
                      onPressed: () {
                        if (items.isNotEmpty) {
                          if (items.where((f) => f.selected).isEmpty) {
                            MsgBox.showMessageOnly('任务名称、完成时间、不合格检查项必须输入、执行人员，请确认后重新提交！', context);
                            return;
                          }
                        }
                        if (_namecontroller.text.isEmpty ||
                            _completeDate == null ||
                            _completeDate.isEmpty ||
                            _contactId <= 0) {
                          MsgBox.showMessageOnly('任务名称、完成时间、执行人员必须输入，请确认后重新提交！', context);
                          return;
                        } else {
                          TaskConfig config = TaskConfig.fromParams(
                              start: num.tryParse(_lowcontroller.text),
                              end: num.tryParse(_highcontroller.text),
                              isMust: radioval2 ? '是' : '否',
                              name: '');
                          List<TaskConfig> lstConfig = [];
                          lstConfig.add(config);
                          TaskInfoForAdd _taskInfoForAdd = TaskInfoForAdd();
                          _taskInfoForAdd.config = lstConfig;
                          _taskInfoForAdd.title = _namecontroller.text;
                          _taskInfoForAdd.finishTime = _completeDateM;
                          _taskInfoForAdd.remark = _statementcontroller.text;
                          _taskInfoForAdd.executor = _contactName;
                          _taskInfoForAdd.executorId = _contactId;
                          _taskInfoForAdd.maxDepth = num.tryParse(_timescontroller.text);
                          _taskInfoForAdd.isWarn = radioval ? '是' : '否';
                          _taskInfoForAdd.warnTime = _alertDateM;
                          _taskInfoForAdd.checkId = widget.checkId ?? 0;
                          _taskInfoForAdd.depId = _deptId;
                          // 添加
                          List<TaskDetailForAdd> details = [];
                          if (items.isNotEmpty) {
                            items.forEach((f) {
                              if (f.selected) {
                                details.add(TaskDetailForAdd.fromParams(
                                    checkId: widget.checkId, pointId: f.pointId, routeId: f.routeId, itemId: f.itemId));
                              }
                            });
                          }
                          addTask(_taskInfoForAdd, details);
                        }
                      },
                      child: const Text('确定', style: TextStyle(color: Colors.white, fontSize: 18)),
                    ),
                  )
          ],
        )
      ],
    );
  }

  Future<void> addTask(TaskInfoForAdd _taskInfoForAdd, List<TaskDetailForAdd> details) async {
    setState(() {
      isSavedPressed = true;
      isAnimating = true;
    });
    await taskAddNew(_taskInfoForAdd, details).then((data) {
      setState(() {
        isAnimating = false;
        isSavedPressed = false;
      });
      if (data['result'] == 'FAILURE') {
        MsgBox.showMessageOnly(data['message'], context);
      } else {
        if (data['success'] == 'false') {
          MsgBox.showMessageOnly(data['message'], context);
        } else {
          MsgBox.showMessageAndExitCurrentPage('任务添加完成！', true, context);
        }
      }
    });
  }

  Future<void> getQueryUnqualifiedInputItem(num checkId) async {
    await queryUnqualifiedInputItem(checkId).then((data) {
      setState(() {
        items = data;
        for (final _items in items) {
          if (widget.selectedItemId != null && widget.selectedItemId.isNotEmpty) {
            if (widget.selectedItemId.where((f) => f == _items.itemId).isNotEmpty) {
              _items.selected = true;
            }
          }
        }
      });
    });
  }
}
