import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.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:jcs_airport/view/common/tree_view.dart';

///@Description     车辆绑定
///@author          helinlin
///@create          2021-10-11 11:16
class BindingCar extends StatefulWidget {
  const BindingCar({Key key}) : super(key: key);

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

class _BindingCarState extends BaseDropdownFilterState<BindingCar> {
  List<Map> type = [
    {'title': '全部类型', 'value': '0'},
  ];

  List<Map> status = [
    {'title': '全部', 'value': ''},
    {'title': '我已绑定', 'value': true},
    {'title': '我未绑定', 'value': false},
  ];
  int typeSelectIndex = 0;
  int statusSelectIndex = 0;

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

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

  @override
  String pageTitle() => '车辆绑定';

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

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
  }

  @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(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            (item['image'] ?? []).isNotEmpty
                ? Image.network(
                    imageUrl + '${item['image'][0]}',
                    width: 70,
                    height: 70,
                    fit: BoxFit.fill,
                    errorBuilder: (
                      BuildContext context,
                      Object error,
                      StackTrace stackTrace,
                    ) =>
                        Image.asset(
                      'assets/images/car_default.png',
                      width: 70,
                      height: 70,
                      fit: BoxFit.fill,
                    ),
                  )
                : Image.asset(
                    'assets/images/car_default.png',
                    width: 70,
                    height: 70,
                    fit: BoxFit.fill,
                  ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item['equipmentName'] ?? '',
                      style: const TextStyle(fontSize: 15),
                    ),
                    const SizedBox(
                      height: 3,
                    ),
                    Opacity(
                      opacity: 0.6,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item['carNum'] ?? '',
                            style: const TextStyle(fontSize: 14),
                          ),
                          Text(
                            item['teamName'] ?? '',
                            style: const TextStyle(fontSize: 14),
                          ),
                          Text(
                            '绑定人:'+(item['userName'] ?? '无'),
                            style: const TextStyle(fontSize: 14),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            Checkbox(
              activeColor: Theme.of(context).primaryColor,
              value: select == item['id'],
              onChanged: (bool val) {
                if (select.isNotEmpty && val) {
                  ToastUtils.showToast('已与其他车辆绑定，请先进行解绑！');
                  return;
                }else if(val &&item['userName']!=null&&item['userName'].isNotEmpty){
                  ToastUtils.showToast(' 此车辆已与'+item['userName']+'绑定，请重新选择！');
                  return;
                }
                showDialog(
                    context: context,
                    builder: (BuildContext context) => AlertDialog(
                          title: const Text('提示', style: TextStyle(fontSize: 18)),
                          content: Row(
                            children: [
                              const Text('确定要与', style: TextStyle(fontSize: 15)),
                              Text(item['equipmentName'], style: const TextStyle(color: Colors.red, fontSize: 15)),
                              Text(val ? '绑定？' : '解绑？', style: const TextStyle(fontSize: 15)),
                            ],
                          ),
                          actions: [
                            TextButton(
                              child: const Text('取消'),
                              onPressed: () {
                                Get.back();
                              },
                            ),
                            TextButton(
                              child: const Text('确定'),
                              onPressed: () {
                                Get.back();
                                submitData(val ? '1' : '2', item);
                              },
                            )
                          ],
                        ));
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  List<DropdownMenuBuilderEntity> getDropdownMenuContentEntity() => <DropdownMenuBuilderEntity>[
        //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['isNo'] = data['value'];
        setState(() {
          statusSelectIndex = index;
        });
        break;
    }
    onRefresh();
  }

  @override
  Future<void> onFilterTap() async {
    super.onFilterTap();
    await Get.to(Filter(carType));
    if (carType.isNotEmpty) {
      filterData.addAll({'code': carType['code']});
    } else {
      filterData.remove('code');
    }
    onRefresh();
  }

  @override
  Future<void> getData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.equipmentCarList(filterData..addAll({'pageNum': page.current + 1, 'pageSize': 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['data']['records'].cast<Map<String, Object>>();
          if (dataSub.isEmpty) {
            refreshController.loadNoData();
          }
          dataList.addAll(dataSub);
          // if (data['select'] != null) {
            select = data['select'] ?? '';
          // }
        });
      }
    }).whenComplete(() => Get.back());
  }

  ///车辆绑定解绑操作 1 绑定 2解绑
  Future<void> submitData(String type, dynamic item) async {
    MsgBox.showProgressDialog(context);
    var data = await API.adduserCar(type, {'carId': item['id'], 'carNum': item['carNum']});
    Get.back();
    if (data == true) {
      setState(() {
        type == '1' ? select = item['id'] : select = '';
      });
      onRefresh();
    }
  }
}

///过滤页面
class Filter extends StatefulWidget {
  final Map carType;

  const Filter(this.carType);

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

class _FilterState extends State<Filter> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('筛选'),
      ),
      body: Column(
        children: [
          Expanded(
            child: FormItem(
                layout: FormLayout.vertical,
                label: '类型:',
                formfield: SelectFormNewPage(
                    value: widget.carType['name'],
                    selectPage: ChooseCar(type: widget.carType),
                    onChanged: (val) {
                      if (val != null) {
                        setState(() {
                          widget.carType.addAll(val);
                        });
                      }
                    })),
          ),
          Row(
            children: [
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: OutlineButton(
                      onPressed: () {
                        setState(() {
                          widget.carType.clear();
                        });
                      },
                      color: Colors.black12,
                      child: const Text(
                        '重置',
                      )),
                ),
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: FlatButton(
                      onPressed: () => Get.back(),
                      color: Theme.of(context).primaryColor,
                      child: const Text(
                        '确定',
                        style: TextStyle(color: Colors.white),
                      )),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

class ChooseCar extends StatefulWidget {
  Map type;

  ChooseCar({this.type});

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

class _ChooseCarState extends ChooseTreeState<ChooseCar> {
  @override
  Future getData() => API.commandTree();

  @override
  String getKey() => 'code';

  @override
  String getName() => 'name';
}
