import 'package:cpt_notice_board/modules/notice_board/page/notice_board_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/basic_export.dart';
import 'package:plugin_basic/modules/global_web_page.dart';
import 'package:plugin_platform/engine/image/image_preview.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/file_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/widget_export.dart';
import 'package:cs_resources/generated/assets.dart';

import '../../../router/page/notice_board_page_router.dart';
import '../vm/documents_list_vm.dart';

@RoutePage()
class DocumentsListPage extends HookConsumerWidget {
  final int? id;

  const DocumentsListPage({Key? key, @PathParam('id') required this.id}) : super(key: key);

  //启动当前页面
  static void startInstance({
    BuildContext? context,
    int? id,
  }) {
    if (context != null) {
      context.router.push(DocumentsListPageRoute(id: id));
    } else {
      appRouter.push(DocumentsListPageRoute(id: id));
    }
  }

  Widget _buildItemLeftSection(BuildContext context, WidgetRef ref, item, _vm) {
    return Container(
      // color: Colors.blue,
      child: Text(
        item['name'],
        maxLines: 2, // 设置最大行数为2
        overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
        style: TextStyle(fontSize: 16.0, color: context.appColors.textBlack, fontWeight: FontWeight.w700), // 设置字体大小
      ),
    ).marginOnly(right: 17.5);
  }

  Widget _buildItemRightSection(BuildContext context, WidgetRef ref, item, _vm) {
    return Container(
      color: Colors.white,
      child: TextButton(
        onPressed: () {},
        style: TextButton.styleFrom(
          foregroundColor: context.appColors.textBlack,
          backgroundColor: context.appColors.tabBgSelectedPrimary,
          // 背景颜色
          minimumSize: const Size(91.5, 30),
          // 最小宽度和高度
          padding: const EdgeInsets.symmetric(horizontal: 11.0, vertical: 9),
          // 内边距
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5), // 圆角
            side: const BorderSide(
              color: AppColorsTheme.colorPrimary,
              width: 1.0,
            ), // 边框
          ),
        ),
        child: Text(
          S.current.open_folder,
          style: TextStyle(
            color: context.appColors.textWhite,
          ),
        ),
      ),
    );
  }

  // list item
  Widget _buildSaleItem(BuildContext context, WidgetRef ref, item, _vm) {
    String url = item['url'];
    return Container(
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: const BorderRadius.all(Radius.circular(6.0)),
        boxShadow: [
          BoxShadow(
            color: context.appColors.itemBGShadow,
          )
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            width: MediaQuery.of(context).size.width - 30,
            height: 70,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(child: _buildItemLeftSection(context, ref, item, _vm)),
                Container(
                    // width: 120,
                    // child: _buildItemRightSection(context, ref, item, _vm),
                    // child: TextButton(onPressed: (){}, child: Text("fdsfds")),
                    ),
              ],
            ).paddingOnly(left: 20, right: 20),
          ).constrained(
            minHeight: 70,
          ),
        ],
      ).onTap(() {
        // 去详情
        // _vm.launchURL(url);
        _previewFile(context, item['name'], url);
      }),
    ).marginOnly(left: 15, bottom: 15, right: 15);
  }

  //预览Url
  void _previewFile(BuildContext context, String title, String url) async {
    final fileType = FileUtils.getFileType(url);

    switch (fileType) {
      case FileType.image:
        ImagePreviewEngine.singleImagePreview(context, url);
        break;
      case FileType.document:
        GlobalWebPage.startInstance(context: context, title: title, url: "https://docs.google.com/gview?embedded=true&url=$url");
        break;
      case FileType.unknown:
      default:
        // 处理未知类型，比如直接打开链接
        if (await canLaunchUrl(Uri.parse(url))) {
          await launchUrl(Uri.parse(url));
        } else {
          ToastEngine.show("Could not launch $url");
        }
        break;
    }
  }

  // list
  Widget _buildSaleList(BuildContext context, WidgetRef ref, _vm) {
    final state = ref.watch(documentsListVmProvider);
    return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
      return _buildSaleItem(context, ref, state.list![index], _vm);
    }, childCount: state.list!.length));
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(documentsListVmProvider.notifier);
    final state = ref.watch(documentsListVmProvider);
    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData(id: id));
      return () {
        // 组件卸载时执行
        Log.d("DocumentsListPage 组件卸载时执行");
      };
    }, []);
    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.documents,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      body: Container(
          child: EasyRefresh(
              controller: vm.refreshController,
              // 上拉加载
              onLoad: () async {
                Log.d("----onLoad");
                vm.loadMore();
              },
              // 下拉刷新
              onRefresh: () async {
                Log.d("----onRefresh");
                vm.onRefresh();
              },
              child: Container(
                color: context.appColors.backgroundDark,
                padding: const EdgeInsets.only(top: 15),
                child: LoadStateLayout(
                  state: state.loadingState,
                  errorMessage: state.errorMessage,
                  errorRetry: () {
                    vm.retryRequest();
                  },
                  successSliverWidget: [_buildSaleList(context, ref, vm)],
                ),
              ))),
    );
  }
}
