import 'dart:io';

import 'package:badges/badges.dart';
import 'package:disable_screenshots/disable_screenshots.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hyzp_ybqx/components/dioFun.dart';
import 'package:hyzp_ybqx/components/hyxx_data_handle.dart';
import 'package:hyzp_ybqx/pages/tabs/page4_myMsics_new.dart';

//import '../../widget/player_pro.dart';
import '../../components/commonFun.dart';

//import 'package:fijkplayer/fijkplayer.dart';
import '../../services/ServiceLocator.dart';
import '../../services/Storage.dart';
import 'page1_work.dart';
import 'package:audioplayers/audio_cache.dart';

class Tabs extends StatefulWidget {
  Tabs({Key key, this.arguments = 0}) : super(key: key);
  int arguments;

  _TabsState createState() => _TabsState();
}

class _TabsState extends State<Tabs> {
  // 初始化插件
  DisableScreenshots _watermarkPlugin = DisableScreenshots();

  //try_setState();   //避免如下异常报错
  try_setState() {
    try {
      if (mounted) {
        setState(() {});
        //区县用户登录接口增加返回字段“sfsy”，0表示正式账号，1表示试用账号
        // print(g_userInfo.mapUserInfo);
        // qx_trial_tag = 1; // 测试用
        // if (1 == qx_trial_tag || 511527 == qx_code) {  // 测试用
        if (1 == qx_trial_tag) {
          print('addWatermark');
          // 添加默认样式的水印
          _watermarkPlugin.addWatermark(context, "黑烟抓拍试用版", rowCount: 4, columnCount: 8);
          // _watermarkPlugin必须放在这里，放在Widget build(BuildContext context)函数中会报错：
          // Dart Unhandled Exception: setState() or markNeedsBuild() called during build.
        } else {
          print('removeWatermark');
          _watermarkPlugin.removeWatermark();
        }
      }
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  int _currentIndex = 0;
  String sAppBar0 = 'Flutter Demo';
  String sAppBar = 'Flutter Demo';
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    getlistItems().then((value) => try_setState());
    print('widget.arguments = ${widget.arguments}');
    //_currentIndex = 3 == widget.arguments ? 0 : widget.arguments; //解决"我的"页面根据用户所属组及时刷新问题
    _currentIndex = widget.arguments;
    this._pageController = PageController(initialPage: _currentIndex);
    // 注册服务
    setupLocator();

    // 解决登录按钮再次变换文字的问题
    Future.delayed(const Duration(milliseconds: 1000), () {
      //重新初始化处理延时登录的变量
      //bMayLogin = false;  //这句必须注释掉，否则“退出登录”后，无法再次进行用户名登录
      bPreLoading = false;
      bLoginVerify = false; //处理延时登录，判断用户名登录是否验证通过
    });

    init();
  }

  init() async {
    // // 从磁盘读取变量
    // g_bVoiceRemind = await Storage.getBool('bVoiceRemind');
    // g_bVoiceRemind = (null == g_bVoiceRemind) ? false : g_bVoiceRemind;
    // // print('g_bVoiceRemind = $g_bVoiceRemind');
    // eventBus.fire(VoiceRemindUpdate('g_bVoiceRemind 数据已更新'));

    // 获取待审核黑烟车记录
    print("listReviewed = $listReviewed");
    await getReviewedList();  //注意：访问区县后台接口，需要统一添加区县代码参数
    print("listReviewed = $listReviewed");
    if (g_bVoiceRemind && listReviewed.length > 0) {
      // if (g_bVoiceRemind) {
      // import 'dart:io';
      // import 'package:audioplayers/audio_cache.dart';
      // print("播放：语音提醒.mp3");
      AudioCache().play(File('audio/语音提醒.mp3').path); //语音提醒
    }
  }

  double _activeIconWidth = 68;

  Future getlistItems() async {
    listItems.addAll([
      BottomNavigationBarItem(
          icon: getImageItem('assets/images/矢量智能对象.png'),
          label: "首页",
          activeIcon: getImageItem('assets/images/矢量智能对象.png',
              width: _activeIconWidth, color: Colors.blue)),
      BottomNavigationBarItem(
          icon: getImageItem('assets/images/矢量智能对象(1).png'),
          label: "统计",
          activeIcon: getImageItem('assets/images/矢量智能对象(1).png',
              width: _activeIconWidth, color: Colors.blue)),
      BottomNavigationBarItem(
          icon: getImageItem('assets/images/矩形 1 拷贝 39.png'),
          label: "设备",
          activeIcon: getImageItem('assets/images/矩形 1 拷贝 39.png',
              width: _activeIconWidth, color: Colors.blue)),
      //bNewVer：是否发现新版本
      BottomNavigationBarItem(
          icon: getImageItem('assets/images/我的.png', bBadge: bNewVer),
          label: "我的",
          activeIcon: getImageItem('assets/images/我的.png',
              width: _activeIconWidth, color: Colors.blue, bBadge: bNewVer)),
    ]);
  }

  // 添加底部导航栏图标的小红点
  Widget getImageItem(String imagePath,
      {double width = 56,
      Color color = const Color.fromRGBO(131, 131, 131, 1),
      bool bBadge = false}) {
    return bBadge
        ? Badge(
            position: BadgePosition.topEnd(top: -4, end: -9),
            badgeContent: null,
            child: Image.asset(imagePath,
                width: ScreenUtil().setWidth(width), fit: BoxFit.cover, color: color))
        : Image.asset(imagePath,
            width: ScreenUtil().setWidth(width), fit: BoxFit.cover, color: color);
  }

  List<BottomNavigationBarItem> listItems = [];

  //该美工优化的页面 Page1_Works，是供多个页面共享的代码框架。不同的页面以 PageType 字段进行区分
  //String pageType = ''; //'home_page'、'statis_page'、'device_page'
  List<Widget> _pageList = [
    Page1_Works(pageType: 'home_page', title: '黑烟车抓拍系统'),
    Page1_Works(pageType: 'statis_page', title: '    统计信息'),
    Page1_Works(pageType: 'device_page', title: '    设备管理'),
    //Page2_StatisticsNew(),
    //Page3_Device(),
    //Page4_MyMsics(),
    Page4_MyMsicsNew(pageType: 'my_page', title: '        我的'),
  ];

  Text _getName(index) {
    return Text(this.sAppBar0 + ' - ' + this.listItems[_currentIndex].label);
  }

  @override
  Widget build(BuildContext context) {
    sizeWindowPhysicalSize = MediaQuery.of(context).size;

    return Scaffold(
      // appBar: _currentIndex!=3?:AppBar(
      //   title: Text("用户中心"),
      // ),
      resizeToAvoidBottomPadding: false, //解决输入法键盘弹出越界问题-OK
      appBar: PreferredSize(
          child: AppBar(
            //title: Text("Flutter Demo"),
            title: listItems.isEmpty ? Text('') : _getName(this._currentIndex),
          ),
          preferredSize: Size.fromHeight(0) //Flutter——设置appBar的高度
          ),
      //底部导航栏，使用PageView方式，在App启动时只加载显示页面，启动时没有警告报错。可以配置每个页面的是否保持状态，更为灵活，也更复杂一些
      body: PageView(
        controller: this._pageController,
        children: this._pageList,
        onPageChanged: (index) {
          setState(() {
            this._currentIndex = index;
            //label: "我的"
            //eventBus.fire(GroupIdUpdateEvent('g_userInfo.userGroupIDlist 数据已更新')); //这样刷新有效
            // if (3 == index) {
            // }
          });
        },
        physics: NeverScrollableScrollPhysics(), //禁止pageView滑动
      ),
      //底部导航栏，使用IndexedStack方式，是在App启动时便一次性加载所有页面，启动时有警告报错。所有页面的状态都会保持
//      body: IndexedStack(
//        index: _currentIndex,
//        children: this._pageList,
//      ),
      bottomNavigationBar: listItems.isEmpty
          ? Text('')
          : BottomNavigationBar(
              currentIndex: _currentIndex,
              onTap: (index) {
                //eventBus.fire(GroupIdUpdateEvent('g_userInfo.userGroupIDlist 数据已更新')); //这样刷新有效
                g_iIndex = index;
                Storage.setString('tabs_index', g_iIndex.toString());
                setState(() {
                  this._currentIndex = index;
                  this._pageController.jumpToPage(index);

                  // if (1 == index && bPlaying) {
                  //   if (player.value.videoRenderStart && player.state == FijkState.paused) {
                  //     player.start();
                  //   }
                  // } else {
                  //   //若player并未初始化播放，调用会报错：The method 'changePlayerState' was called on null.
                  //   if (player.value.videoRenderStart && player.state == FijkState.started) {
                  //     bPlaying = true;
                  //     player.pause();
                  //   }
                  // }
                });
              },
              iconSize: ScreenUtil().setSp(70),
              //icon的大小
              fixedColor: Colors.blueAccent,
              type: BottomNavigationBarType.fixed,
              items: listItems,
            ),
    );
  }
}
