import 'package:amos_flutter_ui/amos_flutter_ui.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';
import 'package:amos_iot_login_tpl/const/global_config.dart';
import 'package:base/view/ImageViewPage.dart';

///@Description     任务反馈
///@author          helinlin
///@create          2021-10-20 14:18
class TaskFeedBack extends StatefulWidget {
  static const String executing = 'executing'; //执行中
  static const String finished = 'finished'; //已完成

  const TaskFeedBack({Key key, this.bindingCarId, this.alertCallId, this.status}) : super(key: key);
  final String bindingCarId; //绑定的车辆ID
  final String alertCallId; //加入的灾情ID
  final String status; //灾情状态
  @override
  _TaskFeedBackState createState() => _TaskFeedBackState();
}

class _TaskFeedBackState extends State<TaskFeedBack> {
  final TextEditingController _controller = TextEditingController();
  String status;
  List<ChooseFileInfo> files = [];
  List formList =[];
  String imageUrl = '';
  bool isSubmit = true ;

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    // status = widget.status ?? TaskFeedBack.executing;
    getHistoryFeedBack();
    status =  TaskFeedBack.executing;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('任务反馈'),
        actions: isSubmit ? [
          IconButton(
              icon: const Icon(
                Icons.check,
                color: Colors.white,
              ),
              onPressed: _submit)
        ]:[],
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child:  GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: SingleChildScrollView(
            child:Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                isShow(),
                formList.isNotEmpty ? recordBody() : const Text('')
              ],
            ),
          )

        ),
      ),
    );
  }

  //判断是否显示提交表单
  Widget isShow(){
    return isSubmit?  Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('任务状态反馈'),
        Row(
          children: [
            Radio(
                value: TaskFeedBack.executing,
                groupValue: status,
                onChanged: (value) {
                  setState(() {
                    status = value;
                  });
                }),
            const Text('执行中'),
            Radio(
                value: TaskFeedBack.finished,
                groupValue: status,
                onChanged: (value) {
                  setState(() {
                    status = value;
                  });
                }),
            const Text('已完成'),
          ],
        ),
        const Text('任务执行反馈'),
        const SizedBox(
          height: 5,
        ),
        TextField(
          controller: _controller,
          maxLines: 3,
          maxLength:50,
          decoration: const InputDecoration(
              border: InputBorder.none, filled: true, fillColor: Color.fromARGB(255, 240, 245, 240)),
        ),
        const Text('现场图片'),
        const SizedBox(
          height: 5,
        ),
        ImagePickerAndRemove(
          files,
          hasVideo: false,
          isPhotoLlbum:false
        ),
        const SizedBox(
          height: 5,
        ),
      ] ,
    ):const SizedBox();
  }

  Widget recordBody(){
    List<Widget> tiles = [];
    Widget content;
    for(var item in formList) {
      tiles.add(
          Container(
              width: MediaQuery.of(context).size.width - 20,
              height: 150,
              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(
                          crossAxisAlignment:CrossAxisAlignment.start,
                          children: <Widget>[
                            const Text('反馈内容：',style: TextStyle(fontSize:10)),
                            Container(
                              child:Expanded(child:
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [item['info'] != null ?

                                Text("${item['info']}",
                                    textAlign: TextAlign.left,
                                    style:const TextStyle(fontSize:10))
                                    :
                                const Text('无',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(fontSize:10))
                                ],
                              )),
                            )
                          ]
                      ),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Container(
                      child:Row(
                        crossAxisAlignment:CrossAxisAlignment.start,
                        children: [
                          const Text('现场照片：',style: TextStyle(fontSize:10)),
                          Container(
                            child: GestureDetector(
                                child: Wrap(
                                    direction: Axis.horizontal,
                                    spacing: 10.0, // 主轴(水平)方向间距
                                    alignment: WrapAlignment.end, //沿主轴方向居中
                                    children: item['photos'] != null
                                        ? item['photos'].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(f))),
                                          ),
                                        ],
                                      );
                                    }).toList() : [Text('无',style: TextStyle(fontSize:10))]),
                                onTap: () {
                                  if (item['photos'] != null && item['photos'].isNotEmpty) {
                                    Navigator.push(context, MaterialPageRoute(builder: (context) {
                                      return PhotoViewPage(item['photos']);
                                    }));
                                  }
                                }),
                          ),
                        ],

                      ),

                    ),

                  ]

              )
          )
      );
    }
    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;
  }

  ///回显历史反馈记录
  void getHistoryFeedBack() {
    Future.delayed(Duration.zero, () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后。。。');
      API.getTaskFeedback(widget.bindingCarId, widget.alertCallId).then((value) {
        Get.back();
        if (value != null) {
          if(value[0]['info'].contains('已完成')){
            isSubmit = false;
          }
          var list = value.map((v){
            if(v['photos'] != null) {
              v['photos'] = v['photos'][0].toString().split(',').toList().map((
                  e) => imageUrl + e).toList();
            }
            //去掉返回给web端的状态
            v['info'] = v['info'].toString().replaceAll('<span style="color: #fe0c0c " >','');
            v['info'] = v['info'].toString().replaceAll('</span>','');
            return v;
          }).toList();
          setState(() {
            formList = list;
          });
        }
      });
    });
  }

  ///提交反馈记录
  void _submit() {
    MsgBox.showProgressDialog(context);
    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) {
        attachment = attachment.map((item) =>item['filePath']).toList();
        API.setCurrentCarOrTaskState(widget.bindingCarId ?? '', widget.alertCallId, status ?? '', '2' ,attachment: attachment , remarks: _controller.text)
            .then((value) {
          ToastUtils.showToast('反馈成功！');
          Get.back();
        }).whenComplete(() => Get.back());
      }
      ToastUtils.showToast('响应异常，提交失败！！');
    }).catchError((e) {
      ToastUtils.showToast('文件上传失败！！');
    });


  }
}

