import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:api_package/meterReading_house_unitTotal.get.dart'
    as houseUnitTotalInterface;
import 'package:api_package/meterReading_common_count.get.dart'
    as commonUnitTotalInterface;
import '../../models/selects_model.dart';
import '../../view_models/filter.dart';

class FilterPage extends StatelessWidget {
  const FilterPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return _PageView();
  }
}

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

class _PageViewState extends State<_PageView> {
  void dispose() {
    Get.delete<FilterPageStore>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;

    final FilterPageStore store = Get.isRegistered<FilterPageStore>()
        ? Get.find<FilterPageStore>()
        : Get.put(FilterPageStore());

    return Scaffold(
      backgroundColor: Color(0xFFF8F8F8),
      appBar: WAppBar(
        title: WisText(
          '筛选',
          color: colorScheme.mainTitle,
          weight: FontWeight.w600,
          size: 18.pt,
        ),
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        leading: IconButton(
          onPressed: () {
            store.back();
          },
          icon: Icon(
            Icons.close,
            color: colorScheme.mainTitle,
            size: 25.pt,
          ),
        ),
      ),
      body: WisScrollView(
        onInit: () => store.init(),
        slivers: [
          SliverToBoxAdapter(
            child: Obx(() {
              return Wisdom.column(
                color: Colors.white,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                padding: EdgeInsets.only(
                  top: 5.pt,
                  left: 15.pt,
                  right: 15.pt,
                  bottom: 15.pt,
                ),
                children: [
                  WFilterButtons(
                    name: '表类型',
                    child: Wrap(
                      spacing: 15.pt,
                      runSpacing: 12.pt,
                      alignment: WrapAlignment.start,
                      children: [
                        for (var i = 0;
                            i < store.meterTypeList.length;
                            i++) ...[
                          Obx(() {
                            return WButton(
                              onPressed: () => store.chooseMeterType(
                                  store.meterTypeList[i]['code']),
                              color: Color.fromRGBO(246, 247, 252, 1),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(4.pt),
                                side: BorderSide(
                                  width: 1,
                                  color: store.meterType.value ==
                                          store.meterTypeList[i]['code']
                                      ? colorScheme.primary.withOpacity(0.5)
                                      : colorScheme.background,
                                  style: BorderStyle.solid,
                                ),
                              ),
                              child: Text(
                                store.meterTypeList[i]['name'] ?? '',
                                style: TextStyle(
                                  fontSize: 13.pt,
                                  color: store.meterType.value ==
                                          store.meterTypeList[i]['code']
                                      ? colorScheme.primary
                                      : colorScheme.minor,
                                ),
                              ),
                            );
                          }),
                        ],
                      ],
                    ),
                  ),
                  SizedBox(height: 10.pt),
                  Wisdom.column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Text(
                        '抄表时间',
                        style: TextStyle(
                          fontSize: 16.pt,
                          fontWeight: FontWeight.bold,
                        ),
                      ).asPaddingSymmetric(vertical: 8.pt),
                      ButtonTheme(
                        height: 40.pt,
                        minWidth: MediaQuery.of(context).size.width,
                        textTheme: ButtonTextTheme.accent,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15.pt),
                        ),
                        child: Wrap(
                          alignment: WrapAlignment.start,
                          children: [
                            Obx(() {
                              return WButton(
                                onPressed: () async {
                                  final res = await WPickerUtil.date(
                                    context,
                                    title: WisText('抄表时间'),
                                    initialDate:
                                        store.meterDate.value == DateTime(1800)
                                            ? null
                                            : store.meterDate.value,
                                  );

                                  if (res != null) {
                                    store.chooseMeterDate(res);
                                  }
                                },
                                color: store.meterDate.value != ''
                                    ? colorScheme.primary
                                    : colorScheme.background,
                                child: Text(
                                  store.meterDate.value != ''
                                      ? "${DateFormat('yyyy-MM-dd').format(store.meterDate.value)}"
                                      : '请选择抄表范围',
                                  style: TextStyle(
                                    fontSize: 14.pt,
                                    color: store.meterDate.value != ''
                                        ? Colors.white
                                        : colorScheme.minor,
                                  ),
                                ),
                              );
                            }),
                          ],
                        ),
                      ),
                    ],
                  ),
                  Wisdom.column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Obx(() {
                        return Text(
                          '抄表范围（${store.isHouse.value ? '住户表' : '公共表'}）',
                          style: TextStyle(
                            fontSize: 16.pt,
                            fontWeight: FontWeight.bold,
                          ),
                        ).asPaddingSymmetric(vertical: 8.pt);
                      }),
                      ButtonTheme(
                        height: 40.pt,
                        minWidth: MediaQuery.of(context).size.width,
                        textTheme: ButtonTextTheme.accent,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15.pt),
                        ),
                        child: Wrap(
                          alignment: WrapAlignment.start,
                          children: [
                            Obx(() {
                              return WButton(
                                onPressed: () async {
                                  final values = await _FilterComponent.show(
                                    store.filterValues,
                                    store.isHouse.value,
                                  );
                                  if (values != null) {
                                    store.filterChange(values);
                                  }
                                },
                                color: store.filterValues['buildId'] != ''
                                    ? colorScheme.primary
                                    : colorScheme.background,
                                child: Text(
                                  store.filterValues['buildId'] != ''
                                      ? "${store.filterValues['name']}"
                                      : '请选择抄表范围',
                                  style: TextStyle(
                                    fontSize: 14.pt,
                                    color: store.filterValues['buildId'] != ''
                                        ? Colors.white
                                        : colorScheme.minor,
                                  ),
                                ),
                              );
                            }),
                          ],
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 10.pt),
                  if (store.isHouse.value) ...[
                    WFilterButtons(
                      name: '楼栋排序',
                      child: Wrap(
                        spacing: 15.pt,
                        runSpacing: 12.pt,
                        alignment: WrapAlignment.start,
                        children: [
                          for (var i = 0;
                              i < store.orderTypeList.length;
                              i++) ...[
                            Obx(() {
                              return WButton(
                                onPressed: () => store.choosehouseFilterType(
                                    store.orderTypeList[i]['code']),
                                color: Color.fromRGBO(246, 247, 252, 1),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(4.pt),
                                  side: BorderSide(
                                    width: 1,
                                    color: store.order.value ==
                                            store.orderTypeList[i]['code']
                                        ? colorScheme.primary.withOpacity(0.5)
                                        : colorScheme.background,
                                    style: BorderStyle.solid,
                                  ),
                                ),
                                child: Text(
                                  store.orderTypeList[i]['name'] ?? '',
                                  style: TextStyle(
                                    fontSize: 13.pt,
                                    color: store.order.value ==
                                            store.orderTypeList[i]['code']
                                        ? colorScheme.primary
                                        : colorScheme.minor,
                                  ),
                                ),
                              );
                            }),
                          ],
                        ],
                      ),
                    ),
                  ],
                  SizedBox(height: 10.pt),
                  WFilterButtons(
                    name: '抄表类型',
                    child: Wrap(
                      spacing: 15.pt,
                      runSpacing: 12.pt,
                      alignment: WrapAlignment.start,
                      children: [
                        for (var i = 0;
                            i < store.statusTypeList.length;
                            i++) ...[
                          Obx(() {
                            return WButton(
                              onPressed: () => store.chooseStatusType(
                                  store.statusTypeList[i]['code']),
                              color: Color.fromRGBO(246, 247, 252, 1),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(4.pt),
                                side: BorderSide(
                                  width: 1,
                                  color: store.statusType.value ==
                                          store.statusTypeList[i]['code']
                                      ? colorScheme.primary.withOpacity(0.5)
                                      : colorScheme.background,
                                  style: BorderStyle.solid,
                                ),
                              ),
                              child: Text(
                                store.statusTypeList[i]['name'] ?? '',
                                style: TextStyle(
                                  fontSize: 13.pt,
                                  color: store.statusType.value ==
                                          store.statusTypeList[i]['code']
                                      ? colorScheme.primary
                                      : colorScheme.minor,
                                ),
                              ),
                            );
                          }),
                        ],
                      ],
                    ),
                  ),
                ],
              );
            }),
          ),
        ],
      ),
      bottomNavigationBar: Wisdom.row(
        padding: EdgeInsets.symmetric(horizontal: 15.pt),
        color: Colors.white,
        children: [
          SafeArea(
            child: WLoadingButton(
              color: Colors.white,
              height: 44.pt,
              minWidth: 120.pt,
              margin: EdgeInsets.symmetric(vertical: 8.pt),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25.pt),
                side: BorderSide(
                  width: 1,
                  color: colorScheme.primary.withOpacity(0.5),
                  style: BorderStyle.solid,
                ),
              ),
              onPressed: () => store.onResetInner(),
              child: WisText('重置', color: colorScheme.primary),
            ),
          ),
          SafeArea(
            child: WLoadingButton(
              height: 44.pt,
              margin: EdgeInsets.only(top: 8.pt, bottom: 8.pt, left: 10.pt),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25.pt),
              ),
              onPressed: () => store.submit(),
              child: Text("确认"),
            ),
          ).asExpanded(),
        ],
      ),
    );
  }
}

class _FilterComponent extends StatefulWidget {
  _FilterComponent({
    Key? key,
    this.values,
    this.onChange,
    required this.isHouse,
  }) : super(key: key);
  final Map<String, dynamic>? values;
  final bool isHouse;
  final Function(Map<String, dynamic> values)? onChange;

  static Future<Map<String, dynamic>?> show(
      Map<String, dynamic> values, bool isHouse) async {
    Map<String, dynamic> _values = Map.from(values);

    return await WBottomModalUtil.show<Map<String, dynamic>>(
      WNavUtil.instance!.context!,
      plain: false,
      title: Text('选择抄表范围'),
      onConfirm: (_) => WNavUtil.instance!.pop(_values),
      onCancel: (_) => WNavUtil.instance!.pop(),
      bodyConstraints: BoxConstraints.tightFor(height: 444.pt),
      body: _FilterComponent(
        values: _values,
        onChange: (values) => _values = values,
        isHouse: isHouse,
      ),
    );
  }

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

class __FilterComponentState extends State<_FilterComponent> {
  ///存放筛选数据
  Map<String, dynamic> values = {
    'name': null,
    'buildId': null,
    'unitId': null,
  };
  @override
  void initState() {
    super.initState();
    values = widget.values ?? {};
    getStatList();
  }

  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  String? get buildId => values['buildId'];
  String? get unitId => values['unitId'];
  bool get isHouse => widget.isHouse;

  changeValue(String field, value) {
    if (values[field] != value) {
      values[field] = value;
      setState(() {});
    }
  }

  ///单元统计
  List<SelectModel>? selectList;
  List<SelectModel> get unitListFilter =>
      selectList?.where((e) => e.name!.indexOf(searchKey) != -1).toList() ?? [];

  String searchKey = '';
  onSearch(String? str) {
    if (str != searchKey) {
      searchKey = str!;
      values['buildId'] = null;
      values['unitId'] = null;
      values['name'] = null;
      setState(() {});
    }
  }

  getStatList() async {
    final communityId = communityGlobalStore.data.id;

    if (isHouse == true) {
      final res = await houseUnitTotalInterface.Interface.request(
        HttpUtil.instance,
        queryParameters: {
          'communityId': communityId,
        },
      );
      final list = res.data?.meterHouseUnitDtos
              ?.map((e) => SelectModel(
                    buildId: e.buildId,
                    name: '${e.buildName}/${e.unitName}',
                    unitId: e.unitId,
                    electricityNotRecord: e.unitEleNoTranscribe,
                    waterNotRecord: e.unitWaterNoTranscribe,
                  ))
              .toList() ??
          [];
      num? electricityNotRecordTotal = 0;
      if (list.length == 1) {
        electricityNotRecordTotal = list[0].electricityNotRecord ?? 0;
      } else if (list.length > 1) {
        electricityNotRecordTotal = list
            .map((e) => e.electricityNotRecord)
            .toList()
            .reduce((v, e) => (v ?? 0) + (e ?? 0));
      }
      num? waterNotRecordTotal = 0;
      if (list.length == 1) {
        waterNotRecordTotal = list[0].waterNotRecord ?? 0;
      } else if (list.length > 1) {
        waterNotRecordTotal = list
            .map((e) => e.waterNotRecord)
            .toList()
            .reduce((v, e) => (v ?? 0) + (e ?? 0));
      }
      selectList = [
        SelectModel(
          name: '全部',
          electricityNotRecord: electricityNotRecordTotal,
          waterNotRecord: waterNotRecordTotal,
        ),
        ...list
      ];
    } else {
      final res = await commonUnitTotalInterface.Interface.request(
        HttpUtil.instance,
        queryParameters: {
          'communityId': communityId,
        },
      );

      final list = res.data?.meterCommonBuildDtos
              ?.map((e) => SelectModel(
                    buildId: e.buildId,
                    name: e.buildName,
                    electricityNotRecord: e.buildEleNoTranscribe,
                    waterNotRecord: e.buildWaterNoTranscribe,
                  ))
              .toList() ??
          [];
      num? electricityNotRecordTotal = 0;
      if (list.length == 1) {
        electricityNotRecordTotal = list[0].electricityNotRecord ?? 0;
      } else if (list.length > 1) {
        electricityNotRecordTotal = list
            .map((e) => e.electricityNotRecord)
            .toList()
            .reduce((v, e) => (v ?? 0) + (e ?? 0));
      }
      num? waterNotRecordTotal = 0;
      if (list.length == 1) {
        waterNotRecordTotal = list[0].waterNotRecord ?? 0;
      } else if (list.length > 1) {
        waterNotRecordTotal = list
            .map((e) => e.waterNotRecord)
            .toList()
            .reduce((v, e) => (v ?? 0) + (e ?? 0));
      }
      selectList = [
        SelectModel(
          name: '全部',
          electricityNotRecord: electricityNotRecordTotal,
          waterNotRecord: waterNotRecordTotal,
        ),
        ...list
      ];
    }
    setState(() {});
  }

  ///选中事件
  onUnitPick(SelectModel item) {
    values['buildId'] = item.buildId;
    values['unitId'] = item.unitId;
    values['name'] = item.name;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    WColorScheme colorScheme = WTheme.of(context).colorScheme;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        ColoredBox(
          color: Colors.white,
          child: WSearch(
            hintText: '输入楼栋${isHouse ? '单元' : ''}名称搜索',
            moonlight: false,
            onSubmitted: onSearch,
            onCancel: () => onSearch(''),
            isDark: true,
          ),
        ),
        Wisdom.column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          padding: EdgeInsets.symmetric(horizontal: 15.pt),
          children: [
            if (selectList == null)
              Center(
                child: WLoading(
                  size: 20.pt,
                  strokeWidth: 2.pt,
                  color: colorScheme.primary,
                ),
              ).asExpanded()
            else
              ListView.builder(
                itemCount: unitListFilter.length,
                itemBuilder: (_, i) {
                  final item = unitListFilter[i];
                  return Wisdom.row(
                    onTap: () => onUnitPick(item),
                    padding: EdgeInsets.symmetric(vertical: 14.pt),
                    border: Border(bottom: Divider.createBorderSide(context)),
                    children: [
                      Wisdom.row(
                        width: 134.pt,
                        children: [
                          Text(
                            '${item.name}',
                            style: values['unitId'] == item.unitId &&
                                    values['buildId'] == item.buildId
                                ? colorScheme.primary.asColorStyle
                                : colorScheme.text.asColorStyle,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ).asFlexible(flex: 1),
                        ],
                      ),
                      Text.rich(
                        TextSpan(
                          style: TextStyle(
                            fontSize: 12.pt,
                            color: colorScheme.minor,
                          ),
                          children: [
                            TextSpan(text: '电表未抄:'),
                            TextSpan(
                              text: '${item.electricityNotRecord}',
                              style: colorScheme.warning.asColorStyle,
                            ),
                          ],
                        ),
                      ).asExpanded(),
                      Text.rich(
                        TextSpan(
                          style: TextStyle(
                            fontSize: 12.pt,
                            color: colorScheme.minor,
                          ),
                          children: [
                            TextSpan(text: '水表未抄:'),
                            TextSpan(
                              text: '${item.waterNotRecord}',
                              style: colorScheme.warning.asColorStyle,
                            ),
                          ],
                        ),
                      ).asExpanded(),
                    ],
                  );
                },
              ).asExpanded(),
          ],
        ).asExpanded(),
      ],
      // child: child,
    );
  }
}
