import 'package:amos_iot_login_tpl/const/global_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter_search_bar/flutter_search_bar.dart';
import 'package:jcs_airport/view/common/base_dropdown_filter.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:get/get.dart';

import '../main_map.dart';
import '../native_bridge.dart';
import './../../../services/api.dart';

/// 当前警情
class CurrentAlarmList extends StatefulWidget {
  ///是否需要开启新地图展示
  final bool needOpenMap;
  final ExecuteJSMethod callJSMethod;

  const CurrentAlarmList({Key key, this.needOpenMap = true, this.callJSMethod}) : super(key: key);

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

class _CurrentAlarmListState extends BaseDropdownFilterState<CurrentAlarmList> {
  List<Map> timeType = [
    {'title': '我的', 'value': '-1'},
    {'title': '即时警情', 'value': '0'},
    {'title': '历史警情', 'value': '1'},
  ];
  List<Map> type = [
    {'title': '全部类型', 'value': ''},
  ];
  List<Map> sort = [
    {'title': '时间倒序', 'value': '1'},
    {'title': '时间正序', 'value': '2'},
  ];
  int timeTypeSelectIndex = 0;
  int typeSelectIndex = 0;
  int sortSelectIndex = 0;

  Map<String, Object> filterData = {'status': '-1', 'orderTime': '1'};
  String imageUrl = '';
  SearchBar _searchBar;

  _CurrentAlarmListState() {
    _searchBar = SearchBar(
        hintText: '请输入地址',
        inBar: false,
        buildDefaultAppBar: (BuildContext context) {
          return AppBar(title: Text(pageTitle()), actions: [_searchBar.getSearchAction(context)]);
        },
        setState: setState,
        closeOnSubmit: false,
        clearOnSubmit: false,
        onSubmitted: (String value) {
          filterData.addIf(value.isNotEmpty, 'address', value);
          onRefresh();
        },
        onCleared: () {
          filterData.remove('address');
          onRefresh();
        },
        onClosed: () {
          filterData.remove('address');
          onRefresh();
        });
  }

  @override
  String pageTitle() => '警情列表';

  @override
  Widget getAppBar() => _searchBar == null
      ? AppBar(
          title: Text(pageTitle()),
        )
      : _searchBar.build(context);

  @override
  void initState() {
    var origin = Get.arguments;
    if (origin is String && origin == 'fromHome') {
      filterData['status'] = '0';
      setState(() {
        timeTypeSelectIndex = 1;
      });
    }
    super.initState();
    setState(() {
      //隐藏过滤按钮
      hasFilter = false;
    });
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    getType();
  }

  @override
  Widget buildListItem(BuildContext context, int index) {
    Map<String, dynamic> item = dataList[index];
    return InkWell(
      onTap: () => _itemClick(item),
      child: CommonCard(
        margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: [
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: Image.asset(
                  _getTypeIcon(item['alarmTypeCode']),
                  width: 37,
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item['alertType'],
                      style: const TextStyle(fontSize: 16),
                    ),
                    const SizedBox(
                      height: 3,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 1),
                      child: Opacity(
                        opacity: 0.6,
                        child: Row(
                          children: [
                            const Text(
                              '',
                              style: TextStyle(fontSize: 13),
                            ),
                            Expanded(
                              child: Text(
                                item['address'] ?? '',
                                style: const TextStyle(fontSize: 13),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 1),
                      child: Opacity(
                        opacity: 0.6,
                        child: Row(
                          children: [
                            const Text(
                              '',
                              style: TextStyle(fontSize: 13),
                            ),
                            Expanded(
                              child: Text(
                                item['callTime'] ?? '',
                                style: const TextStyle(fontSize: 13),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    RichText(
                      text: TextSpan(children: <InlineSpan>[
                        const TextSpan(text: '伤亡: '),
                        TextSpan(
                            text: '${item['casualtiesNum'] ?? '0'}    ',
                            style: const TextStyle(color: Colors.red, fontWeight: FontWeight.bold)),
                        const TextSpan(text: '被困: '),
                        TextSpan(
                            text: '${item['trappedNum'] ?? '0'}    ',
                            style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.bold))
                      ], style: const TextStyle(color: Colors.black87)),
                    ),
                  ],
                ),
              ),
              Container(
                decoration: const BoxDecoration(border: Border(left: BorderSide(color: Colors.black38, width: 0.3))),
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 18),
                  child: Column(
                    children: [
                      Image.asset(
                        'assets/images/location.png',
                        width: 26,
                      ),
                      const SizedBox(
                        height: 2,
                      ),
                      const Opacity(opacity: 0.8, child: Text('地图'))
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///列表项点击事件
  void _itemClick(Map<String, dynamic> item) {
    if (widget.needOpenMap) {
      Get.to(const DispatchMainMap(), arguments: item['sequenceNbr']);
    } else {
      widget.callJSMethod('autoSwitchAlarm("${item['sequenceNbr']}")');
      Get.back();
    }
  }

  @override
  List<DropdownMenuBuilderEntity> getDropdownMenuContentEntity() => <DropdownMenuBuilderEntity>[
        DropdownMenuBuilderEntity(timeTypeSelectIndex, timeType),
        DropdownMenuBuilderEntity(typeSelectIndex, type),
        DropdownMenuBuilderEntity(sortSelectIndex, sort)
      ];

  @override
  void onDropdownItemChanged({int menuIndex, int index, int subIndex, data}) {
    print('menuIndex:$menuIndex index:$index subIndex:$subIndex data:$data');
    switch (menuIndex) {
      case 0:
        filterData['status'] = data['value'];
        setState(() {
          timeTypeSelectIndex = index;
        });
        break;
      case 1:
        filterData['alertTypeCode'] = data['value'];
        setState(() {
          typeSelectIndex = index;
        });
        break;
      case 2:
        filterData['orderTime'] = data['value'];
        setState(() {
          sortSelectIndex = index;
        });
        break;
    }
    onRefresh();
  }

  String _getTypeIcon(String typeCode) {
    switch (typeCode) {
      case '229':
        return 'assets/images/yi_ban.png';
      case '230':
        return 'assets/images/hang_kong_qi.png';
      case '235':
        return 'assets/images/tu_fa_shi_jian.png';
      case '237':
        return 'assets/images/lou_you.png';
      case '238':
        return 'assets/images/zhuan_ji_bao_zhang.png';
      case '1214':
        return 'assets/images/120_ji_jiu.png';
      case '242':
        return 'assets/images/other.png';
      default:
        return 'assets/images/other.png';
    }
  }

  @override
  Future<void> getData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.commandHistoryList(filterData..addAll({'pageNum': page.current + 1, 'pageSize': page.size}));
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      if (data != null) {
        setState(() {
          dataList.addAll(data['records'].cast<Map<String, Object>>());
        });
      }
    }).whenComplete(() => Get.back());
  }

  Future<void> getType() async {
    Future.delayed(Duration.zero, () async {
      var data = await API.gwmcDataDictionaryJQLB();
      if (data != null) {
        setState(() {
          data.forEach((element) {
            type.add({'title': element['name'], 'value': element['id']});
          });
        });
      }
    });
  }
}
