import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:jcs_airport/view/common/image_picker.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:amos_iot_login_tpl/const/global_config.dart';
import 'package:base/view/ImageViewPage.dart';
/// 任务反馈
///
class TaskFeedback extends StatefulWidget {
  const TaskFeedback({Key key, this.taskStatus, this.alarmId}) : super(key: key);

  final String taskStatus;
  final String alarmId;

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

class _TaskFeedbackState extends State<TaskFeedback> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Map<String, dynamic> formData = {};
  List<ChooseFileInfo> files = [];
  List formList =[];
  String imageUrl = '';

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    getInit();
  }

  List<Widget> buildBody(BuildContext context) {
    return [
      FormItem(
          label: '任务状态反馈',
          formfield: AmosRadioGroup(
            initialValue: widget.taskStatus,
            fieldKey: 'status',
            // layout: RadioGroupLayout.horizontal,
            options: const [
              {'title': '执行中', 'value': 'running'},
              {'title': '已完成', 'value': 'done'}
            ],
          )),
      FormItem(
        layout: FormLayout.vertical,
        label: '备注',
        labelWidth: 50,
        invert: true,
        formfield: AmosTextField(
          fieldKey: 'remark',
          maxLength:50,
          maxLines: 5,
          hint: '请输入备注信息',

        ),
      ),
      FormItem(
        layout: FormLayout.vertical,
        label: '现场图片',
        labelWidth: 50,
        invert: true,
        formfield: Container(
            alignment: Alignment.centerLeft,
            child: ImagePickerAndRemove(
              files,
              hasVideo: false, maxLength:4
            )),
      )
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('任务反馈'),
          centerTitle: true,
          elevation: 0.2,
          actions: <Widget>[
            FlatButton.icon(
              icon: const Icon(
                Icons.check,
                color: Colors.white,
              ),
              label: const Text(
                '确定',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                // Navigator.pop(context);
                submit();
              },
            )
          ],
        ),
        body: SingleChildScrollView(
          child: Column(
              children:<Widget>[
                AmosForm(
                formKey: _formKey,
                children: buildBody(context),
                onChanged: (value) {
                  formData['remark'] = value['remark'];
                  formData['status'] = value['status'];
                }),
                formList.isNotEmpty ? recordBody() : const Text('')
              // Expanded(child: recordBody()),
            ],
          ),
        ));
  }

  Widget recordBody(){
    List<Widget> tiles = [];
    Widget content;
    for(var item in formList) {
      tiles.add(
          Container(
            width: MediaQuery.of(context).size.width - 20,
            height: 120,
            margin: const EdgeInsets.only(top:10.0),
            padding: const EdgeInsets.all(10),
            decoration:  BoxDecoration(
              color: Colors.black12,
              border: Border.all(color: Colors.black26, width: 1),
              borderRadius:  BorderRadius.all(Radius.circular(8)),
            ),
              child:  Column(
                  children:<Widget>[
                    Container(
                      child:Row(
                        children:  <Widget>[
                            Text('反馈时间：'+ item['recDate'],style: const TextStyle(fontSize:10)),
                             const Expanded(
                            child: Text(''), // 中间用Expanded控件
                            ),
                           Text('反馈人：' + item['recUserName'],style:const TextStyle(fontSize:10) ),
                        ],
                      ),
                    ),
                    Container(
                      child:Row(
                        children: <Widget>[
                          const Text('反馈内容：',style: TextStyle(fontSize:10)),
                          Container(
                            child:Expanded(child:
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [item['remark'] != null ?
                              Text("${item['remark']}",
                                  textAlign: TextAlign.left,
                                  style:const TextStyle(fontSize:10))
                                  :
                              const Text('无',
                                  textAlign: TextAlign.left,
                                  style: TextStyle(fontSize:10))
                              ],
                              )),
                          )
                        ]
                      ),
                    ),
                    Container(
                      child:Row(
                        children: [
                          const Text('现场照片：',style: TextStyle(fontSize:10)),
                          Container(
                            margin: const EdgeInsets.only(top:10.0),
                            child: GestureDetector(
                                child: Wrap(
                                direction: Axis.horizontal,
                                spacing: 10.0, // 主轴(水平)方向间距
                                alignment: WrapAlignment.end, //沿主轴方向居中
                                children: item['photoUrls'] != null
                                    ? item['photoUrls'].map<Widget>((f) {
                                  return Column(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: <Widget>[
                                      Container(
                                        width: 40,
                                        height: 40,
                                        //  margin: EdgeInsets.only(right: 5),
                                        decoration: BoxDecoration(
                                            color: Colors.transparent,
                                            // borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                                            image: DecorationImage(image: NetworkImage(imageUrl + f))),
                                      ),
                                    ],
                                  );
                                }).toList() : []),
                                onTap: () {
                                  // if (item['photoUrls'] != null && item['photoUrls'].isNotEmpty) {
                                  //   Navigator.push(context, MaterialPageRoute(builder: (context) {
                                  //     var imgList = item['photoUrls'].map((item)=> imageUrl + item['photoUrls']).toList();
                                  //     return PhotoViewPage(imgList);
                                  //   }));
                                  // }
                                }),
                          ),
                        ],

                      ),

                    ),

                  ]

              )
          )
      );
    }
    content = Container(
      width: MediaQuery.of(context).size.width,
        padding: const EdgeInsets.all(15),
        child:Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children:<Widget>[
          const Text('任务反馈记录',
          textAlign: TextAlign.left,
          style: TextStyle(fontSize:15,color:Colors.black),
          ),
          Column( children: tiles)
      ])
    );

    return content;
  }

  Widget imgList(photoUrls){
    List<Widget> tiles = [];
    Widget content;
    for(var item in photoUrls) {
      tiles.add(
          Image.network(
            item,
            width: 50,
          )
      );
    }
    return content;
  }
  // 查询警情记录反馈
  Future<void> getInit() async {
    var result = await API.alarmlistByAlertId(widget.alarmId);
    if (result != null) {
      setState(() {
        formList = result;
      });
    }
  }

  Future<void> submit() async {
    // MsgBox.showProgressDialog(context, content: '提交中...');
    List attachment = [];
    List<Future<dynamic>> imgActions = [];
    files.forEach((element) {
      imgActions.add(API.uploadFile(element, attachment));
    });

    Future.wait(imgActions).then((value) async {
      if (attachment.length == files.length) {
        formData['photoUrls'] = attachment.map((item) =>item['filePath']).toList();
        // formData['attachments'] = attachment;
        formData['alertCalledId'] = widget.alarmId;
        var result = await API.alarmTaskFeedback(formData);
        if (result != null) {
          // MsgBox.showProgressDialog(context);
          ToastUtils.showToast('提交成功！');
          Navigator.pop(context);
          return;
        }
      }
      ToastUtils.showToast('响应异常，提交失败！！');
    }).catchError((e) {
      ToastUtils.showToast('文件上传失败！！');
    });
  }
}
