import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/entity/Page.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:jcs_airport/view/workBench/realTimeMonitoring/iotFacilities/facility.dart';
import 'package:jcs_airport/viewmodel/facility_filter.dart';
import 'package:amos_iot_login_tpl/const/global_config.dart';
import 'package:amos_flutter_utils/utils.dart';

import 'equipment.dart';
import 'equipment_category_detail.dart';

///维保设类型类详情
class EquipmentCategory extends StatefulWidget {
  final String id;
  final String fireFightSysId;
  const EquipmentCategory(this.id,this.fireFightSysId);

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

class _EquipmentCategoryState extends State<EquipmentCategory> {
  final List<Map> _department = [
    {'title': '全部单位', 'value': ''},
  ];
  final List<Map<dynamic, dynamic>> _location = [
    {
      'name': '全部建筑',
      'title': '全部建筑',
      'children': [
        {'name': '全部楼层', 'title': '全部楼层', 'instanceId': ''}
      ]
    },
  ];
  final List<Map> _status = [
    {'title': '全部状态', 'value': ''},
  ];
  final List<Map> _data = [];
  final Map<String, Object> filterData = {};
  final AmosPage _amosPage = AmosPage(current: 0);
  /// 图片服务器前缀
  String imagePrefix = '';

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imagePrefix = value;
      });
    });
    _initData();
    _getStatus();
    _getBuildingTree();
    _userIdentify();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('维保设施'),
      ),
      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['value'] != '') {
                data['type'] == 1
                    ? filterData['maintenanceCompanyId'] = data['value']
                    : filterData['ownerUnitId'] = data['value'];
              } else {
                filterData.remove('ownerUnitId');
                filterData.remove('maintenanceCompanyId');
              }
              break;
            case 1:
              if (data['instanceId'] != '') {
                filterData['buildingId'] = data['instanceId'];
              } else {
                filterData.remove('buildingId');
              }
              break;
            case 2:
              if (data['value'] != '') {
                filterData['status'] = data['value'];
              } else {
                filterData.remove('status');
              }
              break;
          }
          _data.clear();
          _amosPage.current = 0;
          _initData();
        },
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 50),
              child: Column(
                children: [
                  _data.isNotEmpty
                      ? Expanded(
                          child: ListView.builder(
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                margin: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                                decoration: const BoxDecoration(
                                    color: Colors.white,
                                    boxShadow: [
                                      BoxShadow(
                                          color: Colors.black12,
                                          offset: Offset(1.0, 1.0),
                                          blurRadius: 3.0,
                                          spreadRadius: 1.0),
                                    ],
                                    borderRadius: BorderRadius.all(Radius.circular(8.0))),
                                child: InkWell(
                                  onTap: () {
                                    if (_data[index]['fireFacilityType'] != 'equip') {
                                      Get.to(EquipmentCategoryDetail(_data[index]));
                                    } else {
                                      Get.to(
                                          FacilityTab(
                                            equipmentCategory: _data[index],
                                          ),
                                          arguments: FacilityFilter.fromParams(
                                              fireEquipmentCode: _data[index]['fireFacilityCode']));
                                    }
                                  },
                                  child: ListTile(
                                    title: Padding(
                                      padding: const EdgeInsets.only(bottom: 5),
                                      child: Flex(
                                        direction: Axis.horizontal,
                                        children: [
                                          Expanded(
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  _data[index]['fireFacilityName'] ?? '',
                                                  style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                                ),
                                              ],
                                            ),
                                          ),
                                          _data[index]['status'] != null
                                              ? Expanded(
                                                  child: Column(
                                                    crossAxisAlignment: CrossAxisAlignment.end,
                                                    children: [
                                                      Container(
                                                        decoration: BoxDecoration(
                                                            color: AMOSColors.maintenanceEquipmentRecordStatusColor(
                                                                _data[index]['statusText'] ?? ''),
                                                            borderRadius: const BorderRadius.all(Radius.circular(20))),
                                                        child: Text(
                                                          _data[index]['statusText'] ?? '',
                                                          style: const TextStyle(
                                                              fontSize: CoreStyles.textSizeMin, color: Colors.white),
                                                        ),
                                                        padding:
                                                            const EdgeInsets.symmetric(horizontal: 8, vertical: 0.5),
                                                        margin: const EdgeInsets.only(top: 4),
                                                      ),
                                                    ],
                                                  ),
                                                )
                                              : Container(),
                                        ],
                                      ),
                                    ),
                                    subtitle: Column(
                                      children: [
                                        Row(
                                          children: [
                                            const Text('编号：'),
                                            Text(
                                              _data[index]['code'] ?? '',
                                            ),
                                          ],
                                        ),
                                        const SizedBox(
                                          height: 1,
                                        ),
                                        Row(
                                          children: [
                                            const Text('位置：'),
                                            Text(
                                              _data[index]['location'] ?? '',
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                    leading: Container(
                                      width: 60,
                                      height: 60,
                                      child: Image.network(
                                             Utils.completeUrl(imagePrefix, _data[index]['img']),
                                             width: 60,
                                             height: 60,
                                             errorBuilder: ( BuildContext context,Object error,StackTrace stackTrace){
                                               return Image.asset(
                                             'assets/images/mask_group.png',
                                             width: 60,
                                             height: 60,
                                               );
                                             },
                                            )
                                      
                                      /* Image.asset('assets/images/mask_group.png') */,
                                    ),
                                  ),
                                ),
                              );
                            },
                            shrinkWrap: true,
                            itemCount: _data.length,
                          ),
                        )
                      : const NoData()
                ],
              ),
            ),
            Row(
              children: [
                Expanded(
                  child: Container(
                    color: Colors.white,
                    child: DropdownHeader(
                      onTap: null,
                      fontSize: 13,
                      titles: [
                        _department[0],
                        _location[0],
                        _status[0],
                      ],
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 46.0),
              child: DropdownMenu(menus: [
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(selectedIndex: 0, data: _department, itemBuilder: buildCheckItem);
                    },
                    height: (_department.length * 46).toDouble()),
                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 _initData() {
    Future.delayed(Duration.zero, () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      Future.wait([_getData()]).whenComplete(() => Get.back());
    });
  }

  Future<void> _getData() async {
    var data = await API.getFireFacilityPage(
        filterData..addAll({'current': _amosPage.current, 'size': _amosPage.size, 'classifyId': widget.id,'fireFightSysId' : widget.fireFightSysId    }));
    if (data != null) {
      setState(() {
        _data.addAll(data['records'].cast<Map>());
      });
    }
  }

  Future<void> _getStatus() async {
    var data = await API.dictionary('MAINTENANCE_STATUS');
    if (data != null) {
      setState(() {
        data.forEach((element) {
          _status.add({'title': element['dictDataValue'], 'value': element['dictDataKey']});
        });
      });
    }
  }

  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>());
      });
    }
  }

  ///单位下拉列表
  Future<void> _userIdentify() async {
    var data = await API.userIdentify();
    if (data != null) {
      setState(() {
        if ((data['identityType'] ?? 2).toString() == '2') {
          Equipment.isMaster = true;
        }
      });
      _selectOwnerUnitList({'id': data['companyId'], 'type': data['identityType']});
    }
  }

  Future<void> _selectOwnerUnitList(dynamic query) async {
    var data = await API.selectOwnerUnitList(query);
    if (data != null) {
      setState(() {
        data.forEach((element) {
          _department.add({'title': element['name'], 'value': element['id'], 'type': element['type']});
        });
      });
    }
  }
}
