reading_page.dart 9.7 KB
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:wow_english/common/extension/string_extension.dart';
import 'package:wow_english/pages/reading/widgets/ReadingModeType.dart';
import 'package:wow_english/pages/reading/widgets/reading_dialog_widget.dart';
import 'package:wow_english/route/route.dart';

import '../../common/core/app_consts.dart';
import '../../common/core/user_util.dart';
import '../../common/widgets/recorder_widget.dart';
import '../../common/widgets/speaker_widget.dart';
import '../../models/course_process_entity.dart';
import '../../utils/log_util.dart';
import 'bloc/reading_bloc.dart';

///绘本页
class ReadingPage extends StatelessWidget {
  const ReadingPage({super.key, this.courseLessonId, this.moduleColor});

  final String? courseLessonId;

  final Color? moduleColor;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => ReadingPageBloc(
          context, PageController(), courseLessonId ?? '', moduleColor)
        ..add(InitBlocEvent())
        ..add(RequestDataEvent())
        ..add(XSVoiceInitEvent({
          'appKey': AppConsts.xsAppKey,
          'service': AppConsts.xsAppService,
          'secretKey': AppConsts.xsAppSecretKey,
          'userId': UserUtil.getUser()!.id.toString(),
        })),
      child: _ReadingPage(),
    );
  }
}

class _ReadingPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocListener<ReadingPageBloc, ReadingPageState>(
      listener: (context, state) {
        Log.d('reading BlocListener=$state');
        if (state is RequestDataState) {
          ///刷新页面
          context.read<ReadingPageBloc>().add(CurrentPageIndexChangeEvent(0));
        }
        if (state is FeedbackState) {
          showDialog<ReadingDialog>(
              context: context,
              barrierDismissible: false,
              builder: (context) {
                return const ReadingDialog();
              });
        }
      },
      child: _readingPageView(),
    );
  }

  Widget _readingPageView() =>
      BlocBuilder<ReadingPageBloc, ReadingPageState>(builder: (context, state) {
        final bloc = BlocProvider.of<ReadingPageBloc>(context);
        return Container(
          color: Colors.white,
          child: Stack(
            children: [
              PageView.builder(
                  itemCount: bloc.dataCount(),
                  controller: bloc.pageController,
                  onPageChanged: (int index) {
                    bloc.add(CurrentPageIndexChangeEvent(index));
                  },
                  itemBuilder: (context, int index) {
                    return _readingPagerItem(bloc.entity!.readings![index]);
                  }),
              Container(
                color: Colors.transparent,
                height: kToolbarHeight,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Padding(
                      padding:
                          EdgeInsets.only(left: ScreenUtil().bottomBarHeight),
                      child: IconButton(
                          onPressed: () {
                            popPage(data: {
                              'currentStep': bloc.currentPage,
                              'courseLessonId': bloc.courseLessonId,
                              'isCompleted': bloc.isLastPage(),
                            });
                          },
                          icon: Image.asset(
                            'back_around'.assetPng,
                            width: 40.w,
                            height: 40.h,
                          )),
                    ),
                    Container(
                      height: 10.h,
                      width: 150.w,
                      alignment: Alignment.center,
                      child: LinearPercentIndicator(
                        animation: true,
                        lineHeight: 10.h,
                        animationDuration: 250,
                        animateFromLastPercent: true,
                        percent: bloc.dataCount() > 0
                            ? bloc.currentPage / bloc.dataCount()
                            : 0,
                        // center: Text('$progress/$total}'),
                        barRadius: const Radius.circular(5),
                        progressColor: bloc.moduleColor,
                      ),
                    ),

                    Padding(
                      padding: EdgeInsets.only(
                          right: 15.w + ScreenUtil().bottomBarHeight),
                      child: GestureDetector(
                        onTap: () {
                          bloc.add(CurrentModeChangeEvent());
                        },
                        child: SizedBox(
                          height: 40.h,
                          child: Container(
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage('bg_reading_mode'.assetPng),
                                  fit: BoxFit.fill),
                            ),
                            alignment: Alignment.center,
                            padding: EdgeInsets.symmetric(horizontal: 10.w),
                            child: Text(
                              bloc.currentMode == ReadingModeType.auto
                                  ? '设为手动'
                                  : '设为自动',
                              style: TextStyle(fontSize: 14.5.sp),
                            ),
                          ),
                        ),
                      ),
                    ),

                    // ScreenUtil().bottomBarHeight.horizontalSpace,
                  ],
                ),
              ),
              Align(
                alignment: Alignment.bottomLeft,
                child: Container(
                  color: const Color(0xCCFFFFFF),
                  child: Row(
                    children: [
                      5.horizontalSpace,
                      SpeakerWidget(
                        isPlaying:
                            bloc.voicePlayState == VoicePlayState.playing &&
                                bloc.isOriginAudioPlaying,
                        // 控制动画播放
                        isClickable: !bloc.isRecording,
                        // 控制是否可点击
                        width: 42.w,
                        height: 42.w,
                        onTap: () {
                          bloc.add(PlayOriginalAudioEvent(null));
                        },
                      ),
                      SizedBox(
                        width: 10.w,
                      ),
                      Expanded(
                        child: RichText(
                          text: TextSpan(
                            style: DefaultTextStyle.of(context).style,
                            children: bloc.displayContent(),
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      SizedBox(
                        width: 10.w,
                      ),
                      RecorderWidget(
                        isPlaying: bloc.isRecording,
                        width: 54.w,
                        height: 54.w,
                        onTap: () {
                          if (bloc.isRecording) {
                            bloc.add(XSVoiceStopEvent());
                          } else {
                            bloc.add(XSVoiceStartEvent(bloc.readingContent(),
                                '0', UserUtil.getUser()?.id.toString()));
                          }
                        },
                      ),
                      GestureDetector(
                          onTap: () {
                            if (bloc.isRecording) {
                              return;
                            }
                            bloc.add(PlayRecordAudioEvent());
                          },
                          child: Visibility(
                            visible: bloc.currentPageData()?.recordUrl != null,
                            child: Image.asset(
                              bloc.isRecordAudioPlaying
                                  ? 'record_pause'.assetWebp
                                  : 'record_play'.assetWebp,
                              height: 35.h,
                              width: 35.h,
                            ),
                          )),
                      // RecorderPlaybackWidget(
                      //   isClickable: !bloc.isRecording && bloc.currentPageData()?.recordUrl != null,
                      //   isPlaying: bloc.isRecordAudioPlaying,
                      //   width: 42.w,
                      //   height: 42.w,
                      //   onTap: () {
                      //     bloc.add(PlayRecordAudioEvent());
                      //   },
                      // )
                      SizedBox(
                        width: 10.w,
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      });

  Widget _readingPagerItem(CourseProcessReadings readings) =>
      BlocBuilder<ReadingPageBloc, ReadingPageState>(builder: (context, state) {
        return Stack(
          children: [
            Positioned.fill(
              child: Image.network(readings.picUrl ?? '', fit: BoxFit.cover),
            ),
          ],
        );
      });
}