import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/image_picker.dart';

class AddRepair extends StatefulWidget {
  final String sequenceNbr;

  const AddRepair(this.sequenceNbr, {Key key}) : super(key: key);

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

class _AddRepairState extends State<AddRepair> {
  ///照片/视频
  List<ChooseFileInfo> files = [];

  ///提交数据
  Map<String, Object> submitData = {};
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('故障设备维修记录'),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          setState(() {});
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Form(
                    key: _formKey,
                    child: FormItem(
                      label: '维修内容描述:',
                      formfield: ITextFormField(
                          value: submitData['maintainContent'] ?? '',
                          maxLines: 4,
                          validator: ValidatorMulti([ValidatorRequired(errorText: '请输入维修内容描述')]),
                          hintText: '请输入维修内容描述',
                          onChanged: (val) {
                            submitData['maintainContent'] = val;
                          }),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Row(
                      children: const [Text('维修照片/视频:')],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    child: ImagePickerAndRemove(files),
                  ),
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.all(15),
              child: Row(
                children: [
                  Expanded(
                      child: FlatButton(
                    color: const Color.fromRGBO(200, 200, 200, 1),
                    height: 40,
                    onPressed: () {
                      onSubmit(context, 0);
                    },
                    child: const Text(
                      '维修完成',
                      style: TextStyle(color: Colors.white),
                    ),
                  )),
                  const SizedBox(
                    width: 5,
                  ),
                  Expanded(
                      child: FlatButton(
                    color: Colors.blueAccent,
                    height: 40,
                    onPressed: () {
                      onSubmit(context, 1);
                    },
                    child: const Text(
                      '保存',
                      style: TextStyle(color: Colors.white),
                    ),
                  )),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void onSubmit(BuildContext context, int type) {
    if (_formKey.currentState.validate()) {
      MsgBox.showConfirmDialog(context, () => submit(type));
    }
  }

  void submit(int type) {
    MsgBox.showProgressDialog(context);
    var attachment = [];
    List<Future<dynamic>> futureTask = [];
    files.forEach((element) {
      futureTask.add(API.uploadFile(element, attachment));
    });
    Future.wait(futureTask).then((value) async {
      if (attachment.length == files.length) {
        if (type == 0) {
          submitData['condition'] = 1;
          submitData['attachment'] = attachment;
          submitData['faultId'] = widget.sequenceNbr;
          var result = await API.failureMaintainSave(submitData);
          if (result != null && result == true) {
            submitData['condition'] = type;
            submitData['attachment'] = [];
            submitData['faultId'] = widget.sequenceNbr;
            var result = await API.failureMaintainSave(submitData);
            Get.back();
            if (result != null && result == true) {
              Get.back();
            } else {
              ToastUtils.showToast('相应异常，提交失败');
            }
          } else {
            ToastUtils.showToast('相应异常，提交失败');
          }
        } else {
          submitData['condition'] = type;
          submitData['attachment'] = attachment;
          submitData['faultId'] = widget.sequenceNbr;
          var result = await API.failureMaintainSave(submitData);
          Get.back();
          if (result != null && result == true) {
            Get.back();
          } else {
            ToastUtils.showToast('相应异常，提交失败');
          }
        }
      } else {
        Get.back();
        ToastUtils.showToast('文件上传失败！！');
      }
    }).catchError((e) {
      Get.back();
      ToastUtils.showToast('文件上传失败！！');
    });
  }
}
