/*
 * @Author: XianKaiQun
 * @Date: 2020-09-11 09:41:24
 * @LastEditors: wuwei
 * @LastEditTime: 2024-03-27 10:59:11
 * @Description: 
 */
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:metered_package/src/assets.gen.dart';
import 'package:metered_package/src/view_models/private_index_store.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
part 'components/meter_item.dart';
part 'components/panel.dart';

///抄表
class IndexPage extends StatelessWidget {
  const IndexPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (providerContext) => PrivateIndexStore(context, providerContext),
      child: _PageView(),
      lazy: false,
    );
  }
}

///抄表
class _PageView extends StatefulWidget {
  _PageView({Key? key}) : super(key: key);
  @override
  _PageViewState createState() => _PageViewState();
}

class _PageViewState extends State<_PageView>
    with SingleTickerProviderStateMixin {
  PrivateIndexStore get store => Provider.of(context, listen: false);

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

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    Provider.of<PrivateIndexStore>(context, listen: false)
        .tabController
        .dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    final store = Provider.of<PrivateIndexStore>(context, listen: true);
    return Scaffold(
      appBar: WAppBar(
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        title: WisText('${store.routingArgs['appBarTitle'] ?? '手机抄表'}',
            size: 19.pt, weight: FontWeight.w600, color: colorScheme.mainTitle),
        actions: [
          IconButton(
            onPressed: () => store.toFilter(),
            icon: Image(
              image: AssetList.$filter_png_image,
              width: 20.pt,
              color: colorScheme.mainTitle,
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          if (store.isHouse)
            Wisdom.row(
              color: Colors.white,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                /// 输入框
                Expanded(
                  child: WSearch(
                    hintText: '输入房号搜索',
                    initValue: store.houseSearchKey ?? '',
                    onSubmitted: (v) => store.onHouseSubmint(v),
                    onCancel: () => store.onHouseSubmint(''),
                    isControlOutside: true,
                    controller:
                        TextEditingController(text: store.houseSearchKey),
                    padding: EdgeInsets.symmetric(vertical: 10.pt),
                    isDark: true,
                  ),
                ),
              ],
            )
          else
            Wisdom.row(
              color: Colors.white,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                /// 输入框
                Expanded(
                  child: WSearch(
                    hintText: '输入仪表名称搜索',
                    initValue: store.meterSearchKey,
                    onSubmitted: (v) => store.onMeterSubmint(v),
                    onCancel: () => store.onMeterSubmint(''),
                    isControlOutside: true,
                    controller:
                        TextEditingController(text: store.meterSearchKey),
                    padding: EdgeInsets.symmetric(vertical: 10.pt),
                    isDark: true,
                  ),
                ),
              ],
            ),
          _PanelComponent(),
          WisScrollView(
            key: store.scrollViewKey,
            onInit: () => store.getData(isLoad: false),
            onRefresh: () => store.getData(isLoad: false),
            onLoad: () => store.getData(isLoad: true),
            slivers: [
              if (store.isHouse)
                WisSliverList.childBuilder(
                  childCount: store.houseMeterList.length,
                  builder: (_, i) {
                    final data = store.houseMeterList[i];
                    return Wisdom.column(
                      borderRadius: BorderRadius.circular(12.pt),
                      color: Colors.white,
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      margin: EdgeInsets.only(left: 15.pt,right: 15.pt,bottom: 10.pt),
                      padding: EdgeInsets.only(top: 15.pt),
                      children: [
                        Wisdom.row(
                          children: [
                            Wisdom(
                              height: 20.pt,
                              width: 3.pt,
                              color: colorScheme.primary,
                              margin: EdgeInsets.only(
                                right: 10.pt,
                                left: 15.pt,
                              ),
                              borderRadius: BorderRadius.circular(4.pt),
                            ),
                            WisText(
                              '${data.roomNo}',
                              color: colorScheme.mainTitle,
                              weight: FontWeight.w600,
                              size: 15.pt,
                            ),
                          ],
                        ),
                        SizedBox(height: 5.pt),
                        if (data.meterHouseInfos.length == 0)
                          WEmptyWidget.plain(
                            text: Text('空空如也~~'),
                          )
                        else
                          // SizedBox(height: 15.pt),
                          for (var item in data.meterHouseInfos)
                            _MeterItemComponent(
                              key: ValueKey(item),
                              item: item,
                              id: item.id,
                              source: 'house',
                              type: item.meterType?.code,
                              name: item.meterName,
                              lastAmount: item.lastAmount,
                              lastActualAmount: item.lastActualAmount,
                              date: item.readerDate,
                              backhaulAmount: item.backhaulAmount,
                              multiple: item.multiple,
                              transcribes: item.transcribes,
                              meterCode: item.meterCode,
                              location: item.roomNo,
                              onSave: store.onSave,
                            ),
                      ],
                    );
                  },
                )
              else
                WisSliverList.childBuilder(
                  childCount: store.commonMeterList.length,
                  builder: (_, i) {
                    final item = store.commonMeterList[i];
                    final location = [
                      if (item.buildName?.isNotEmpty == true) item.buildName,
                      if (item.unitName?.isNotEmpty == true) item.unitName
                    ];
                    return Wisdom(
                     borderRadius: BorderRadius.circular(12.pt),
                      color: Colors.white,
                      margin: EdgeInsets.only(left: 15.pt,right: 15.pt,bottom: 10.pt),
                      padding: EdgeInsets.only(top: 15.pt),
                      child: _MeterItemComponent(
                        key: ValueKey(item),
                        id: item.id,
                        source: 'common',
                        type: item.meterType,
                        name: item.meterName,
                        lastAmount: item.lastAmount,
                        lastActualAmount: item.lastActualAmount,
                        date: item.readerDate,
                        backhaulAmount: item.backhaulAmount,
                        multiple: item.multiple,
                        transcribes: item.transcribes,
                        meterCode: item.meterCode,
                        onSave: store.onSave,
                        location:
                            location.length == 0 ? '--' : location.join('-'),
                      ),
                    );
                  },
                ),
            ],
          ).nestExpanded(),
        ],
      ),
    );
  }
}
