/*
 * @Author       : WuWei
 * @LastEditors: wjc
 * @Date         : 2021-04-27 09:42:49
 * @LastEditTime: 2023-01-16 15:11:26
 * @FilePath     : /wisdom-huiguanjia-app/task_package/lib/src/pages/index/index.dart
 * @Description  : 任务管理-入口页
 */
import 'dart:async';
import 'package:get/get.dart';
// import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'as e;
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:task_package/src/components/last.dart';
import 'package:task_package/src/components/sticky_tab_bar.dart';
import 'package:task_package/src/components/task_item.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../../../src/assets.gen.dart';
import '../../../src/view_models/index_store.dart';
import '../../../src/view_models/filter_store.dart';
part 'index.g.dart';
part 'components/tabbar.dart';
part 'components/search.dart';
part 'components/statistic.dart';
part 'components/mine.dart';
part 'components/copy.dart';
part 'components/department.dart';
part 'components/operate.dart';
part 'components/notice.dart';
part 'components/dropdown_filter.dart';
part 'components/to_others.dart';
part 'components/transfer.dart';

///路由传递的参数
class IndexPageArguments {
  final String? appBarTitle;
  IndexPageArguments({this.appBarTitle});

//***以下为模板代码谨慎修改***
  factory IndexPageArguments.fromJson(Map<String, dynamic> json) {
    return _$IndexPageArgumentsFromJson(json);
  }
  factory IndexPageArguments.fromRouteArguments(BuildContext context) {
    return _$IndexPageArgumentsFromJson(
        (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>);
  }
  Map<String, dynamic> toJson() => _$IndexPageArgumentsToJson(this);
}

//***以下为模板代码谨慎修改***
class IndexPage extends StatelessWidget {
  const IndexPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => IndexStore(context)),
      ],
      child: IndexView(),
    );
  }
}

class IndexView extends StatelessWidget {
  const IndexView({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    IndexStore store = Provider.of<IndexStore>(context, listen: true);
    final colorScheme = WTheme.of(context).colorScheme;
    return Scaffold(
      appBar: WAppBar(
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        title: WisText(
          '${store.arguments.appBarTitle ?? '任务工单'}',
          size: 19.pt,
          weight: FontWeight.w600,
          color: colorScheme.mainTitle,
        ),

        /// 顶部按钮
        actions: <Widget>[
          Wisdom.row(
            children: <Widget>[
              Wisdom(
                onTap: () => Navigator.pushNamed(context, 'task/statistic'),
                margin: EdgeInsets.only(right: 15.pt),
                child: Image(
                  image: AssetList.$datas_png_image,
                  height: 28.pt,
                ),
              ),
              Wisdom(
                onTap: () => store.toTaskAdd(),
                margin: EdgeInsets.only(right: 15.pt),
                child: Image(
                  image: AssetList.$plus_png_image,
                  height: 28.pt,
                ),
              ),
            ],
          ),
        ],
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: _BuildBody(),
      ),
      // bottomSheet: _BuildBottomBar(),
      floatingActionButton: !store.showToTopBtn
          ? null
          : FloatingActionButton(
              child: Icon(Icons.arrow_upward),
              onPressed: () {
                //返回到顶部时执行动画
                store.outerController.animateTo(
                  .0,
                  duration: Duration(milliseconds: 200),
                  curve: Curves.ease,
                );
              }),
    );
  }
}

class _BuildBody extends StatefulWidget {
  _BuildBody({Key? key}) : super(key: key);

  @override
  __BuildBodyState createState() => __BuildBodyState();
}

class __BuildBodyState extends State<_BuildBody>
    with SingleTickerProviderStateMixin {
  IndexStore get store => Provider.of(context, listen: false);

  final FilterStore filterStore = Get.isRegistered<FilterStore>()
      ? Get.find<FilterStore>()
      : Get.put(FilterStore());

  @override
  void initState() {
    store.onInit();
    store.tabController = TabController(
      vsync: this,
      length: 6,
      initialIndex: store.tabIndex,
    );
    store.tabController!.addListener(() {
      if (store.tabController!.index != store.tabIndex) {
        store.onSetTabIndex(store.tabController!.index);
      }
    });
    setState(() {});
    super.initState();
  }

  @override
  void dispose() {
    Get.delete<FilterStore>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    final store = Provider.of<IndexStore>(context, listen: true);

    return NestedScrollView(
      controller: store.outerController,
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [
          _BuildNoticeBlock(),
          new _BuildSearchInput(
            title: store.taskTitle,
            onInput: (v) => store.onSearchTaskTitles(v),
            onCancel: () => store.onSearchTaskTitles(''),
          ).asSliver(),
          SliverToBoxAdapter(
            child: Wisdom(
              height: 44.pt,
              color: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 5.pt),
              child: Wisdom.row(
                children: [
                  CustomScrollView(scrollDirection: Axis.horizontal, slivers: [
                    SliverToBoxAdapter(
                      child: Wisdom.row(
                        children: [
                          for (var i = 0; i < store.statusList.length; i++)
                            Observer(builder: (_) {
                              return Wisdom(
                                borderRadius: BorderRadius.circular(4.pt),
                                color: Color(0xFFF6F7FC),
                                padding: EdgeInsets.symmetric(
                                  horizontal: 8.5.pt,
                                  vertical: 5.pt,
                                ),
                                onTap: () => store
                                    .filterStatus(store.statusList[i]['code']!),
                                margin: EdgeInsets.only(right: 12.pt),
                                child: WisText(
                                  store.statusList[i]['name']!,
                                  size: 14.pt,
                                  color: store.filterStatusCode ==
                                          store.statusList[i]['code']
                                      ? colorScheme.primary
                                      : colorScheme.minor,
                                ),
                              );
                            })
                        ],
                      ),
                    ),
                  ]).asExpanded(),
                  Wisdom.row(
                    color: Colors.white,
                    padding: EdgeInsets.symmetric(vertical: 5.pt),
                    width: 75.pt,
                    onTap: () => store.toFilterPage(),
                    alignment: Alignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text('筛选',
                          style: TextStyle(
                            fontSize: 13.pt,
                            color: filterStore.isFilterStatus
                                ? colorScheme.primary
                                : colorScheme.mainTitle,
                          )),
                      Image(
                        image: filterStore.isFilterStatus
                            ? AssetList.$filter_blue_png_image
                            : AssetList.$filter_png_image,
                        height: 20.pt,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          SliverPersistentHeader(
            pinned: true,
            floating: true,
            delegate: StickyTabBarDelegate(
              child: Wisdom(
                key: store.scrollKey,
                color: Colors.white,
                child: TabBar(
                  tabAlignment: TabAlignment.start,
                  controller: store.tabController,
                  labelColor: colorScheme.text,
                  isScrollable: true,
                  dividerHeight: 0,
                  indicatorColor: colorScheme.primary,
                  unselectedLabelColor: colorScheme.minor,
                  indicatorSize: TabBarIndicatorSize.label,
                  indicatorPadding: EdgeInsets.zero,
                  indicatorWeight: 2.0,
                  labelPadding: EdgeInsets.symmetric(vertical: 10.pt),
                  indicator: RoundUnderlineTabIndicator(
                    width: 25.pt,
                  ),
                  labelStyle: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18.pt,
                  ),
                  unselectedLabelStyle: TextStyle(
                    fontWeight: FontWeight.normal,
                    fontSize: 16.pt,
                  ),
                  tabs: [
                    Wisdom(
                      padding: EdgeInsets.symmetric(horizontal: 10.pt),
                      child: WisText('我的任务'),
                    ),
                    Wisdom(
                      padding: EdgeInsets.symmetric(horizontal: 10.pt),
                      child: WisText('我创建的'),
                    ),
                    Wisdom(
                      padding: EdgeInsets.symmetric(horizontal: 10.pt),
                      child: WisText('抄送我的'),
                    ),
                    Wisdom(
                      padding: EdgeInsets.symmetric(horizontal: 10.pt),
                      child: WisText('本部门'),
                    ),
                    Wisdom(
                      padding: EdgeInsets.symmetric(horizontal: 10.pt),
                      child: WisText('我转派的'),
                    ),
                    Wisdom(
                      padding: EdgeInsets.symmetric(horizontal: 10.pt),
                      child: WisText('我指派的'),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ];
      },
      body: TabBarView(
        controller: store.tabController,
        children: [
          _MineTaskList(),
          _OperateTaskList(),
          _CopyTaskList(),
          _DepartTaskList(),
          _TransferTaskList(),
          _ToOtherTaskList(),
        ],
      ),
    );
  }
}

/// 任务大厅滚动消息
class _BuildNoticeBlock extends StatelessWidget {
  const _BuildNoticeBlock({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final store = Provider.of<IndexStore>(context, listen: false);

    return Observer(builder: (_) {
      return Wisdom(
          color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 10.pt),
          child: Wisdom.row(
            onTap: () => store.toTaskHallList(),
            height: 44.pt,
            color: Colors.white,
            padding: EdgeInsets.only(right: 15.pt),
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            border: Border.all(
              color: Color(0x4D0074FF),
              width: 1.pt,
            ),
            borderRadius: BorderRadius.circular(11.pt),
            children: [
              // 待领取标记
              Wisdom(
                height: 48.pt,
                padding: EdgeInsets.all(10.pt),
                borderRadius: BorderRadius.circular(10.pt),
                gradient: LinearGradient(
                  colors: [Color(0xFF4D80FF), Color(0xFF0F67F8)],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
                child: Text(
                  "待领取",
                  style: TextStyle(
                    fontWeight: FontWeight.w400,
                    fontSize: 14.pt,
                    color: Colors.white,
                  ),
                ),
              ),

              /// 轮播消息
              if (store.noticeList.length > 0) ...[
                _BuildNotice(
                  count: store.noticeList.length,
                  itemBuilder: (BuildContext context, int index) {
                    var item = store.noticeList[index];
                    return Wisdom.row(
                      padding: EdgeInsets.only(left: 15.pt),
                      mainAxisAlignment: MainAxisAlignment.start,
                      color: Colors.white,
                      children: [
                        Text.rich(
                          TextSpan(children: [
                            TextSpan(
                              text: item.title,
                              style: TextStyle(
                                fontSize: 15.pt,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ]),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ).asExpanded(),
                      ],
                    );
                  },
                ).asExpanded(),
              ] else ...[
                Wisdom(
                  margin: EdgeInsets.only(left: 10.pt),
                  child: WisText('暂无待领取任务'),
                ).asExpanded(),
              ],
              Text(
                "更多",
                style: TextStyle(
                  fontWeight: FontWeight.w300,
                  fontSize: 14.pt,
                  color: Color(0xFF0F67F8),
                ),
              ),
            ],
          )).asSliver();
    });
  }
}
