import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide FormData, MultipartFile;
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/choose_department_jcs_tree.dart';
import 'package:jcs_airport/view/common/choose_person_malfunction_report.dart';
import 'package:jcs_airport/view/common/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:jcs_airport/consts/file_type.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
class MalfunctionReport extends StatefulWidget {
  ///修改的主键ID
  final String sequenceNbr;
  final bool isUpdate;

  const MalfunctionReport({this.sequenceNbr, this.isUpdate});

  @override
  State<StatefulWidget> createState() => MalfunctionReportState();
}

class MalfunctionReportState extends State<MalfunctionReport> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  ///提交数据
  Map<String, Object> submitData = {
    'faultTime': DateUtils.formatDate(DateTime.now(), format: 'yyyy-MM-dd'),
  };
  Map chooseDepartment = {};
  Map choosePerson = {};

  ///照片/视频
  List<ChooseFileInfo> files = [];

  /// 图片服务器前缀
  String imagePrefix = '';

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imagePrefix = value;
      });
    });
    if (widget.sequenceNbr != null) {
      _getData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(''),
        ),
        body: GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
            setState(() {});
          },
          child: SingleChildScrollView(
            child: Column(
              children: [
                Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      FormItem(
                        layout: FormLayout.horizontal,
                        label: '故障设备:',
                        formfield: ITextFormField(
                            value: submitData['failureEquipment'] ?? '',
                            textStyle: CoreStyles.smallText,
                            validator: ValidatorMulti([
                              ValidatorMaxLength(20, errorText: '最多输入20个字')
                            ]),
                            hintText: '例：火灾自动报警系统',
                            onChanged: (val) {
                              setState(() {
                                submitData['failureEquipment'] = val;
                              });
                            }),
                      ),
                      FormItem(
                          layout: FormLayout.horizontal,
                          label: '故障时间',
                          formfield: InputDatePicker(
                            onChange: (val) {
                              setState(() {
                                submitData['faultTime'] = DateUtils.formatDate(
                                    val,
                                    format: 'yyyy-MM-dd');
                              });
                            },
                            value: submitData['faultTime'] ?? '',
                          )),
                      FormItem(
                        layout: FormLayout.horizontal,
                        label: '故障现象:',
                        formfield: ITextFormField(
                            value: submitData['faultPhenomenon'] ?? '',
                            maxLines: 4,
                            textStyle: CoreStyles.smallText,
                            validator: ValidatorMulti([
                              ValidatorMaxLength(300, errorText: '最多输入300个字')
                            ]),
                            hintText: '请输入故障现象',
                            onChanged: (val) {
                              setState(() {
                                submitData['faultPhenomenon'] = val;
                              });
                            }),
                      ),
                      Container(
                        padding:
                            const EdgeInsets.only(left: 15, right: 15, top: 5),
                        child: Row(
                          children: [
                            const Expanded(child: Text('现场图片/视频:')),
                            const SizedBox(
                              width: 10,
                            ),
                            Expanded(
                              flex: 4,
                              child: ImagePickerAndRemove(
                                files,
                                hasVideo: true,
                              ),
                            )
                          ],
                        ),
                      ),
                      FormItem(
                          layout: FormLayout.horizontal,
                          label: '送达部门:',
                          formfield: SelectFormNewPage(
                              value: chooseDepartment['name'] ?? '',
                              selectPage: ChooseDepartmentJcsTree(
                                  chooseDepartment: chooseDepartment),
                              onChanged: (val) {
                                if (val != null) {
                                  setState(() {
                                    chooseDepartment = val;
                                  });
                                }
                              })),
                      FormItem(
                          layout: FormLayout.horizontal,
                          label: '报  送  人:',
                          formfield: SelectFormNewPage(
                              value: choosePerson['bizOrgName'] ?? '',
                              selectPage: ChoosePersonMalfunctionReport(
                                  person: choosePerson),
                              onChanged: (val) {
                                if (val != null) {
                                  setState(() {
                                    choosePerson = val;
                                  });
                                }
                              })),
                      const SizedBox(
                        height: 10,
                      ),
                      Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: Row(
                          children: [
                            Expanded(
                                child: FlatButton(
                              color: Theme.of(context).primaryColor,
                              height: 40,
                              onPressed: () {
                                onSubmit(context);
                              },
                              child: const Text(
                                '确定',
                                style: TextStyle(color: Colors.white),
                              ),
                            )),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  void onSubmit(BuildContext context) {
    if (_formKey.currentState.validate()) {
      //校验(不使用表单自带校验原因：表单输入项与选人/选部门判空提示无法保持一致)
      if (submitData['failureEquipment'] == null ||
          submitData['failureEquipment'].toString().trim().isEmpty) {
        ToastUtils.showToast('请输入故障设备！');
        return;
      }
      if (submitData['faultTime'] == null ||
          submitData['faultTime'].toString().trim().isEmpty) {
        ToastUtils.showToast('请输入故障时间！');
        return;
      }
      if (submitData['faultPhenomenon'] == null ||
          submitData['faultPhenomenon'].toString().trim().isEmpty) {
        ToastUtils.showToast('请输入故障现象！');
        return;
      }
      if (chooseDepartment.isEmpty) {
        ToastUtils.showToast('请选择送达部门！');
        return;
      } else {
        submitData['submissionBranch'] = chooseDepartment['name'];
        submitData['submissionBranchId'] = chooseDepartment['value'];
      }
      if (choosePerson.isEmpty) {
        ToastUtils.showToast('请选择报送人！');
        return;
      } else {
        submitData['submissionName'] = choosePerson['bizOrgName'];
        submitData['submissionPid'] = choosePerson['amosOrgId'];
      }
      MsgBox.showConfirmDialog(context, submit);
    }
  }

  Future<void> submit() async {


    MsgBox.showProgressDialog(context);
    var attachment = [];
    List<Future<dynamic>> futureTask = [];
    files.forEach((element) {
      if (element.file != null) {
        futureTask.add(API.uploadFile(element, attachment));
      }else if (element.url != null) {
        attachment.add({
          'fileCategory': element.isPhoto ? FileType.IMAGE : FileType.VIDEO,
          'fileName': element.fileName,
          'filePath': element.fileUrl,
        });
      }
    });

    Future.wait(futureTask).then((value) async {

      if (attachment.length == files.length) {
        submitData['attachment'] = attachment;
        var result = await API.failureDetailsSave(submitData);
        if (result != null && result == true) {
          ToastUtils.showToast('提交成功！');

          if (widget.sequenceNbr != null) {
            Get.close(2);
          }else{
            Get.back();
          }


          //Get.offNamedUntil('/index', ModalRoute.withName('/index'));

        }
      }else{
        ToastUtils.showToast('响应异常，提交失败！');
      }

    }).catchError((e) {
      ToastUtils.showToast('文件上传失败！');
    }).whenComplete(() =>
        Get.back()
    );
  }

  Future<void> _getData() async {
    var baseInfoData = await API.failureDetails(widget.sequenceNbr);
    if (baseInfoData != null) {
      setState(() {
        submitData.addAll(baseInfoData);
        chooseDepartment['name'] = submitData['submissionBranch'];
        chooseDepartment['value'] = submitData['submissionBranchId'];

        List list =
            submitData['attachment'] != null ? submitData['attachment'] : [];
        list.forEach((element) {
          if (element['fileCategory'].toString() == 'image') {
            files.add(ChooseFileInfo(null,
                isPhoto: true,
                fileUrl: element['filePath'].toString(),
                fileName: element['fileName'].toString(),
                url: imagePrefix + element['filePath'].toString()));
          } else {



            VideoPlayerController _controller =
            VideoPlayerController.network(imagePrefix + element['filePath'].toString())..initialize();
            ChewieController _chewieController = ChewieController(
              videoPlayerController: _controller,
              autoPlay: false,
              looping: false,
            );
            files.add(ChooseFileInfo(null,
                isPhoto: false,
                fileUrl: element['filePath'].toString(),
                isVideo: true,
                url: imagePrefix + element['filePath'].toString(),
                fileName: element['fileName'].toString(),
                videoPlayerController: _controller,
                chewieController: _chewieController));



          }
        });

        if (!widget.isUpdate) {
          submitData['sequenceNbr'] = null;
        }
      });
    }
  }

  Future<void> _getUserInfo() async {
    var userInfo = await API.agencyuserMe();
    if (userInfo != null) {
      setState(() {
        choosePerson['bizOrgName'] = userInfo['realName'];
        choosePerson['amosOrgId'] = userInfo['userId'];
      });
    }
  }

  Future<void> getCurrentUser() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    setState(() {
      submitData['submissionName'] = sp.getString(GlobalConst.USER_NAME);
      submitData['submissionPid'] = sp.getString(GlobalConst.USER_ID);
    });
  }
}
