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

import 'package:equipment_manage/routes/routes.dart' as equipment_manage_routes;
import 'package:flutter/material.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:offline/routes/routes.dart' as offline_routes;
import 'package:offline/view/hidedanger_manage/hide_danger_page_mytask.dart';
import 'package:offline/view/inspection_spot/offline_inspection_spot_screen.dart';
import 'package:offline/view/move_inspection/move_spot_list_screen.dart';
import 'package:offline/view/no_plan_inspection/no_plan_inspection.dart';
import 'package:offline/view/plan_inspection/offline_plan_list_screen.dart';
import 'package:offline/view/task_detail/task_detail_screen.dart';
import 'package:provider/provider.dart';
import 'package:safe_control/model/Task/TaskContentResult.dart';
import 'package:safe_control/view/CheckExecute/checkexec_list_content.dart';
import 'package:safe_control/view/plan_inspection/plan_list_content.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';

import '../../consts/color.dart';

import '../../consts/global_config.dart';

import '../../consts/share_prefers_key_const.dart';
import '../../model/CompanyInfo.dart';
import '../../model/configuration_item_model.dart';
import '../../model/home_config_model.dart';
import '../../model/message/MessageDetail.dart';
import '../../model/warehouse_info_model.dart';
import '../../model/warehouse_info_view_model.dart';
import '../../routes/routes.dart' as base_routes;
import '../../services/application.dart';
import '../../services/company_services.dart';
import '../../services/message_service.dart';
import '../../utils/request.dart';
import '../../view/message/message_detail.dart';
import '../../view/message/message_list.dart';
import '../../widgets/loading_dialog.dart';

const crossAxisCount = 4;

/// 工作台首页
class Platform extends StatelessWidget {
  final List userPowers;

  const Platform(this.userPowers);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: HomeContent(userPowers),
    );
  }
}

class HomeContent extends StatefulWidget {
  final List userPowers;

  const HomeContent(this.userPowers);

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

class _HomeContentState extends State<HomeContent> {
  bool isOffline = false;
  CompanyInfos company;
  String theme = '';
  int _unReadCount = 0;
  List userHaveToDo = [];

  @override
  void initState() {
    super.initState();
    initFunction();
    getUnreadCountMessage();
    getPatrolCountMessage();
  }

  Future<void> getUnreadCountMessage() async {
    await getUnreadCount().then((count) {
      setState(() {
        _unReadCount = count;
      });
    });
  }

  Future<void> getPatrolCountMessage() async {
    await getPatrolCount().then((count) {
      setState(() {
        userHaveToDo = count;
      });
    });
  }

  Future<void> initFunction() async {
    final SharedPreferences sp = await SharedPreferences.getInstance();
    theme = sp.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
    company = CompanyInfos.fromJson(json.decode(sp.get(SharePrefersKey.companyModelKey)));

    if (sp.getBool('offline') != null && sp.getBool('offline')) {
      isOffline = sp.getBool('offline');
    } else {
      String str = sp.get('permissionList');
      if (checkPermission('/app1', str)) {
        getCompanyInfo(context);
      }
    }
    setState(() {});
  }

  void getCompanyInfo(context) {
    Future.delayed(Duration.zero, () async {
      final SharedPreferences prefers = await SharedPreferences.getInstance();
      final result = prefers.getString(SharePrefersKey.companyModelKey);
      String orgCode = json.decode(result)['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((_) {});
    });
  }

  bool checkPermission(String permission, String permissionList) {
    if (permissionList == null || permissionList.isEmpty) {
      return false;
    }
    bool hasPermission = false;
    final List permissions = permissionList.split(',');
    if (permissions.isEmpty) {
      hasPermission = false;
    } else {
      permissions.forEach((f) {
        print(f);
        if (f == permission) {
          hasPermission = true;
        }
      });
    }
    return hasPermission;
  }

  // 获取数据
  Future<void> getData(context) async {
    Future.delayed(Duration.zero, () {
      showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              barrierDismissible: true,
            );
          });
      HttpRequest.getSelectCompany().then((res) {
        Navigator.of(context).pop();
        if (res['status'] == 200) {
          final _result = res['result'];
          Application.navigateToPath(context, base_routes.Routes.selectCompanyRole,
              params: {'extension': json.encode(_result)});
          // handleTurn(context,_result);
        }
      }).catchError((_) {
        Navigator.of(context).pop();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Stack(
      children: <Widget>[buildTopBar(context), ContentList(widget.userPowers, isOffline, userHaveToDo)],
    ));
  }

  Widget buildTopBar(context) {
    return Stack(
      children: <Widget>[
        Image.asset(
          'assets/images/home_top_bar_' + theme + '.png',
          fit: BoxFit.fitWidth,
        ),
        Container(
            margin: EdgeInsets.only(top: 34.px),
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 24.px, right: 24.px, top: 10.px, bottom: 5.px),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        width: 90.px,
                      ),
                      theme != 'red'
                          ? Image.asset(
                              'assets/images/home_top_logo.png',
                              fit: BoxFit.fitWidth,
                              width: 110,
                            )
                          : Image.asset(
                              'assets/images/colo.png',
                              fit: BoxFit.fitWidth,
                              width: 110,
                            ),
                      Container(
                        width: 90.px,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            Container(
                              child: GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Stack(
                                      children: <Widget>[
                                        Icon(
                                          Icons.message,
                                          color: Colors.white,
                                          size: 18.px,
                                        ),
                                        _unReadCount > 0
                                            ? Container(
                                                padding: const EdgeInsets.only(left: 14),
                                                child: const CircleAvatar(
                                                  radius: 3,
                                                  backgroundColor: Colors.red,
                                                ),
                                              )
                                            : Container()
                                      ],
                                    ),
                                  ],
                                  mainAxisAlignment: MainAxisAlignment.end,
                                ),
                                onTap: () {
                                  if (isOffline) {
                                    MsgBox.showMessageOnly('离线模式，该功能暂不支持。', context);
                                    return;
                                  }
                                  // MessageListPage
                                  Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
                                    return MessageListPage();
                                  })).then((v) {
                                    if (v) {
                                      getUnreadCountMessage();
                                    }
                                  });
                                },
                              ),
                              alignment: Alignment.centerRight,
                            ),
                            const Padding(
                              padding: EdgeInsets.only(right: 10),
                            ),
                            Container(
                                child: GestureDetector(
                              child: Image.asset('assets/images/home_bar_search.svg'),
                            )),
                            SvgButton(
                              src: 'assets/images/home_bar_search.svg',
                              size: 30.px,
                              imageSize: 18.px,
                              onTap: () {
                                if (isOffline) {
                                  MsgBox.showMessageOnly('离线模式，该功能暂不支持。', context);
                                  return;
                                }
                                Application.navigateTo(context, equipment_manage_routes.Routes.categoryDetailList);
                              },
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                    child: InkWell(
                        onTap: () {
                          if (isOffline) {
                            MsgBox.showMessageOnly('离线模式，该功能暂不支持。', context);
                            return;
                          }
                          getData(context);
                        },
                        child: Container(
                            width: MediaQuery.of(context).size.width - 20,
                            height: 30,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Consumer<WarehouseInfoViewModel>(
                                  builder: (ctx, warehouseVm, child) {
                                    String name = company?.companyName;
                                    return Text('${name ?? ''}',
                                        style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.white));
                                  },
                                ),
                                Container(
                                    //alignment: Alignment.topCenter,
                                    padding: EdgeInsets.only(
                                      top: 4.px,
                                    ),
                                    child: Image.asset(
                                      'assets/images/home_192.png',
                                      fit: BoxFit.fitWidth,
                                      width: 10,
                                    ))
                              ],
                            ))))
              ],
            )),
      ],
    );
  }
}

class ContentList extends StatefulWidget {
  final List userPowers;
  final bool isOffline;
  final List userHaveToDo;

  const ContentList(this.userPowers, this.isOffline, this.userHaveToDo);

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

class _ContentListState extends State<ContentList> {
  List<ConfigurationItemModel> data = [];
  final jpush = JPush();

  @override
  void initState() {
    super.initState();
    final usePowers = widget.userPowers;
    for (final json in usePowers) {
      data.add(ConfigurationItemModel.fromJson(json));
    }
    // 初始化极光推送
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    String platformVersion;
    jpush.addEventHandler(
      onReceiveNotification: (Map<String, dynamic> message) async {
        print('flutter onReceiveNotification: $message');
        print('extras info:' + message['extras']['cn.jpush.android.EXTRA']);
      },
      onOpenNotification: (Map<String, dynamic> message) async {
        print('flutter onOpenNotification: $message');
        String extrasMsg = message['extras']['cn.jpush.android.EXTRA'];
        print('extras info:' + extrasMsg);
        Map extras = json.decode(extrasMsg);

        // 页面跳转
        String id = extras['id'];
        String type = extras['type'];
        if (type == 'check') {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return CheckExecListContent(num.tryParse(id));
          }));
        } else if (type == 'task') {
          TaskContent taskContent = TaskContent.fromParams(id: num.tryParse(id));
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => TaskDetailPage(
                      task: taskContent,
                    )),
          );
        } else if (type == 'planBegin' || type == 'planWarn' || type == 'planEnd') {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => PlanListContent(num.tryParse(id))),
          );
        } else if (type == 'notify') {
          MessageDetail msg = await getMessageById(num.tryParse(id));
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MessageDetailPage(msg)),
          );
        }
      },
      onReceiveMessage: (Map<String, dynamic> message) async {
        print('flutter onReceiveMessage: $message');
      },
    );

    print('极光推送appKey >>>>>' + GlobalConfig.jpushKey);

    jpush.setup(
      appKey: GlobalConfig.jpushKey,
      channel: 'developer-default',
      production: false,
      debug: true,
    );
    jpush.getRegistrationID().then((rid) {
      print('推送测试getRegistrationID>>>>>' + rid);
    });

    jpush.applyPushAuthority(const NotificationSettingsIOS(sound: true, alert: true, badge: true));

    try {
      // 设置别名,可以实现给特定设备推送信息
      final prefs = await SharedPreferences.getInstance();
      String userName = prefs.getString('loginUser');
      String companyCode = prefs.getString('companyCode');
      List<String> tags = [];
      tags.add(companyCode);
      jpush.setAlias(userName).then((value) {});
      jpush.setTags(tags).then((value) {});
    } on Exception {
      platformVersion = 'Failed to get platform version.';
    }
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return data.isNotEmpty
        ? Padding(
            padding: EdgeInsets.only(left: 8.px, right: 8.px, top: 130.px, bottom: 12.px),
            child: MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: ListView(
                    shrinkWrap: true,
                    key: const PageStorageKey('data'),
                    children: List.generate(data.length, (index) {
                      return Column(
                        children: <Widget>[
                          CardContent(
                            model: data[index],
                            isOffline: widget.isOffline,
                            userHaveToDo: widget.userHaveToDo,
                          ),
                          //SizedBox(height: 12.px,),
                        ],
                      );
                    }).toList())),
          )
        : const Center(
            child: CircularProgressIndicator(),
          );
  }
}

class CardContent extends StatelessWidget {
  final HomeConfigModel config;
  final ConfigurationItemModel model;
  final List userHaveToDo;

  const CardContent({this.config, @required this.model, this.isOffline, this.userHaveToDo});

  final bool isOffline;

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6.px)),
      shadowColor: const Color.fromRGBO(69, 91, 99, 0.08),
      elevation: 4,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(16.px, 9.px, 0, 25.px),
            child: Text(
              model.permissionName,
              style: Theme.of(context).textTheme.headline4.copyWith(letterSpacing: 0.5),
            ),
          ),
          GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: model.children != null ? model.children.length : 0,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: crossAxisCount),
              itemBuilder: (ctx, index) {
                ConfigurationItemModel item = model.children[index];
                return InkWell(
                    onTap: () {
                      final params = {
                        'title': item.permissionName,
                        'category': '${model.frontComponent}',
                        'item': item.frontComponent ?? ''
                      };
                      if (isOffline) {
                        if (item.path == '/PlanPatrol') {
                          //OfflinePlanListScreen()
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return OfflinePlanListScreen();
                          }));
                        } else if (item.path == '/NoPlanPatrol') {
                          //OfflineNoPlanInspection()
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return OfflineNoPlanInspection();
                          }));
                        } else if (item.path == '/MoblePatrol') {
                          //OfflineMoveSpotListScreen()
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return OfflineMoveSpotListScreen();
                          }));
                        } else if (item.path == '/PatrolPoint') {
                          //OfflineInspectionSpotScreen()
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return OfflineInspectionSpotScreen();
                          }));
                        } else if (item.path == '/MyReceive') {
                          //OfflineHiderManageMyTaskPage()
                          Navigator.push(context, MaterialPageRoute(builder: (context) {
                            return OfflineHiderManageMyTaskPage();
                          }));
                        } else if (item.path == '/equipWareHousing') {
                          Application.navigateToPath(context, '/offlineEquipWareHousing', params: params);
                        } else if (item.path == '/createScrap') {
                          Application.navigateToPath(context, offline_routes.Routes.offlineCreateScrap, params: params);
                        } else if (item.path == '/fireAgentInStock') {
                          Application.navigateToPath(context, offline_routes.Routes.offlineFireAgentInStock,
                              params: params);
                        } else {
                          MsgBox.showMessageOnly('离线模式，该功能暂不支持。', context);
                          return;
                        }
                      } else {
                        Application.navigateToPath(context, item.path, params: params);
                      }
                    },
                    splashColor: Colors.transparent,
                    child: Stack(
                      children: [
                        Container(
                            alignment: Alignment.topCenter,
                            child: Column(
                              children: <Widget>[
                                base64Image(item.icon),
                                SizedBox(
                                  height: 5.px,
                                ),
                                Text(
                                  '${item.permissionName}',
                                  style: Theme.of(context).textTheme.bodyText1,
                                )
                              ],
                            )),
                        (item.permissionName == '计划巡检' && userHaveToDo.contains('planPatrol') ||
                                item.permissionName == '待处理' && userHaveToDo.contains('waitHandle'))
                            ? Container(
                                padding: const EdgeInsets.only(left: 22),
                                alignment: Alignment.topCenter,
                                child: const CircleAvatar(
                                  radius: 4,
                                  backgroundColor: Colors.red,
                                ),
                              )
                            : Container()
                      ],
                    ));
              }),
        ],
      ),
    );
  }

  Image base64Image(String icon) {
    if (icon != null && icon.isNotEmpty) {
      final base64 = icon.split(',')[1];
      Uint8List bytes = const Base64Decoder().convert(base64);
      if (bytes != null) {
        return Image.memory(
          bytes,
          fit: BoxFit.contain,
          gaplessPlayback: true,
          width: 40.px,
          height: 40.px,
        );
      } else {
        return Image.asset(
          'assets/images/icon_default.png',
          width: 40.px,
          height: 40.px,
        );
      }
    } else {
      return Image.asset(
        'assets/images/icon_default.png',
        width: 40.px,
        height: 40.px,
      );
    }
  }
}
