/*
 * @Author       : WuWei
 * @LastEditors: ChenYaJin
 * @Date         : 2023-08-07 11:01:15
 * @LastEditTime: 2023-11-02 17:15:27
 * @Description  : Do not edit
 */
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:app_package/src/models/community_picker.dart';

import '../../view_models/private_index_store.dart';

class SummaryIndexPage extends StatelessWidget {
  const SummaryIndexPage({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> {
  @override
  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    final store = Provider.of<PrivateIndexStore>(context, listen: true);

    return Scaffold(
      backgroundColor: Color(0xFFF8F8F8),
      appBar: WAppBar(
        title: WisText(
          '收支统计',
          color: colorScheme.mainTitle,
          weight: FontWeight.w600,
          size: 18.pt,
        ),
        brightness: Brightness.light,
        backgroundColor: Colors.white,
      ),
      body: WisScrollView(
        key: store.indexScrollViewKey3,
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: WisCard(
              margin: EdgeInsets.only(top: 10.pt, left: 15.pt, right: 15.pt),
              color: Colors.white,
              child: Wisdom.column(children: [
                Wisdom.row(
                  padding:
                      EdgeInsets.symmetric(horizontal: 15.pt, vertical: 15.pt),
                  children: [
                    WisText(
                      '温馨提示：最大可查询范围不超过一年',
                      color: Color(0xff00BA7B),
                    )
                  ],
                ),
                Wisdom.column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  margin: EdgeInsets.symmetric(horizontal: 15.pt),
                  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: [
                          WButton(
                            onPressed: () async {
                              final res = await WPickerUtil.single<
                                  CommunityPickerModel>(
                                context,
                                title: Text('选择小区'),
                                initialValue: store.communityList,
                                getData: () => store.getAsyncCommunityList(),
                                isSearch: true,
                              );
                              if (res != null) {
                                store.onChooseCommunity(res);
                              }
                            },
                            color: store.communityId != null
                                ? colorScheme.primary
                                : colorScheme.background,
                            child: Text(
                              store.communityId != null
                                  ? "${store.communityIName}"
                                  : '请选择小区',
                              style: TextStyle(
                                fontSize: 14.pt,
                                color: store.communityId != null
                                    ? Colors.white
                                    : colorScheme.minor,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                Wisdom.column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    margin: EdgeInsets.symmetric(horizontal: 15.pt),
                    children: [
                      Text(
                        '时间范围',
                        style: TextStyle(
                          fontSize: 16.pt,
                          fontWeight: FontWeight.bold,
                        ),
                      ).asPaddingOnly(top: 8.pt),
                    ]),
                Wisdom.row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  color: Colors.white,
                  padding: EdgeInsets.all(15.pt),
                  border: Border(
                    bottom: BorderSide(
                      width: 0.5.pt,
                      color: colorScheme.divider,
                    ),
                  ),
                  children: [
                    _BuildFilterItemButton(
                        title: '今日',
                        chooseKey: 'today',
                        onChoose: () => store.onChooseDateButton('today')),
                    _BuildFilterItemButton(
                        title: '昨日',
                        chooseKey: 'yesterday',
                        onChoose: () => store.onChooseDateButton('yesterday')),
                    _BuildFilterItemButton(
                        title: '近七日',
                        chooseKey: 'week',
                        onChoose: () => store.onChooseDateButton('week')),
                    _BuildFilterItemButton(
                        title: '本月',
                        chooseKey: 'thismonth',
                        onChoose: () => store.onChooseDateButton('thismonth')),
                    _BuildFilterItemButton(
                        title: '上月',
                        chooseKey: 'lastmonth',
                        onChoose: () => store.onChooseDateButton('lastmonth')),
                  ],
                ),
                Wisdom.column(
                    padding: EdgeInsets.symmetric(
                      horizontal: 15.pt,
                      vertical: 0,
                    ),
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5.pt,
                        color: colorScheme.divider,
                      ),
                    ),
                    color: Colors.white,
                    children: [
                      WFDatePicker(
                        firstDate: store.payAtStart != null
                            ? DateTime.parse(store.payAtStart!)
                                .add(Duration(days: -365))
                                .toFormat(WisDateTimeFormat.date)
                            : null,
                        lastDate: store.payAtEnd,
                        initialDateTime: store.payAtStart,
                        onChanged: (v) => store.onPickStartDate(v),
                        title: Text.rich(
                          TextSpan(
                            children: [
                              WidgetSpan(
                                child: Wisdom(
                                  margin: EdgeInsets.only(
                                      right: 10.pt, bottom: 2.pt),
                                  child: Image.asset(
                                    'lib/assets/rl.png',
                                    width: 17.pt,
                                    height: 14.pt,
                                    package: 'pay_package',
                                  ),
                                ),
                              ),
                              TextSpan(
                                text: '起始时间',
                                style: TextStyle(
                                  color: colorScheme.mainTitle,
                                  fontSize: 15.pt,
                                  fontWeight: FontWeight.w300,
                                ),
                              ),
                            ],
                          ),
                        ),
                        hintText: '选择起始时间',
                      ),
                      WFDatePicker(
                        firstDate: store.payAtStart,
                        lastDate: store.payAtStart != null
                            ? DateTime.parse(store.payAtStart!)
                                .add(Duration(days: 365))
                                .toFormat(WisDateTimeFormat.date)
                            : null,
                        initialDateTime: store.payAtEnd,
                        onChanged: (v) => store.onPickEndDate(v),
                        title: Text.rich(
                          TextSpan(
                            children: [
                              WidgetSpan(
                                child: Wisdom(
                                  margin: EdgeInsets.only(
                                    right: 10.pt,
                                    bottom: 2.pt,
                                  ),
                                  child: Image.asset(
                                    'lib/assets/rl.png',
                                    width: 17.pt,
                                    height: 14.pt,
                                    package: 'pay_package',
                                  ),
                                ),
                              ),
                              TextSpan(
                                text: '结束时间',
                                style: TextStyle(
                                  color: colorScheme.mainTitle,
                                  fontSize: 15.pt,
                                  fontWeight: FontWeight.w300,
                                ),
                              ),
                            ],
                          ),
                        ),
                        hintText: '选择结束时间',
                      ),
                    ]),
                Wisdom.row(
                  color: Colors.white,
                  children: [
                    WButton(
                      color: colorScheme.primary,
                      margin: EdgeInsets.fromLTRB(15.pt, 15.pt, 15.pt, 15.pt),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(25.pt),
                      ),
                      onPressed: () => store.onFilterSummary(),
                      disabledColor: colorScheme.disabled,
                      child: Text('查询'),
                    ).asExpanded(),
                  ],
                )
              ]),
            ),
          ),
          if (store.isShowList == true) ...[
            SliverToBoxAdapter(
              child: Wisdom.column(
                children: [
                  if (store.billList != null && store.billList!.length > 0) ...[
                    WisCard(
                      margin: EdgeInsets.only(
                          left: 15.pt, right: 15.pt, top: 10.pt, bottom: 5.pt),
                      color: Colors.white,
                      child: _BuildBillBLock(
                        list: store.billList ?? [],
                        name: '${store.communityINameBySubmit}账单实收统计表',
                        total: store.summary?.totalBillFee,
                        isBill: true,
                      ),
                    ),
                  ],
                  if (store.preList != null && store.preList!.length > 0) ...[
                    WisCard(
                      margin: EdgeInsets.only(
                          left: 15.pt, right: 15.pt, top: 5.pt, bottom: 10.pt),
                      color: Colors.white,
                      child: _BuildBillBLock(
                        list: store.preList ?? [],
                        name: '${store.communityINameBySubmit}预存款收款统计表',
                        total: store.summary?.totalPrePayFee,
                      ),
                    ),
                  ],
                  if (store.depositeList != null &&
                      store.depositeList!.length > 0) ...[
                    WisCard(
                      margin: EdgeInsets.only(
                          left: 15.pt, right: 15.pt, top: 5.pt, bottom: 10.pt),
                      color: Colors.white,
                      child: _BuildBillBLock(
                        list: store.depositeList ?? [],
                        name: '${store.communityINameBySubmit}押金收款统计表',
                        total: store.summary?.totalDepositeFee,
                      ),
                    ),
                  ],
                  if ((store.billList == null || store.billList!.length == 0) &&
                      (store.preList == null || store.preList!.length == 0) &&
                      (store.depositeList == null ||
                          store.depositeList!.length == 0)) ...[
                    WisCard(
                      margin: EdgeInsets.only(
                          left: 15.pt, right: 15.pt, top: 5.pt, bottom: 10.pt),
                      color: Colors.white,
                      child: WEmptyWidget(text: Text('查询期间无缴费数据')),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }
}

class _BuildBillBLock extends StatelessWidget {
  const _BuildBillBLock(
      {Key? key, this.list, this.name, this.total, this.isBill = false})
      : super(key: key);
  final list;
  final name;
  final total;
  final bool isBill;
  @override
  Widget build(BuildContext context) {
    final store = Provider.of<PrivateIndexStore>(context);
    final colorScheme = WTheme.of(context).colorScheme;
    return Wisdom.column(
      margin: EdgeInsets.only(top: 10.pt),
      padding: EdgeInsets.symmetric(vertical: 20.pt),
      color: Colors.white,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Wisdom.column(
          crossAxisAlignment: CrossAxisAlignment.center,
          padding: EdgeInsets.only(bottom: 20.pt),
          margin: EdgeInsets.only(bottom: 20.pt, left: 15.pt, right: 15.pt),
          border: Border(
              bottom: BorderSide(
            width: 0.5.pt,
            color: colorScheme.divider,
          )),
          children: [
            WisText(
              '$name',
              size: 16.pt,
              weight: FontWeight.w600,
              color: colorScheme.mainTitle,
            ),
            SizedBox(height: 5.pt),
            WisText(
              '${store.payAtStartDate ?? '--'}至${store.payAtEndDate ?? '--'}',
              color: colorScheme.placeholder,
              size: 14.pt,
              weight: FontWeight.w300,
            ),
          ],
        ),
        for (int i = 0; i < list.length; i++)
          _BuildBillItem(
            item: list[i],
            index: i,
          ),
        Wisdom.row(
          border: Border(
              top: BorderSide(
            width: 0.5.pt,
            color: colorScheme.divider,
          )),
          margin: EdgeInsets.only(top: 15.pt),
          padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 15.pt),
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            WisText(
              '总计:',
              size: 16.pt,
              weight: FontWeight.w600,
              color: colorScheme.mainTitle,
            ),
            WisText(
              '￥${total ?? 0}',
              size: 16.pt,
              weight: FontWeight.w600,
              color: colorScheme.primary,
            ),
          ],
        ),
        if (isBill == true &&
            store.summary != null &&
            store.summary?.billPayWayCount != null &&
            store.summary!.billPayWayCount!.length > 0) ...[
          for (int i = 0; i < store.summary!.billPayWayCount!.length; i++)
            Wisdom.row(
              margin: EdgeInsets.only(bottom: 15.pt),
              padding: EdgeInsets.symmetric(
                horizontal: 15.pt,
              ),
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                WisText(
                  '${store.summary!.billPayWayCount![i].payWay['name']}:',
                  size: 15.pt,
                  weight: FontWeight.w300,
                  color: colorScheme.mainTitle,
                ),
                WisText(
                  '￥${store.summary?.billPayWayCount![i].payFee ?? '0'}(${store.summary?.billPayWayCount![i].feeRate ?? '0'}%)',
                  size: 15.pt,
                  weight: FontWeight.w300,
                  color: colorScheme.green,
                ),
              ],
            ),
        ]
      ],
    );
  }
}

class _BuildBillItem extends StatelessWidget {
  const _BuildBillItem({Key? key, this.item, this.index}) : super(key: key);
  final item;
  final index;
  @override
  Widget build(BuildContext context) {
    final colorScheme = WTheme.of(context).colorScheme;
    return Wisdom.row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      padding: EdgeInsets.symmetric(horizontal: 15.pt),
      margin: EdgeInsets.only(top: index == 0 ? 0 : 15.pt),
      children: [
        WisText(
          item?.name,
          size: 15.pt,
          weight: FontWeight.w300,
          color: colorScheme.mainTitle,
        ),
        WisText(
          '￥${item?.fee ?? '0'}',
          size: 15.pt,
          weight: FontWeight.w300,
          color: colorScheme.mainTitle,
        ),
      ],
    );
  }
}

class _BuildFilterItemButton extends StatelessWidget {
  const _BuildFilterItemButton(
      {Key? key, this.title, this.chooseKey, this.onChoose})
      : super(key: key);
  final String? title;
  final String? chooseKey;
  final Function()? onChoose;

  @override
  Widget build(BuildContext context) {
    final colorScheme = WTheme.of(context).colorScheme;
    final store = Provider.of<PrivateIndexStore>(context, listen: true);
    return Wisdom(
      onTap: onChoose!,
      alignment: Alignment.center,
      color: store.chooseButton == chooseKey
          ? Color(0xffEAF3FD)
          : colorScheme.background,
      height: 30.pt,
      border: Border.all(
        color: store.chooseButton == chooseKey
            ? colorScheme.primary
            : Colors.transparent,
        width: 0.5,
      ),
      padding: EdgeInsets.symmetric(
        horizontal: 15.pt,
      ),
      borderRadius: BorderRadius.circular(15.pt),
      child: WisText(
        title!,
        size: 14.pt,
        weight: FontWeight.w300,
        color: store.chooseButton == chooseKey
            ? colorScheme.primary
            : colorScheme.mainTitle,
      ),
    );
  }
}
