// ignore_for_file: body_might_complete_normally_catch_error

/*
 * @Author: XianKaiQun
 * @LastEditors  : WuWei
 * @Date: 2020-11-04 16:54:35
 * @LastEditTime : 2023-08-17 10:44:57
 */

import 'dart:convert';
import 'dart:io';

import 'package:app_package/app_package.dart';
import 'package:app_package/src/api/message.dart';
import 'package:mobx/mobx.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

part 'push.g.dart';

///推送全局变量
class PushGlobalStore = _PushGlobalStore with _$PushGlobalStore;

///main函数中调用[WJpushUtil.setup],先注册极光且设置回调函数。
///
///然后再调用其他方法
///
///eg：
///在登录前后，登出前后调用相应方法操作[tags]
///
///登出后[stopPush]停止推送
///
///登录后[resumePush]恢复推送
///
abstract class _PushGlobalStore with Store {
  bool _init = false;
  @computed
  bool get isNewNotice => _isNewNotice;
  @observable
  bool _isNewNotice = false;

  @action
  setIsNewNotice(data) => _isNewNotice = data;

  // void logout() {

  // }

  ///在`main`中注册
  void setup() {
    // print('-------------------------------------push in store------------------------------');
    // if (_init) return;
    // _init = true;

    // bool _isReadPrivacy = WisStorageUtil.get(key: 'isReadPrivacy') ?? false;
    // print(_isReadPrivacy);
    // print('---------------------------------------------------------------------isReadPrivacy_in_PushGlobalStore--------------------------------');
    // // 检查用户是否同意隐私政策
    // if (!_isReadPrivacy) {
    //   print('---------------------------------------------------------------------用户未同意隐私政策，极光推送初始化已跳过--------------------------------------------------------------------');
    //   return;
    // }
    
    // WJpushUtil.instance!.setup(
    //   appKey: APPConfig.jpushKey,
    //   debug: false,
    //   production: APPConfig.isProdEnv!,
    //   onReceiveMessage: (map) async {},
    //   onReceiveNotification: (map) async {
    //     _onReceiveNotification(map);
    //   },
    //   onOpenNotification: _onOpenNotification,
    // );

    // final authGlobalStore = GetIt.I.get<AuthGlobalStore>();

    // ///添加登录时监听。
    // ///别名`alias`设置为`用户id`,
    // ///标签`tags`是一个字符串
    // Future<void> _addLoginListener() async {
    //   final userId = WisStorageUtil.get(key: 'storage-user-id');
    //   final entCode = WisStorageUtil.get(key: 'storage-user-entCode');
    //   WJpushUtil.instance!.setAlias('$userId').catchError((e) {print(e);});
    //   //`tag`添加企业号encode
    //   WJpushUtil.instance!.addTags(['$entCode']).catchError((e) {print(e);});
    //   await WJpushUtil.instance!.getRegistrationID;
    // }

    // ///与[_addLoginListener]相反的退出登录监听
    // void _addLogoutListener() {
    //   final entCode = WisStorageUtil.get(key: 'storage-user-entCode');

    //   WJpushUtil.instance!.deleteAlias().catchError((e) {print(e);});
    //   WJpushUtil.instance!.deleteTags(['$entCode']).catchError((e) {print(e);});
    // }

    // authGlobalStore.addLoginListener(_addLoginListener);
    // authGlobalStore.addLogoutListener(_addLogoutListener);
  }

  Future _onReceiveNotification(Map map) async {
    // WorkStore(context).
    setIsNewNotice(true);
  }

  ///点击推送监听
  ///格式如下所示
  ///`content`会随着`type`的变化而变化，
  ///
  //  {
  //   'alert': '18889187408提交了报事：18889187408，请尽快处理!',
  //   'title': "新的报事",
  //   'extras': {
  //     'cn.jpush.android.ALERT_TYPE': ' -1',
  //     'cn.jpush.android.NOTIFICATION_ID': '518325102',
  //     'cn.jpush.android.MSG_ID': '54043295233262155',
  //     'cn.jpush.android.ALERT': '18889187408提交了报事：18889187408，请尽快处理!',
  //     'cn.jpush.android.EXTRA': {
  //       "content": {"id": "360379567538216960"},
  //       "type": "REPORT"
  //     }
  //   },
  // };
  Future _onOpenNotification(Map map) async {
    Map? obj = {};

    try {
      if (Platform.isAndroid) {
        final extras = map['extras'];
        if (extras != null) {
          final extra = extras['cn.jpush.android.EXTRA'];
          obj = jsonDecode(extra);
        }
      } else if (Platform.isIOS) {
        final extra = map['extras'];
        if (extra != null) {
          obj = Map.of(extra);
        }
      }
    } catch (e) {
      return;
    }

    final String? type = obj!['type'];
    if (type == null) {
      return;
    }

    final content = obj['content'];
    jumpByType(type, content, true);
  }

  void jumpByType(type, content, isRead) {
    ///根据type进行响应
    switch (type) {
      case 'TASK_BATCH_WAIT_RECEIVE': // 批量待领取
        if (content == null) break;
        WNavUtil.instance!.pushNamed('task/hall');
        break;
      case 'REPORT': //跳转报事
      case 'REPORT_DISPATCH': //报事派单
      case 'REPORT_MULTI_LEVEL_RESPONSE': //多级响应
      case 'REPORT_CC': //抄送
        if (content == null || content['id'] == null) break;
        WNavUtil.instance!.pushNamed('report/detail', arguments: {
          'id': content['id'],
          'communityId': content['communityId'],
          'index': 0,
        });
        break;
      case 'REPORT_DIALOG': //报事消息回复
        if (content == null || content['id'] == null) break;
        WNavUtil.instance!.pushNamed('report/detail', arguments: {
          'id': content['id'],
          'communityId': content['communityId'],
          'index': 1,
        });
        break;
      case 'REPAIR': //跳转报修
      case 'REPAIR_DISPATCH': //报修派单
      case 'REPAIR_MULTI_LEVEL_RESPONSE': //多级响应
      case 'REPAIR_CC': //抄送
        if (content == null || content['id'] == null) break;
        WNavUtil.instance!.pushNamed('repair/detail', arguments: {
          'id': content['id'],
          'communityId': content['communityId'],
          'index': 0,
        });
        break;
      case 'REPAIR_DIALOG': //报修消息回复
        if (content == null || content['id'] == null) break;
        WNavUtil.instance!.pushNamed('repair/detail', arguments: {
          'id': content['id'],
          'communityId': content['communityId'],
          'index': 1,
        });
        break;

      /// (任务待领取 TASK_WAIT_RECEIVE； 任务领取  TASK_RECEIVE； 任务即将开始  TASK_STARTING_JOB； 任务即将超时  TASK_THE_TIMEOUT；任务即将超时-推送给创建人 TASK_THE_TIMEOUT_TO_CREATE_BY；任务即将逾期  TASK_THE_OVERDUE ；任务即将逾期-推送给创建人 TASK_THE_OVERDUE_TO_CREATE_BY 任务催办 TASK_URGE
      case 'TASK_CC': //任务抄送
      case 'TASK_ADD': //新任务
      case 'TASK_START': //任务开始执行
      case 'TASK_END': //任务结束
      case 'TASK_WAIT_RECEIVE':
      case 'TASK_RECEIVE':
      case 'TASK_STARTING_JOB':
      case 'TASK_THE_TIMEOUT':
      case 'TASK_DELETED':
      case 'TASK_THE_TIMEOUT_TO_CREATE_BY':
      case 'TASK_THE_OVERDUE':
      case 'TASK_THE_OVERDUE_TO_CREATE_BY':
      case 'TASK_NODE_ABNORMAL_TO_CREATE_BY':
      case 'TASK_OVERDUE_PENALTY':
      case 'TASK_TIMEOUT_PENALTY':
      case 'TASK_TERMINATION':
      case 'TASK_URGE':
      case 'TASK_NODE_ABNORMAL_TO_SUPERVISOR':
      case 'TASK_NODE_ABNORMAL':
      case 'TASK_THE_TIMEOUT_TO_SUPERVISOR':
        if (content == null ||
            content['id'] == null ||
            content['isChild'] == null) break;
        WNavUtil.instance!.pushNamed('task/detail', arguments: {
          'id': content['id'],
          'isChild': content['isChild'],
          'communityId': content['communityId'],
        });
        break;
      case 'FACE_WAIT_AUDITED':
        WNavUtil.instance!.pushNamed('face/detail', arguments: {
          'id': content['id'],
          'communityId': content['communityId'],
        });
        break;
      case 'PAYMENT_SUCCESS':
        WNavUtil.instance!.pushNamed('paylist/detail', arguments: {
          'id': content['id'],
          'communityId': content['communityId'],
          'billType': {'code': content['billType']}
        });
        // WNavUtil.instance!.pushNamed('paylist/index', arguments: {
        //   'id': content['id'],
        //   'communityId': content['communityId'],
        //   'billType': {'code': content['billBehavior']}
        // });
        break;

      case 'BILL_BATCH_CREATE':
        WNavUtil.instance!.pushNamed('bill/index', arguments: {
          'id': content['id'],
          'communityId': content['communityId'],
        });
        break;
      default:
        break;
    }
  }

  /// 已读单条消息
  Future putReadMessage(id) async {
    await MessageApi.putSingleMessageRead({
      'id': id,
    });
  }
}
