import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:jcs_airport/view/workBench/maintenance/common/choose_maintenance_firefighting_system.dart';
import 'package:jcs_airport/view/workBench/maintenance/maintenanceTask/task_detail.dart';

class TaskEquipment extends StatefulWidget {
  final String title;
  final String sequenceNbr;
  final bool isExecutor;
  final bool canExecute;
  const TaskEquipment(this.title,this.sequenceNbr, this.isExecutor, this.canExecute);
  // const TaskEquipment({Key key}) : super(key: key);

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

class _TaskEquipmentState extends State<TaskEquipment> {


  final List<Map> _location = [
    {
      'name': '全部建筑',
      'title': '全部建筑',
      'children': [
        {'name': '全部建筑', 'title': '全部建筑', 'instanceId': ''}
      ]
    },
  ];
  final List<Map> _status = [
    {'title': '全部状态', 'value': ''},
  ];

  Map system = {};
  final Map<String, Object> filterData = {};
  final List<Map<String, Object>> _data = [];

  @override
  void initState() {
    super.initState();
    _getData();
    _getStatus();
    _getBuildingTree();
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: DefaultDropdownMenuController(
        onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
          print('menuIndex:$menuIndex index:$index subIndex:$subIndex data:$data');
          switch (menuIndex) {
            case 0:
              if (data['instanceId'] != '') {
                filterData['buildingId'] = data['instanceId'];
              } else {
                filterData.remove('buildingId');
              }
              break;
            case 1:
              if (data['value'] != '') {
                filterData['isFinish'] = data['value'];
              } else {
                filterData.remove('isFinish');
              }
              break;
          }
          setState(() {
            _data.clear();
          });
          _getData();
        },
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 46),
              child: Column(
                children: [
                  _data.isNotEmpty
                      ? Expanded(
                          child: ListView.builder(
                            itemCount: _data.length,
                            shrinkWrap: true,
                            itemBuilder: (BuildContext context, int index) {
                              Map<String, Object> item = _data[index];
                              ListViewItemModel listViewItemModel = ListViewItemModel(
                                  hasState: true,
                                  stateColor: AMOSColors.maintenanceEquipmentStatusColor(item['isFinish']),
                                  hasFooter: true,
                                  footer: '编号：' + item['pointNo'],
                                  title: item['name'],
                                  onclick: () async {
                                    await Get.to(TaskDetail(
                                        (item['id'] ?? '').toString(),
                                        (item['routePointId'] ?? '').toString(),
                                        widget.isExecutor && widget.canExecute && item['isFinish'] == 0));
                                    _data.clear();
                                    _getData();
                                  });
                              return ListViewItem(
                                listViewItemModel: listViewItemModel,
                                contentWidget: Padding(
                                  padding: const EdgeInsets.all(5.0),
                                  child: Column(
                                    children: [
                                      Row(
                                        children: [
                                          Expanded(
                                            child: Row(
                                              children: [
                                                const Text('系统：'),
                                                const SizedBox(
                                                  width: 5,
                                                ),
                                                Expanded(
                                                    child: Text(
                                                  item['belongSystemName'],
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                )),
                                              ],
                                            ),
                                          ),
                                          Transform.translate(
                                            offset: const Offset(8, 0),
                                            child: Row(
                                              children: [
                                                Text(
                                                  item['isFinishDesc'].toString(),
                                                  style: TextStyle(
                                                      color: AMOSColors.maintenanceEquipmentStatusColor(item['isFinish'])),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                      const SizedBox(
                                        height: 5,
                                      ),
                                      Row(
                                        children: [
                                          Expanded(
                                            child: Row(
                                              children: [
                                                const Text('位置：'),
                                                const SizedBox(
                                                  width: 5,
                                                ),
                                                Text(item['position']),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            },
                          ),
                        )
                      : const NoData()
                ],
              ),
            ),
            Row(
              children: [
                Expanded(
                  flex: 4,
                  child: DropdownHeader(
                    onTap: null,
                    fontSize: 13,
                    titles: [
                      _location[0],
                      _status[0],
                    ],
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child: InkWell(
                      onTap: () async {
                        var data = await Get.to(TaskEquipmentFilter(filterData, system));
                        if (data != null) {
                          system = data;
                        }
                        print(filterData);
                        setState(() {
                          _data.clear();
                        });
                        _getData();
                      },
                      child: Row(
                        children: const [
                          Text(
                            '筛选',
                            style: TextStyle(color: Colors.black54),
                          ),
                          Icon(
                            Icons.filter_alt_outlined,
                            size: 14,
                            color: Colors.black54,
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 46.0),
              child: DropdownMenu(menus: [
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownTreeMenu(
                        selectedIndex: 0,
                        subSelectedIndex: 0,
                        itemExtent: 45.0,
                        itemBuilder: (BuildContext context, dynamic data, bool selected) {
                          if (!selected) {
                            return DecoratedBox(
                                decoration: BoxDecoration(border: Border(right: Divider.createBorderSide(context))),
                                child: Padding(
                                    padding: const EdgeInsets.only(left: 15.0),
                                    child: Row(
                                      children: <Widget>[
                                        Text(data['name']),
                                      ],
                                    )));
                          } else {
                            return DecoratedBox(
                                decoration: BoxDecoration(
                                    border: Border(
                                        top: Divider.createBorderSide(context), bottom: Divider.createBorderSide(context))),
                                child: Container(
                                    color: Theme.of(context).scaffoldBackgroundColor,
                                    child: Row(
                                      children: <Widget>[
                                        Container(color: Theme.of(context).primaryColor, width: 3.0, height: 20.0),
                                        Padding(padding: const EdgeInsets.only(left: 12.0), child: Text(data['name'])),
                                      ],
                                    )));
                          }
                        },
                        subItemBuilder: (BuildContext context, dynamic data, bool selected) {
                          final Color color =
                              selected ? Theme.of(context).primaryColor : Theme.of(context).textTheme.bodyText2.color;
                          return Container(
                            decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey))),
                            child: SizedBox(
                              height: 45.0,
                              child: Row(
                                children: <Widget>[
                                  Text(
                                    data['name'],
                                    style: TextStyle(color: color),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                        getSubData: (dynamic data) {
                          return data['children'];
                        },
                        data: _location,
                      );
                    },
                    height: 450.0),
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(selectedIndex: 0, data: _status, itemBuilder: buildCheckItem);
                    },
                    height: (_status.length * 46).toDouble()),
              ]),
            ),
          ],
        ),
      ),
    );
  }

  void _getData() {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.planTaskPoint(widget.sequenceNbr, filterData);
      Get.back();
      if (data != null) {
        setState(() {
          _data.addAll(data.cast<Map<String, Object>>());
        });
      }
    });
  }

  Future<void> _getStatus() async {
    var data = await API.planFinishStatusList();
    if (data != null) {
      setState(() {
        data.forEach((element) {
          _status.add({'title': element.values.first, 'value': element.keys.first});
        });
      });
    }
  }

  Future<void> _getBuildingTree() async {
    var data = await API.buildingTree();
    if (data != null) {
      setState(() {
        var temp = data[0]['children'];
        temp.forEach((element) {
          element.addAll({'title': element['name']});
          element['children'].forEach((item) {
            item.addAll({'title': item['name']});
          });
        });
        _location.addAll(temp.cast<Map>());
      });
    }
  }
}

///筛选页面
class TaskEquipmentFilter extends StatefulWidget {
  final Map<String, Object> filterData;
  Map system;

  TaskEquipmentFilter(this.filterData, this.system);

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

class _TaskEquipmentFilterState extends State<TaskEquipmentFilter> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('筛选'),
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Form(
                  child: Column(
                children: [
                  const SizedBox(
                    height: 10,
                  ),
                  FormItem(
                      layout: FormLayout.vertical,
                      label: '消防系统:',
                      formfield: SelectFormNewPage(
                          value: widget.filterData['systemName'] ?? '',
                          selectPage: ChooseFireFightingSystem(widget.system),
                          onChanged: (val) {
                            if (val != null) {
                              setState(() {
                                widget.system = val;
                                widget.filterData['systemName'] = val['name'];
                                widget.filterData['systemId'] = val['id'];
                              });
                            }
                          })),
                  const SizedBox(
                    height: 10,
                  ),
                  FormItem(
                    layout: FormLayout.vertical,
                    label: '设备名称:',
                    formfield: ITextFormField(
                        value: widget.filterData['pointName'] ?? '',
                        textStyle: CoreStyles.smallText,
                        hintText: '',
                        onChanged: (val) {
                          setState(() {
                            widget.filterData['pointName'] = val;
                          });
                        }),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  FormItem(
                    layout: FormLayout.vertical,
                    label: '设备编号:',
                    formfield: ITextFormField(
                        value: widget.filterData['pointNo'] ?? '',
                        textStyle: CoreStyles.smallText,
                        hintText: '',
                        onChanged: (val) {
                          setState(() {
                            widget.filterData['pointNo'] = val;
                          });
                        }),
                  ),
                ],
              )),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              children: [
                Expanded(
                    child: FlatButton(
                  color: const Color.fromRGBO(242, 246, 249, 1),
                  height: 40,
                  onPressed: () {
                    setState(() {
                      widget.filterData.clear();
                    });
                  },
                  child: const Text(
                    '重置',
                    style: TextStyle(color: Colors.black87),
                  ),
                )),
                const SizedBox(
                  width: 5,
                ),
                Expanded(
                    child: FlatButton(
                  color: Colors.blueAccent,
                  height: 40,
                  onPressed: () {
                    Get.back(result: widget.system);
                  },
                  child: const Text(
                    '确定',
                    style: TextStyle(color: Colors.white),
                  ),
                )),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
