import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_ui/form/form_item.dart';
import 'package:amos_flutter_ui/form/select_form.dart';
import 'package:amos_flutter_ui/form/select_form_newpage.dart';
import 'package:amos_flutter_ui/form/validat.dart';
import 'package:amos_flutter_ui/message/message_box.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/image_picker.dart';
import 'package:jcs_airport/view/workBench/fireproofSupervision/common/choose_fireproof_building.dart';
import 'package:permission_handler/permission_handler.dart';

import 'choose_location.dart';

///@Description     计划检查添加隐患
///@author          helinlin
///@create          2021-09-02 11:52
class AddHiddenDanger extends StatefulWidget {
  final DangerDto danger;
  final bool canAdd;

  const AddHiddenDanger({this.danger, this.canAdd = true});

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

class _AddHiddenDangerState extends State<AddHiddenDanger> {
  final AMapFlutterLocation aMapFlutterLocation = AMapFlutterLocation();
  final List<Map<String, dynamic>> _level = [];
  final List<Map<String, dynamic>> _ways = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _locationController = TextEditingController();
  String address = '';

  @override
  void initState() {
    super.initState();
    _locationController.text = widget.danger.dangerPosition ?? '';
    Future.delayed(Duration.zero, () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      Future.wait([getLevel(), getWays()]).whenComplete(() => Get.back());
    });
    getLocation();
  }

  /// 高德定位
  Future<void> getLocation() async {
    if (await Permission.location.request().isGranted) {
      AMapLocationOption aMapLocationOption = AMapLocationOption();
      aMapFlutterLocation.setLocationOption(aMapLocationOption);
      aMapFlutterLocation.onLocationChanged().listen((Map<String, Object> result) {
        if (result != null) {
          /* Logger.warn('已定位:${result['address']}');
          FlutterToast.toastBottom('已定位:${result['address']}');*/
          double latitude = result['latitude'];
          double longitude = result['longitude'];
          // setState(() {
            widget.danger.latitude = latitude;
            widget.danger.longitude = longitude;
          // });
          aMapFlutterLocation.stopLocation();
        }
      });
      aMapFlutterLocation.startLocation();
    }
  }

  @override
  void dispose() {
    aMapFlutterLocation.destroy();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: widget.canAdd ? const Text('隐患添加') : const Text('查看隐患'),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          setState(() {});
        },
        child: Column(
          children: [
            Expanded(
              child: Card(
                child: Form(
                  key: _formKey,
                  child: SingleChildScrollView(
                    child: IgnorePointer(
                      ignoring: false,
                      child: Column(
                        children: [
                          FormItem(
                              layout: FormLayout.horizontal,
                              label: '隐患地址:',
                              labelWidth: 60,
                              formfield: SelectFormNewPage(
                                  value: widget.danger.structureName ?? '',
                                  selectPage: ChooseFireproofBuild(
                                      build: {'id': widget.danger.structureId, 'name': widget.danger.structureName}),
                                  onChanged: (val) {
                                    setState(() {
                                      widget.danger.structureId = val == null ? null : val['id'];
                                      widget.danger.structureName = val == null ? null : val['name'];
                                    });
                                  })),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 15),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                const Text('位置描述:'),
                                Expanded(
                                    child: Padding(
                                  padding: const EdgeInsets.only(left: 15),
                                  child: TextField(
                                    controller: _locationController,
                                    maxLines: 3,
                                    style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                    decoration: const InputDecoration(
                                      hintText: '请输入问题位置描述',
                                      hintStyle: TextStyle(fontSize: CoreStyles.textSizeSmall),
                                      border: InputBorder.none,
                                      filled: true,
                                      fillColor: Color.fromARGB(255, 245, 245, 245),
                                    ),
                                    onChanged: (val) => widget.danger.dangerPosition = val,
                                  ),
                                )),
                                const SizedBox(
                                  width: 10,
                                ),
                                Center(
                                  child: GestureDetector(
                                    child: Icon(
                                      Icons.location_on_outlined,
                                      color: (widget.danger.latitude == null || widget.danger.longitude == null)
                                          ? Colors.red
                                          : Colors.green,
                                      size: 28,
                                    ),
                                    onTap: () async {
                                      /*if (address != null && address.isNotEmpty) {
                                            FlutterToast.toastBottom('已定位:$address');
                                          }*/
                                      var result = await Get.to(ChooseLocation(
                                        widget.danger.longitude,
                                        widget.danger.latitude,
                                      ));
                                      if (result != null && result['longitude'] != null && result['latitude'] != null) {
                                        setState(() {
                                          widget.danger.longitude = result['longitude'];
                                          widget.danger.latitude = result['latitude'];
                                          FlutterToast.toastBottom('经度：${widget.danger.longitude},纬度：${widget.danger.latitude}');
                                        });
                                      }
                                    },
                                  ),
                                )
                              ],
                            ),
                          ),
                          FormItem(
                            layout: FormLayout.horizontal,
                            label: '隐患名称',
                            labelWidth: 60,
                            formfield: ITextFormField(
                                value: widget.danger.dangerName ?? '',
                                textStyle: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                validator: ValidatorRequired(errorText: '此项为必填项'),
                                hintText: '请输入隐患名称',
                                onChanged: (val) => widget.danger.dangerName = val),
                          ),
                          FormItem(
                              layout: FormLayout.horizontal,
                              label: '隐患级别',
                              labelWidth: 60,
                              formfield: SelectFormField(
                                  hintText: '请选择',
                                  initialValue: widget.danger.dangerLevel ?? '',
                                  type: SelectFormFieldType.dropdown,
                                  dialogTitle: '请选择',
                                  dialogCancelBtn: '取消',
                                  enableSearch: false,
                                  items: _level,
                                  style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                  validator: ValidatorRequired(errorText: '此项为必填项'),
                                  onChanged: (val, item) {
                                    widget.danger.dangerLevel = val;
                                    widget.danger.dangerLevelName = item['label'];
                                  })),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 18),
                            child: Row(
                              children: [
                                const Text('拍照取证:'),
                                const SizedBox(
                                  width: 15,
                                ),
                                ImagePickerAndRemove(
                                  widget.danger.picture,
                                  readOnly: !widget.canAdd,
                                ),
                              ],
                            ),
                          ),
                          FormItem(
                              layout: FormLayout.horizontal,
                              label: '治理方式',
                              labelWidth: 60,
                              formfield: SelectFormField(
                                  hintText: '请选择',
                                  initialValue: widget.danger.reformType ?? '',
                                  style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                  type: SelectFormFieldType.dropdown,
                                  dialogTitle: '请选择',
                                  dialogCancelBtn: '取消',
                                  enableSearch: false,
                                  items: _ways,
                                  validator: ValidatorRequired(errorText: '此项为必填项'),
                                  onChanged: (val, item) {
                                    widget.danger.reformType = val;
                                    widget.danger.reformTypeName = item['label'];
                                  })),
                          FormItem(
                            layout: FormLayout.horizontal,
                            label: '整改期限',
                            labelWidth: 60,
                            formfield: InputDatePicker(
                              onChange: (val) {
                                setState(() {
                                  widget.danger.reformLimitDate = DateUtils.formatDate(val, format: 'yyyy-MM-dd');
                                });
                              },
                              value: widget.danger.reformLimitDate ?? '',
                            ),
                          ),
                          FormItem(
                            layout: FormLayout.horizontal,
                            label: '备        注',
                            labelWidth: 60,
                            formfield: ITextFormField(
                                value: widget.danger.remark ?? '',
                                textStyle: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                maxLines: 3,
                                hintText: '现场问题备注',
                                onChanged: (val) => widget.danger.remark = val),
                          ),
                          widget.canAdd
                              ? Row(
                                  children: [
                                    Expanded(
                                      child: Padding(
                                        padding: const EdgeInsets.all(15.0),
                                        child: FlatButton(
                                          onPressed: () {
                                            if (_formKey.currentState.validate()) {
                                              Get.back(result: widget.danger);
                                            }
                                          },
                                          child: const Text(
                                            '提交',
                                            style: TextStyle(color: Colors.white),
                                          ),
                                          color: Theme.of(context).primaryColor,
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              : Container()
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Future<void> getLevel() async {
    var data = await API.dangerDangerLevel();
    setState(() {
      if (data != null) {
        data.forEach((element) {
          _level.add({'value': element['dictDataKey'], 'label': element['dictDataValue']});
        });
      }
    });
  }

  Future<void> getWays() async {
    var data = await API.dangerGovernance();
    setState(() {
      if (data != null) {
        data.forEach((element) {
          _ways.add({'value': element['dictDataKey'], 'label': element['dictDataValue']});
        });
      }
    });
  }
}

class DangerDto {
  String id;

  /// 建筑id
  String structureId;

  /// 建筑名称
  String structureName;

  /// 隐患地址
  String dangerPosition;

  /// 隐患名称
  String dangerName;

  /// 隐患级别
  String dangerLevel;

  /// 隐患等级名称
  String dangerLevelName;

  /// 治理方式
  String reformType;

  /// 治理方式名称
  String reformTypeName;

  /// 整改期限
  String reformLimitDate;

  /// 问题描述
  String remark;

  /// 隐患图片上传后地址列表
  List<String> photoUrl = [];

  /// 隐患图片列表
  List<ChooseFileInfo> picture = [];

  /// 经度
  double longitude;

  /// 纬度
  double latitude;

  ///是否删除
  bool deleted = false;

  ///是否审核
  bool unReviewed = true;

  dynamic toJson() {
    dynamic jsonRes = {};
    jsonRes['id'] = id;
    jsonRes['structureId'] = structureId;
    jsonRes['structureName'] = structureName;
    jsonRes['dangerPosition'] = dangerPosition;
    jsonRes['dangerName'] = dangerName;
    jsonRes['dangerLevel'] = dangerLevel;
    jsonRes['dangerLevelName'] = dangerLevelName;
    jsonRes['reformType'] = reformType;
    jsonRes['reformTypeName'] = reformTypeName;
    jsonRes['reformLimitDate'] = reformLimitDate;
    jsonRes['remark'] = remark;
    jsonRes['photoUrl'] = photoUrl;
    jsonRes['longitude'] = longitude;
    jsonRes['latitude'] = latitude;
    jsonRes['deleted'] = deleted;
    return jsonRes;
  }

  DangerDto();

  DangerDto.fromJson(jsonRes) {
    id = jsonRes['id'];
    structureId = jsonRes['structureId'];
    structureName = jsonRes['structureName'];
    dangerPosition = jsonRes['dangerPosition'];
    dangerName = jsonRes['dangerName'];
    dangerLevel = jsonRes['dangerLevel'];
    dangerLevelName = jsonRes['dangerLevelName'];
    reformType = jsonRes['reformType'];
    reformTypeName = jsonRes['reformTypeName'];
    reformLimitDate = jsonRes['reformLimitDate'];
    remark = jsonRes['remark'];
    photoUrl = (jsonRes['photoUrl'] ?? []).cast<String>();
    longitude = double.parse(jsonRes['longitude'] ?? '0');
    latitude = double.parse(jsonRes['latitude'] ?? '0');
    deleted = jsonRes['deleted'];
    unReviewed = jsonRes['unReviewed'];
  }
}
