/*
 * @Author: XianKaiQun
 * @Date: 2020-04-21 15:59:53
 * @LastEditors: wuwei 
 * @LastEditTime: 2025-03-12 14:39:55
 * @Descripttion: 
 */

import 'dart:io';
import 'package:app_package/src/models/current_userinfo.dart';
import 'package:flutter/material.dart';

// import 'package:r_upgrade/r_upgrade.dart';
import 'package:app_package/app_package.dart';
import 'package:app_package/src/api/root.dart';
import 'package:app_package/src/assets.gen.dart';
import 'package:app_package/src/models/form_menu_id_detail.dart';
// import 'package:app_package/src/pages/dynamic_menu/index.dart';
// import 'package:app_package/src/pages/message/index.dart';
// import 'package:app_package/src/pages/mine/index.dart';
// import 'package:app_package/src/pages/work/index.dart';
// import 'package:oa_package/oa_package.dart' as oaPackage;
// import 'package:news_package/src/pages/sass_index/index.dart';
import 'package:mobx/mobx.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

import '../models/industry_news_list.dart';
part 'app.g.dart';

class AppGlobalStore = _AppGlobalStore with _$AppGlobalStore;

abstract class _AppGlobalStore with Store {
  _AppGlobalStore() {}
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  CommunityModel get currentCommunity => communityGlobalStore.data;

  String chargeMode = '';

  @computed
  CurrentUserinfoModel? get currentUserinfo => _currentUserinfo;

  @observable
  CurrentUserinfoModel? _currentUserinfo = CurrentUserinfoModel();
  @action
  _setCurrentUserinfo(CurrentUserinfoModel value) => _currentUserinfo = value;

  void setCurUserInfo(data) {
    _setCurrentUserinfo(data ?? CurrentUserinfoModel());
  }

  Future getMeterChargeMode() async {
    var res = await GlobalApi.getCommunityMeterChargeMode({
      'communityId': currentCommunity.id,
    });
    chargeMode = (res.data ?? null)!;
  }

  /// 已经催办列表 { 环节id: , 催办时间: ,}
  @observable
  ObservableList urgeList = ObservableList.of([]);

  get urgeIdList => urgeList.map((element) => element['id']).toList();
  @action
  onSetUrgeList(list) {
    urgeList = ObservableList.of(list);
  }

  List staticAppList = [
    {
      'name': '工作台',
      'icon': AssetList.$main_work_png_image,
      'acIcon': AssetList.$main_work1_png_image,
      'widget': 'work',
      'isNet': false,
    },
    {
      'name': '绘资讯',
      'icon': AssetList.$main_synergy_png_image,
      'acIcon': AssetList.$main_synergy1_png_image,
      'widget': 'sassnews',
      'isNet': false,
    },
    // {
    //   'name': '协同办公',
    //   'icon': AssetList.$main_synergy_png_image,
    //   'acIcon': AssetList.$main_synergy1_png_image,
    //   'widget': oaPackage.IndexPage(),
    //   'isNet': false,
    // },
    // {
    //   'name': '绘经营',
    //   'icon': AssetList.$main_business_png_image,
    //   'acIcon': AssetList.$main_business1_png_image,
    //   'widget': businessPackage.IndexPage(),
    // },
    {
      'name': '房管数据',
      'icon': AssetList.$main_msg_png_image,
      'acIcon': AssetList.$main_msg1_png_image,
      'widget': 'message',
      'isNet': false,
    },
    {
      'name': '我的',
      'icon': AssetList.$main_mine_png_image,
      'acIcon': AssetList.$main_mine1_png_image,
      'widget': 'mine',
      'isNet': false,
    },
  ];
  @observable
  ObservableList appList = ObservableList.of([]);

  @observable
  bool isPageSet = false;

  /// app页面设置列表
  @action
  Future getPageSettingList() async {
    var res = await RootApi.getAppPageSettingList();
    appList = ObservableList.of(staticAppList);

    /// 是否存在页面设置

    isPageSet = res.data?.appPageSet ?? false;
    return appList;
  }

  // getAppWiget(item) {
  //   switch (item.id) {
  //     /// 工作台
  //     case '512672712577089538':
  //       return WorkPage();

  //     /// 房管数据
  //     case '512672712577089537':
  //       return MessagePage();

  //     /// 我的
  //     case '512672712577089539':
  //       return MinePage();

  //     /// OA 已在首页去除
  //     case '512672712577089540':
  //       return oaPackage.IndexPage();

  //     /// 绘资讯
  //     default:
  //       return DynamicMenu(menuItem: item);
  //   }
  // }

  @observable
  Map currentPage = {};
  @action
  onSetCurrentPage(int index) {
    currentPage = appList[index];
  }

  var pageDetail;

  /// app页面设置详情
  Future getPageSetting(id) async {
    var data;

    PackageInfo packageInfo = await AppPackageInfo.instance.getPackageInfo();

    /// 版本号
    if (Platform.isAndroid) {
      data = {
        'androidMinimumVersion': packageInfo.version,
      };
    } else {
      data = {
        'iosMinimumVersion': packageInfo.version,
      };
    }
    var res = await RootApi.getAppPageSettingDetail(id, data);
    pageDetail = res.data;
    return pageDetail;
  }

  toRoutes(item, type) {
    switch (type) {
      // case 'oa':
      //   break;
      case 'menu':
        toMenuDetail(item);
        break;
      case 'intelligentForm':
        toFormDetail(item);
        break;
    }
  }

  FormMenuIdDetailModel? formDetail;
  toFormDetail(item) async {
    var res = await RootApi.getFormIdDetail(item.id);
    formDetail = res.data!;
    if (formDetail != null) {
      handleRoute(formDetail);
    }
  }

  handleRoute(item) async {
    /// 单次填报表单
    if (item.fillPeriodType == 'single') {
      var params = {
        'isPage': false,
        'formIdentification': item.formIdentification,
      };

      /// 屏蔽小区
      // params['communityId'] =
      //     currentCommunity != null && currentCommunity.id != null
      //         ? currentCommunity.id
      //         : null;
      var res = await RootApi.getMenuFormList(params);
      if (res.data != null && res.data!.length == 1) {
        toDetail(res.data![0], res.data![0].title);
      } else {
        toList(item);
      }
    } else {
      toList(item);
    }
  }

  /// 跳转详情
  toDetail(item, title) async {
    await WNavUtil.instance!.pushNamed(
      'message_detail',
      arguments: {
        'appBarTitle': item?.title,
        'item': item,
      },
    );
  }

  /// 跳转填报列表
  toList(item) async {
    await WNavUtil.instance!.pushNamed(
      'message_list',
      arguments: {
        'appBarTitle': item?.name,
        'item': item,
      },
    );
  }

  toMenuDetail(item) async {
    var _cmmunityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

    ///判断未开通
    if (!item.exist) {
      return WToastUtil.show('正在建设中...');
    }
    if (item.relationCommunity == true) {
      var boolean = await _cmmunityGlobalStore.intent;
      if (boolean) {
        if (item.route == 'qrcode/clean' || item.route == 'qrcode/security') {
          final context = WNavUtil.instance!.context;
          Route2business.scan2page(
            context: context!,
            scene: item.route == 'qrcode/clean'
                ? ScanScene.clean
                : ScanScene.security,
          );
        } else {
          WNavUtil.instance!
              .pushNamed(item?.route, arguments: {'appBarTitle': item?.name});
        }
      }
    } else if (item.route == 'qrcode/clean' ||
        item.route == 'qrcode/security') {
      final context = WNavUtil.instance!.context;
      Route2business.scan2page(
        context: context!,
        scene:
            item.route == 'qrcode/clean' ? ScanScene.clean : ScanScene.security,
      );
    } else {
      WNavUtil.instance!
          .pushNamed(item?.route, arguments: {'appBarTitle': item?.name});
    }
  }

  final scorllViewKey = GlobalKey<WisScrollViewState>();
  Map<String, dynamic> sassNewsparams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  @observable
  ObservableList<IndustryNewsListModel> sassNewslist = ObservableList.of([]);
  @action
  Future getSassNewsList({bool isLoad = true}) async {
    if (!isLoad) {
      sassNewsparams['pageNum'] = 1;
      sassNewslist = ObservableList.of([]);
    }
    var res = await RootApi.getIndexNews({
      'publishChannel': 1,
      'exhibitionArea': 2,
      'communityIds': currentCommunity.id,
      ...sassNewsparams,
    });
    final _data = res.data;
    List<IndustryNewsListModel> _list = [];
    if (res.data?.list != null) {
      res.data?.list?.forEach((item) {
        if (item.status == 1) {
          _list.add(item);
        }
        ;
      });
    }
    if (_list.length == 0) {
      scorllViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewKey.currentState?.isLast();
    } else {
      sassNewsparams['pageNum']++;
    }
    isLoad
        ? sassNewslist.addAll(_list)
        : sassNewslist = ObservableList.of(_list);
  }

  @observable
  ObservableList<IndustryNewsListModel> picList = ObservableList.of([]);

  @action
  Future getSassPicList() async {
    picList = ObservableList.of([]);
    var res = await RootApi.getIndexNews({
      'publishChannel': 1,
      'exhibitionArea': 1,
      'communityIds': currentCommunity.id,
    });

    List<IndustryNewsListModel> _list = [];
    if (res.data?.list != null) {
      res.data?.list?.forEach((item) {
        if (item.status == 1) {
          _list.add(item);
        }
        ;
      });
    }
    picList = ObservableList.of(_list);
  }

  Future onInitSassNewsList() async {
    getSassNewsList(isLoad: false);
    getSassPicList();
  }

  /// 直接增加阅读数，不请求接口
  @action
  addReadCount(id) async {
    List<IndustryNewsListModel> list = [];
    sassNewslist.forEach((item) {
      if (item.id == id) {
        item.viewCount = (item.viewCount ?? 0) + 1;
        list.add(item);
      } else {
        list.add(item);
      }
      ;
    });
    sassNewslist = ObservableList.of([]);
    sassNewslist = ObservableList.of(list);
  }
}
