import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/entity/platform_menu.dart';
import 'package:flutter/material.dart';
import 'package:get/get.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:amos_iot_login_tpl/const/global_config.dart';
import 'package:amos_flutter_utils/utils.dart';
import 'equipment_category.dart';

///维保任务
class Equipment extends StatefulWidget {
  ///是否为业主单位角色
  static bool isMaster = false;

  const Equipment({Key key}) : super(key: key);

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

class _EquipmentState extends State<Equipment> {
  final List<Map> companys = [
    {'title': '全部单位', 'value': ''},
  ];
  final List<Map> orderByEndTime = [
    {'title': '到期数正序', 'value': 'asc'},
    {'title': '到期数逆序', 'value': 'desc'},
  ];
  final List<Map<String, Object>> _systemData = [];
  final List<Map<String, Object>> _equipmentData = [];

  Divider divider = const Divider(height: 2);
  AmosPage amosPage = AmosPage(current: 0, size: 9999);
  Map<String, Object> filterData = {'expirationTimeSort': 'asc'};
  /// 图片服务器前缀
  String imagePrefix = '';

  /// 左侧选中颜色
  String isLeftAddColor = '';

  ///从首页跳转额外处理
  void processFromHome() {
    PlatformMenu platformMenu = Get.arguments;
  }

  @override
  void initState() {
    super.initState();
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imagePrefix = value;
      });
    });
    processFromHome();
    _initData();
    _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['value'] != '') {
                filterData['expirationTimeSort'] = data['value'];
              } else {
                filterData.remove('expirationTimeSort');
              }
              break;
          }
          setState(() {
            _systemData.clear();
            _equipmentData.clear();
          });
          _initData();
        },
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 50),
              child: Column(
                children: [
                  Expanded(
                    child: Row(
                      children: [
                        Expanded(
                          child: Ink(
                            decoration: const BoxDecoration(color: Colors.white,
                                //borderRadius: BorderRadius.all(Radius.circular(8)),
                                boxShadow: [
                                  BoxShadow(
                                      color: Colors.black12,
                                      offset: Offset(1.0, 1.0),
                                      blurRadius: 3.0,
                                      spreadRadius: 1.0)
                                ]),
                            child: Column(
                              children: [
                                Expanded(
                                  child: ListView.separated(
                                      shrinkWrap: true,
                                      itemBuilder: (BuildContext context, int index) {
                                        return InkWell(
                                          onTap: () {
                                            _equipmentData.clear();
                                            setState(() {
                                              isLeftAddColor = _systemData[index]['id'];
                                            });
                                            getEquipmentData(id: _systemData[index]['id']);
                                          },
                                          child: Container(
                                            child: Text(_systemData[index]['name'] ?? ''),
                                            height: 40,
                                            padding: const EdgeInsets.all(10.0),
                                            color: isLeftAddColor == _systemData[index]['id'] ? Colors.blue[100] : null,
                                          ),
                                        );
                                      },
                                      separatorBuilder: (BuildContext context, int index) {
                                        return divider;
                                      },
                                      itemCount: _systemData.length),
                                ),
                              ],
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 2,
                          child: Column(
                            children: [
                              _equipmentData.isNotEmpty
                                  ? Expanded(
                                      child: ListView.builder(
                                          shrinkWrap: true,
                                          itemBuilder: (BuildContext context, int index) {
                                            return Container(
                                              child: InkWell(
                                                onTap: () {
                                                  Get.to(EquipmentCategory(_equipmentData[index]['classifyId'] ?? '',_equipmentData[index]['fireFightSysId'] ?? ''));
                                                },
                                                child: ListTile(
                                                  title: Padding(
                                                    padding: const EdgeInsets.only(bottom: 5),
                                                    child: Text(
                                                      _equipmentData[index]['classifyName'] ?? '',
                                                      style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                                    ),
                                                  ),
                                                  subtitle: Column(
                                                    children: [
                                                      Row(
                                                        children: [
                                                          const Text('数量：'),
                                                          Text(
                                                            (_equipmentData[index]['amount'] ?? 0).toString(),
                                                          ),
                                                        ],
                                                      ),
                                                      Row(
                                                        children: [
                                                          const Text('到期：'),
                                                          Text(
                                                            _equipmentData[index]['maintenanceExpirationTime'] ?? '',
                                                            style: const TextStyle(color: Colors.orange),
                                                          ),
                                                        ],
                                                      )
                                                    ],
                                                  ),
                                                  trailing: Transform.translate(
                                                    offset: const Offset(0, 15),
                                                    child: const Icon(
                                                      Icons.arrow_forward_ios_outlined,
                                                      color: Colors.blue,
                                                      size: 16,
                                                    ),
                                                  ),
                                                  leading: Container(
                                                    width: 60,
                                                    height: 60,
                                                    child:  Image.network(
                                                            Utils.completeUrl(imagePrefix, _equipmentData[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(_equipmentData[index]['img'] ?? 'assets/images/mask_group.png') */,
                                                  ),
                                                ),
                                              ),
                                              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)),
                                              ),
                                              margin: const EdgeInsets.only(left: 6, right: 6, bottom: 4),
                                            );
                                          },
                                          itemCount: _equipmentData.length),
                                    )
                                  : const NoData(),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                Expanded(
                  child: Container(
                    color: Colors.white,
                    child: DropdownHeader(
                      onTap: null,
                      fontSize: 13,
                      titles: [
                        companys[0],
                        orderByEndTime[0],
                      ],
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 46.0),
              child: DropdownMenu(menus: [
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(selectedIndex: 0, data: companys, itemBuilder: buildCheckItem);
                    },
                    height: (companys.length * 46).toDouble()),
                DropdownMenuBuilder(
                    builder: (BuildContext context) {
                      return DropdownListMenu(selectedIndex: 0, data: orderByEndTime, itemBuilder: buildCheckItem);
                    },
                    height: (orderByEndTime.length * 46).toDouble()),
              ]),
            ),
          ],
        ),
      ),
    );
  }

  void _initData() {
    Future.delayed(Duration.zero, () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      Future.wait([getSystemDate(), getEquipmentData(id: '')]).whenComplete(() => Get.back());
    });
  }

  Future<void> getSystemDate() async {
    var data = await API.fireFightSysPage({'current': amosPage.current, 'size': amosPage.size,'type':3});
    if (data != null) {
      setState(() {
        _systemData.addAll(data['records'].cast<Map<String, Object>>());
      });
    }
  }

  Future<void> getEquipmentData({String id}) async {
    if (id != '') {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
    }
    var data = await API.fireFacilityPage(filterData
      ..addAll({
        'current': amosPage.current,
        'size': amosPage.size,
        'fireFightSysId': id,
      }));
    if (id != '') {
      Get.back();
    }
    if (data != null) {
      setState(() {
        _equipmentData.addAll(data['records'].cast<Map<String, Object>>());
      });
    }
  }

  ///单位下拉列表
  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) {
          companys.add({'title': element['name'], 'value': element['id'], 'type': element['type']});
        });
      });
    }
  }
}
