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

///@Description     联动信息
///@author          helinlin
///@create          2021-10-11 11:16
class LinkageInformation extends StatefulWidget {
  const LinkageInformation({Key key}) : super(key: key);

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

class _LinkageInformationState extends BaseDropdownFilterState<LinkageInformation> {
  List<Map> department = [
    {'title': '联动单位', 'value': ''},
  ];
  List<Map> type = [
    {'title': '服务类型', 'value': ''},
  ];
  List<Map> status = [
    {'title': '全部时效', 'value': ''},
    {'title': '协议期有效', 'value': '是'},
    {'title': '协议期无效', 'value': '否'},
  ];
  int departmentSelectIndex = 0;
  int typeSelectIndex = 0;
  int statusSelectIndex = 0;

  Map<String, Object> filterData = {};
  String imageUrl = '';
  SearchBar _searchBar;

  _LinkageInformationState() {
    _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, 'unitName', value);
          onRefresh();
        },
        onCleared: () {
          filterData.remove('unitName');
          onRefresh();
        },
        onClosed: () {
          filterData.remove('unitName');
          onRefresh();
        });
  }

  @override
  String pageTitle() => '联动信息';

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

  @override
  void initState() {
    super.initState();
    setState(() {
      //隐藏过滤按钮
      hasFilter = false;
    });
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    getType();
    getDepartment();
  }

  @override
  Widget buildListItem(BuildContext context, int index) {
    Map<String, dynamic> item = dataList[index];
    return CommonCard(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          children: [
            (item['image'] ?? []).isNotEmpty
                ? Image.network(imageUrl + '${item['image'][0]['filePath']}',
                    width: 70,
                    height: 70,
                    fit: BoxFit.fill,
                    errorBuilder: (
                      BuildContext context,
                      Object error,
                      StackTrace stackTrace,
                    ) =>
                        Image.asset(
                          'assets/images/location.png',
                          width: 70,
                          height: 70,
                          fit: BoxFit.fill,
                        ))
                : Image.asset('assets/images/linkage_information.png', width: 70, height: 70, fit: BoxFit.fill),
            const SizedBox(
              width: 10,
            ),
            Expanded(
              flex: 3,
              child: Padding(
                padding: const EdgeInsets.only(left: 8.0),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                            child: Text(
                          item['unitName'] ?? '',
                          style: const TextStyle(fontWeight: FontWeight.w600),
                        )),
                        item['linkageUnitType'] != null
                            ? Container(
                                color: getColor(item['linkageUnitType'] ?? '')['background'],
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 14),
                                  child: Text(
                                    item['linkageUnitType'] ?? '',
                                    style: TextStyle(color: getColor(item['linkageUnitType'] ?? '')['textColor']),
                                  ),
                                ),
                              )
                            : const SizedBox(),
                        const SizedBox(
                          width: 10,
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 2,
                    ),
                    _buildRow('地址：', item['address'] ?? ''),
                    _buildRow('负责人：', item['contactUser'] ?? ''),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 1),
                      child: Opacity(
                        opacity: 0.6,
                        child: Row(
                          children: [
                            const Text(
                              '联系电话：',
                              style: TextStyle(fontSize: 13),
                              overflow: TextOverflow.ellipsis,
                            ),
                            GestureDetector(
                              child: Text(
                                item['contactPhone'] ?? '',
                                style: const TextStyle(fontSize: 13, color: Colors.blue),
                                overflow: TextOverflow.ellipsis,
                              ),
                              onTap: () {
                                if (item['contactPhone'] != null && item['contactPhone'].isNotEmpty) {
                                  launch('tel:${item['contactPhone']}');
                                }
                              },
                            )
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRow(String title, String content) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 1),
      child: Opacity(
        opacity: 0.6,
        child: Row(
          children: [
            Text(
              title,
              style: const TextStyle(fontSize: 13),
              overflow: TextOverflow.ellipsis,
            ),
            Expanded(
              child: Text(
                content,
                style: const TextStyle(fontSize: 13),
                overflow: TextOverflow.ellipsis,
              ),
            )
          ],
        ),
      ),
    );
  }

  Map<String, Color> getColor(String type) {
    switch (type) {
      case '联动':
        return {'background': Colors.green[50], 'textColor': Colors.green};
      case '协议':
        return {'background': Colors.blue[50], 'textColor': Colors.blue};
      default:
        return {'background': Colors.green[50], 'textColor': Colors.green};
    }
  }

  @override
  List<DropdownMenuBuilderEntity> getDropdownMenuContentEntity() => <DropdownMenuBuilderEntity>[
        DropdownMenuBuilderEntity(departmentSelectIndex, department),
        DropdownMenuBuilderEntity(typeSelectIndex, type),
        DropdownMenuBuilderEntity(statusSelectIndex, status)
      ];

  @override
  void onDropdownItemChanged({int menuIndex, int index, int subIndex, data}) {
    print('menuIndex:$menuIndex index:$index subIndex:$subIndex data:$data');
    switch (menuIndex) {
      case 0:
        filterData['emergencyLinkageUnitCode'] = data['value'];
        setState(() {
          departmentSelectIndex = index;
        });
        break;
      case 1:
        filterData['linkageUnitTypeCode'] = data['value'];
        setState(() {
          typeSelectIndex = index;
        });
        break;
      case 2:
        filterData['inAgreement'] = data['value'];
        setState(() {
          statusSelectIndex = index;
        });
        break;
    }
    onRefresh();
  }

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

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

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