import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/viewmodel/monitor_event.dart';
import 'package:jcs_airport/viewmodel/confirm_alam.dart';

const _items = [
  {'value': 'FIREALARM', 'label': '火警'},
  {'value': 'BREAKDOWN', 'label': '故障'},
  {'value': 'wrong', 'label': '误报'},
  {'value': 'SHIELD', 'label': '屏蔽'},
  {'value': 'NOTICE', 'label': '预警'},
  {'value': 'warning', 'label': '告警'}
];

/// 在岗监测详情页面
class MonitorEventDetail extends StatefulWidget {
  const MonitorEventDetail({Key key}) : super(key: key);

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

class _MonitorEventDetailState extends State<MonitorEventDetail> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  MonitorEvent monitorEvent = MonitorEvent();

  bool isAnimating = false;
  bool shouldEdit = false;
  bool shouldSubmit = false;

  @override
  void initState() {
    super.initState();
    getMe();
    monitorEvent = Get.arguments;
    shouldSubmit = monitorEvent.eventState != '已处理' ? true : false;
  }

  @override
  Widget build(BuildContext context) {
    print('${Get.arguments}');
    String buttonName = getButtonText();
    return Scaffold(
        appBar: AppBar(
          title: const Text('事件详情'),
        ),
        body: SingleChildScrollView(
            child: Card(
                child: Container(
                    padding: const EdgeInsets.all(10),
                    child: Column(children: [
                      _buildAlarmInfoItem(),
                      Row(children: [
                        Expanded(
                            child: FlatButton(
                                color: Colors.blueAccent,
                                height: 40,
                                onPressed: () {
                                  MsgBox.showConfirmDialog(
                                      context, confirmAlam,
                                      content: '是否${buttonName}');
                                },
                                child: Text(buttonName,
                                    style:
                                        const TextStyle(color: Colors.white))))
                      ])
                    ])))));
  }

  String getButtonText() {
    if (shouldEdit && !shouldSubmit) {
      return '修改';
    }
    return '提交';
  }

  Future<void> confirmAlam() async {
    if (!shouldSubmit) {
      this.setState(() {
        shouldSubmit = true;
      });
      return;
    }
    API.confirmMonitorEvent(monitorEvent).then((result) {
      if (result != null) {
        Get.back();
        return;
      } else {
        ToastUtils.showToast('响应异常，提交失败！！');
      }
    });
  }

  /// 构建警情详情
  Container _buildAlarmInfoItem() {
    List<Widget> widgetList = [];
    widgetList.addAll(_buildAlarmInfo());
    widgetList.addAll(_buildProcessInfo());

    return Container(
      padding: const EdgeInsets.only(right: 00, bottom: 20),
      child: Column(
        children: widgetList,
      ),
    );
  }

  /// 构建警情信息
  List<Widget> _buildAlarmInfo() {
    String firm = getIsFirm();
    Color firmColor = getIsFirmColor();
    List<Widget> widgetList = [];
    widgetList.addAll([
      Container(
        child: Row(
          children: [
            Expanded(
              flex: 5,
              child: Column(
                children: [
                  _buildTitle('警情信息'),
                  _buildRowInfo('事件类型：', monitorEvent.eventType),
                  _buildRowInfo('报警设备：', monitorEvent.videoName)
                ],
              ),
            ),
            Expanded(
                flex: 2,
                child: Column(children: [
                  ClipRRect(
                      //剪裁为圆角矩形
                      borderRadius: BorderRadius.circular(38.0),
                      child: Container(
                          height: 76,
                          width: 76,
                          decoration: BoxDecoration(color: firmColor),
                          child: Transform.translate(
                              offset: const Offset(15, 25),
                              child: Text(firm,
                                  style: TextStyle(
                                      color: getIsFirmTextColor(),
                                      fontWeight: FontWeight.w600)))))
                ]))
          ],
        ),
      ),
      _buildRow('事件内容：', monitorEvent.eventContent),
      _buildRow('报警时间：', monitorEvent.createDate),
      _buildRow('设备编号：', monitorEvent.videoCode),
      _buildRow('设备位置：', monitorEvent.videoPosition)
    ]);
    return widgetList;
  }

  /// 构建处理信息
  List<Widget> _buildProcessInfo() {
    bool edit = (monitorEvent.eventState != '已处理' ? true : false);
    if (shouldSubmit) {
      edit = true;
    }
    List<Widget> widgetList = [];
    widgetList.add(_buildTitle('处理信息'));
    if (edit) {
      /// 编辑/新增处理警情
      widgetList.add(
        AmosForm(
            formKey: formKey,
            children: _buildFormModel(context),
            onChanged: (value) => onChangeForm(value)),
      );
    } else {
      widgetList.add(_build2Row('处理情况：', monitorEvent.disposalRecord));
      widgetList.add(_buildRow('处理人员：', monitorEvent.disposalUserName));
      widgetList.add(_buildRow('处理时间：', monitorEvent.disposalDate));
    }

    return widgetList;
  }

  Future<void> onChangeForm(value) {
    monitorEvent.disposalRecord = value['disposalRecord'];
  }

  String getIsFirm() {
    String firm = monitorEvent.eventState == '已处理' ? '已处理' : '待处理';
    return firm;
  }

  Color getIsFirmColor() {
    Color firm =
    monitorEvent.eventState == '已处理' ? Color(0xffcccccc) : Color(0xffff9900);
    return firm;
  }

  Color getIsFirmTextColor() {
    Color firm = monitorEvent.eventState == '已处理' ? Colors.black : Colors.white;
    return firm;
  }

  /// 构建编辑/新增处理警情表单
  List<FormItem> _buildFormModel(context) {
    List<FormItem> formItems = [];

    formItems.addAll([
      FormItem(
          layout: FormLayout.vertical,
          label: '处理情况',
          labelWidth: 80,
          invert: true,
          formfield: AmosTextField(
              fieldKey: 'disposalRecord', maxLines: 5, hint: '请输入处理情况'))
    ]);

    return formItems;
  }

  /// 构建单行显示信息
  Widget _buildRow(String title, String content) {
    return Container(
      padding: const EdgeInsets.only(bottom: 5, left: 16),
      child: Row(
        children: [
          Expanded(
              flex: 2,
              child: Text(
                title ?? '',
              )),
          Expanded(
              flex: 7,
              child: Text(
                content ?? '',
              )),
        ],
      ),
    );
  }

  /// 构建换行显示信息
  Widget _build2Row(String title, String content) {
    return Container(
      child: Row(
        children: [
          Expanded(
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.only(bottom: 5, left: 16),
                  child: Row(
                    children: [
                      Expanded(child: Text(title ?? '')),
                    ],
                  ),
                ),
                Container(
                    padding: const EdgeInsets.only(bottom: 5, left: 16),
                    child: Transform.translate(
                        offset: const Offset(20, 0),
                        child: Row(
                          children: [
                            Expanded(child: Text(content ?? '')),
                          ],
                        )))
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 构建警情信息 待处理右侧组件
  Widget _buildRowInfo(String title, String content) {
    return Container(
      padding: const EdgeInsets.only(bottom: 5, left: 16),
      child: Row(
        children: [
          Expanded(flex: 3, child: Text(title ?? '')),
          Expanded(
              flex: 5,
              child: Transform.translate(
                  offset: const Offset(-10, 0), child: Text(content ?? ''))),
        ],
      ),
    );
  }

  /// 构建分组标题
  Widget _buildTitle(String title) {
    return Container(
      padding: const EdgeInsets.only(bottom: 10, left: 16),
      child: Row(
        children: [
          Expanded(
              flex: 2,
              child: Text(title ?? '',
                  style: TextStyle(fontSize: 22, fontWeight: FontWeight.w800))),
        ],
      ),
    );
  }

  Future<void> getMe() {
    API.agencyuserMe().then((userInfo) {
      userInfo['orgRoles'].forEach((key, value) {
        for (var item in value) {
          if (item['roleType'] == 'admin') {
            setState(() {
              shouldEdit = true;
            });
          }
        }
      });
      print(userInfo);
    });
  }
}
