import 'dart:convert';
import 'package:base/routes/routes.dart' as base_routes;
import 'package:amos_flutter_ui/message/flutter_toast.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.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/view/Home/home_common.dart';
import 'package:base/view/statistics_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:base/utils/request.dart';
import 'package:base/model/warehouse_info_model.dart';
import 'package:base/model/warehouse_info_view_model.dart';
import 'package:provider/provider.dart';
import 'package:base/consts/share_prefers_key_const.dart';

import 'dart:convert';
import 'dart:typed_data';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';


import './../routes/routes.dart';
import './../services/api.dart';
import './http_config.dart';

const String FOOTER_COPYRIGHT = '东方电气集团东方汽轮机有限公司';

PermissionManager pm;

/// 统计中子菜单
List statisticsCardMenu = [];

/// 组件映射关系，需要采用权限进行配置时使用
Map<String, WidgetInfo> wmap = {
  //含有领导首页权限的后续将会替换此处为领导首页
  'Home': WidgetInfo('Home', const HomeCommon()),
  'Statistic': WidgetInfo('Statistic', StatisticsScreen(statisticsCardMenu)),
  'WorkBench': WidgetInfo('WorkBench', Workbench(IotPageConfig.workbenchBaseInfo, IotPageConfig.workbenchCardInfo)),
  'Mine': WidgetInfo('Mine', Mine(IotPageConfig.mineMenuLists, IotPageConfig.mineShareInfo, IotPageConfig.changePWD)),
  'Message': WidgetInfo('Message', MessageList())
};

/// 处理工作台 item
List handleWorkbenchChildren(menus, parent) {
  List<CardItem> cardItems = [];
  menus.forEach((element) {
    PlatformMenu platformMenu = PlatformMenu.fromJson(element);
    platformMenu.parentFrontComponent = parent['frontComponent'];
    if (platformMenu.parentId == parent['sequenceNbr'] && platformMenu.permissionType != 'BUTTON') {
      cardItems.add(CardItem(platformMenu.permissionName, platformMenu.icon, () {
        SharedPreferences.getInstance().then((sp) {
          bool offline = sp.getBool("offline");
          if (offline) {
            if(platformMenu.path == '/PlanPatrol') {
              Get.toNamed('/offlinePlanPatrol', arguments: platformMenu);
            } else if(platformMenu.path == '/NoPlanPatrol') {
              Get.toNamed('/offlineNoPlanPatrol', arguments: platformMenu);
            } else if(platformMenu.path == '/MoblePatrol') {
              Get.toNamed('/offlineMoblePatrol', arguments: platformMenu);
            } else if(platformMenu.path == '/PatrolPoint') {
              Get.toNamed('/offlinePatrolPoint', arguments: platformMenu);
            } else if(platformMenu.path == '/hiddenAdd') {
              Get.toNamed('/hiddenOfflineAdd', arguments: platformMenu);
            } else if(platformMenu.path == '/sign') {
              Get.toNamed('/offlineSign', arguments: platformMenu);
            } else if(platformMenu.path == '/trainAdd') {
              Get.toNamed('/trainAdd', arguments: platformMenu);
            } else if(platformMenu.path == '/trainRecord') {
              Get.toNamed('/trainRecord', arguments: platformMenu);
            } else {
              shortMessage('离线模式，该功能暂不支持。');
            }
          } else {
            if (platformMenu.path == '/trainAdd') {
              shortMessage('请切换离线模式使用。');
            } else if (platformMenu.path == '/trainRecord') {
              shortMessage('请切换离线模式使用。');
            } else {
              Get.toNamed(platformMenu.path, arguments: platformMenu).then((value)  {
                // Get.toNamed('/offlineSign', arguments: platformMenu);
                Get.off(MainIndex(pm.getBarItems(), pm.getTabBodys(), true));
              });
            }
          }
        });
      }));
    }
  });
  return cardItems;
}

/// 登录成功之后，权限处理/同步配置的IP地址
void handlePermission(dynamic menus) {
  // 重置统计中子菜单
  statisticsCardMenu = [];
  //根菜单ID
  String rootMenuID = '';
  //按钮权限
  List buttonPermission = [];
  //查找根菜单ID
  menus.forEach((menu) {
    if (menu['parentId'] == '0') {
      rootMenuID = menu['sequenceNbr'];
    }
    if (menu['permissionType'] == 'BUTTON') {
      buttonPermission.add(menu);
    }
  });

  /// 底部导航菜单
  List bottomNavigationMenu = [];
  menus.forEach((menu) {
    if (menu['parentId'] == rootMenuID) {
      bottomNavigationMenu.add(menu);
    }
  });

  ///如果底部导航菜单包含领导首页，移除掉普通首页，只显示领导首页
  int homeIndex;
  bottomNavigationMenu.forEach((menu) {
  if(menu['frontComponent'] == 'Home'){
      wmap['Home'] = WidgetInfo('Home', const HomeCommon());
    }

  });
  if (homeIndex != null) {
    bottomNavigationMenu.removeAt(homeIndex);
  }

  /// 获取工作台根菜单
  String workBenchRootMenuId = '';
  menus.forEach((menu) {
    //工作台
    if (menu['frontComponent'] == 'WorkBench') {
      workBenchRootMenuId = menu['sequenceNbr'];
    }
  });

  ///保存按钮权限
  List buttonPermissionList = [];

  /// 工作台的卡片菜单
  List workBenchCardMenu = [];
  menus.forEach((menu) {
    if (menu['parentId'] == workBenchRootMenuId) {
      workBenchCardMenu.add(menu);
    }
    buttonPermissionList.add(menu['path']);
  });

  /// 获取统计根菜单
  String statisticsRootMenuId = '';
  menus.forEach((menu) {
    //工作台
    if (menu['frontComponent'] == 'Statistic') {
      statisticsRootMenuId = menu['sequenceNbr'];
    }
  });

  /// 统计的中菜单
  menus.forEach((menu) {
    if (menu['parentId'] == statisticsRootMenuId) {
      statisticsCardMenu.add(menu);
    }
  });

  /// 工作台的卡片菜单下的子菜单
  List<WorkbenchCardInfo> workbenchCardInfo = [];
  workBenchCardMenu.forEach((element) {
    workbenchCardInfo.add(WorkbenchCardInfo(element['permissionName'], handleWorkbenchChildren(menus, element)));
  });
  IotPageConfig.workbenchCardInfo.clear();
  IotPageConfig.workbenchCardInfo.addAll(workbenchCardInfo);
  pm = PermissionManager(bottomNavigationMenu, wmap);


  buttonPermission.forEach((element) {
    buttonPermissionList.add(element['authCode']);
  });
  SharedPreferences.getInstance().then((sp) {
    sp.setString('permissionList', buttonPermissionList.join(','));
    sp.setBool('offline', false);
    API.agencyuserMe().then((value) {
      sp.setString('myInfo', json.encode(value));
    }).catchError((error) => ToastUtils.showToast(error.toString()));
  });

  ///跳转首页
  Get.off(MainIndex(pm.getBarItems(), pm.getTabBodys(), true));
}

mixin IotPageConfig {
  ///登录页数据接口
  static LoginInfo loginInfo = LoginInfo(
      HttpConfig.product, HttpConfig.appKey, 'assets/fire_logo.png', 'assets/sysname.png', handlePermission,
      footerText: FOOTER_COPYRIGHT, checkUpdate: (BuildContext context) {
    UpgradeAppHelper.customCheckUpdate(context, enableTopImage: true);
    // UpgradeAppHelper.checkUpdate(context, (){
    //   // do nothing
    // });
    Future.delayed(Duration.zero, () async {
      final SharedPreferences prefers = await SharedPreferences.getInstance();
      var resultA = prefers.getString(SharePrefersKey.companyModelKey);
      var resultB = prefers.getString(SharePrefersKey.companyModelKey1);
      final result = resultA ?? resultB;
      String orgCode = '';
      if(resultA != null){
         orgCode = json.decode(result)['orgCode'].toString();
      }else{
         orgCode = json.decode(result)['companys'][0]['orgCode'].toString();
      }
      HttpRequest.getWarehouseInfo(orgCode).then((value) {
        if (value['status'] == 200) {
          try {
            final model = WarehouseInfoModel.fromJson(value['result']);
            Provider.of<WarehouseInfoViewModel>(context, listen: false).warehouseInfoModel = model;
          } catch (e) {
            print(e);
          }
        } else {}
      }).catchError((_) {});
    });
  });

  static List getChildren(menus, menu) {
    List<CardItem> cardItems = [];
    menus.forEach((element) {
      PlatformMenu platformMenu = PlatformMenu.fromJson(element);
      if (platformMenu.parentId == menu['sequenceNbr']) {
        cardItems.add(CardItem(platformMenu.permissionName, GlobalImagePath.WAIT_PLAN, () {
          Get.toNamed(platformMenu.path, arguments: platformMenu);
        }));
      }
    });
    return cardItems;
  }

  ///mine分享页面数据接口
  static MineShareInfo mineShareInfo =
      const MineShareInfo(logoIconPath: 'assets/fire_logo.png', sysnameIconPath: 'assets/sysname.png');

  /// mine修改密码数据接口
  static ChangePWD changePWD = ChangePWD((String originalPassword, LoginFormData lfd) {
    /// 跳转至登录界面，自动填充新的密码
    Get.offAllNamed(JCSRoutes.root, arguments: lfd.toMap());
  });

  /// mine 模块，自定义添加功能
  static List<MineMenuList> mineMenuLists = [];
  // static List<MineMenuList> mineMenuLists = [
  //   MineMenuList(
  //       leftText: '消息1阅',
  //       leftIconData: Icons.ac_unit,
  //       onClick: () {
  //           SharedPreferences.getInstance().then((sp) {
  //           bool offline = sp.getBool("offline");
  //             if(offline) {
  //               shortMessage('离线模式，该功能暂不支持。');
  //             } else {
  //               Get.toNamed(base_routes.Routes.subscribePage);
  //             }
  //           });
  //       })
  // ];

  /// 工作台基础配置
  static WorkbenchBaseInfo workbenchBaseInfo = const WorkbenchBaseInfo('assets/images/mask_group.png');

  /// 工作台 card 数据集合(必须final修饰，防止修改引用更新菜单后再次登陆导致工作台数据不同步)
  static final List<WorkbenchCardInfo> workbenchCardInfo = [];

  /// home 数据配置
  static HomeMajorInfo homeMajorInfo = const HomeMajorInfo('assets/images/mask_group.png');

  /// 首页初始化执行函数
  static Future<List<HomeCardInfo>> initAction() {
    //缓存用户信息(装备模块需要使用)
    SharedPreferences.getInstance().then((sp) {
      API.agencyuserMe().then((value) {
        sp.setString('myInfo', json.encode(value));
      }).catchError((error) => ToastUtils.showToast(error.toString()));
    });


    //获取首页信息
    return getHomeInfo();
  }

  /// 获取 home 数据
  static Future<List<HomeCardInfo>> getHomeInfo() async {
    List<HomeCardInfo> _cardInfos = [];
    var datas = await API.homeStatisticsAction();
    if (datas != null) {
      datas.forEach((data) {
        List<HomeCardItem> cardItems = [];
        if (data['children'] != null) {
          data['children'].forEach((child) {
            PlatformMenu platformMenu = PlatformMenu.fromJson(child);
            double value = platformMenu.value ?? 0.0;
            double floorValue = value.floor().toDouble();
            HomeCardItem cardItem = HomeCardItem(
              title: platformMenu.permissionName,
              icon: platformMenu.icon,
              value: value - floorValue > 0.0 ? value : value.toInt(),
              onTap: () {
                Get.toNamed(platformMenu.path, arguments: platformMenu);
              },
            );
            cardItems.add(cardItem);
          });
        }
        HomeCardInfo hci = HomeCardInfo(data['permissionName'], cardItems);
        _cardInfos.add(hci);
      });
    }
    return _cardInfos;
  }
}
