/*
 * @Author: WuWei
 * @Date: 2020-08-13 19:30:34
 * @LastEditors: wuwei 
 * @LastEditTime: 2024-06-05 16:05:37
 * @Description:
 */
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../../view_models/private_index_store.dart';

class DetailPage extends StatelessWidget {
  const DetailPage({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
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    final store = Provider.of<PrivateIndexStore>(context);
    final detail = store.payDetail;
    final list = store.payDetail?.list ?? [];

    num calcFeeCount(feeType) {
      num count = 0;
      list.forEach((element) {
        if (element.feeType == feeType) {
          count = count + double.parse(element.fee!);
        }
      });
      return count;
    }

    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
        title: WisText('收支详情',
            size: 19.pt, weight: FontWeight.w600, color: colorScheme.mainTitle),
      ),
      body: WisScrollView(
        onInit: () => store.getDetail(),
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: Wisdom.column(
              margin: EdgeInsets.only(top: 20.pt, bottom: 10.pt),
              children: [
                Wisdom.row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    WTag(
                      plain: true,
                      border: Border.all(color: store.getMoneyFlowColor),
                      backgroundColor: store.getMoneyFlowColor.withOpacity(0.1),
                      padding: EdgeInsets.symmetric(horizontal: 5.pt),
                      child: WisText(
                        '${store.getMoneyFlowName}',
                        color: store.getMoneyFlowColor,
                        size: 13.pt,
                      ),
                    ),
                    SizedBox(width: 10.pt),
                    WTag(
                      plain: true,
                      padding: EdgeInsets.symmetric(horizontal: 5.pt),
                      child: WisText(
                        '${store.getAccountStatusName}',
                        color: colorScheme.primary,
                        size: 13.pt,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 10.pt),
                Wisdom.row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    WisText(
                      '￥',
                      color: store.getMoneyFlowColor,
                      size: 14.pt,
                      weight: FontWeight.bold,
                    ),
                    WisText(
                      '${detail?.totalPayFee ?? '0'}',
                      color: store.getMoneyFlowColor,
                      size: 28.pt,
                      weight: FontWeight.w600,
                    ),
                  ],
                ),
              ],
            ),
          ),
          if (detail?.moneyFlow == 'out' && detail?.originalId != null)
            SliverToBoxAdapter(
              child: WisCard(
                margin: EdgeInsets.only(left: 15.pt, right: 15.pt, top: 10.pt),
                padding: EdgeInsets.symmetric(horizontal: 20.pt),
                color: Colors.white,
                child: Wisdom.column(
                  children: [
                    Wisdom.row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      padding: EdgeInsets.only(
                          top: 20.pt,
                          bottom: store.showDetail == true ? 0 : 20.pt),
                      children: [
                        Wisdom.row(
                          children: [
                            WisText(
                              '缴费信息',
                              size: 15.pt,
                              weight: FontWeight.w300,
                            ),
                            SizedBox(width: 10.pt),
                            WTag(
                              plain: true,
                              border: Border.all(color: Color(0xffFF495E)),
                              backgroundColor:
                                  Color(0xffFF495E).withOpacity(0.1),
                              child: WisText(
                                '已退费',
                                color: Color(0xffFF495E),
                                size: 13.pt,
                              ),
                            ),
                          ],
                        ),
                        if (store.showDetail == false)
                          Wisdom(
                            onTap: () => store.onSetShowDetail(true),
                            child: WisText(
                              '展开明细',
                              size: 15.pt,
                              weight: FontWeight.w300,
                              color: colorScheme.primary,
                            ),
                          )
                        else
                          Wisdom(
                            onTap: () => store.onSetShowDetail(false),
                            child: WisText(
                              '收起明细',
                              size: 15.pt,
                              weight: FontWeight.w300,
                              color: colorScheme.primary,
                            ),
                          )
                      ],
                    ),
                    if (store.refundDetail?.id != null &&
                        store.showDetail == true)
                      detailInfo(
                        detail: store.refundDetail,
                      )
                  ],
                ),
              ),
            ),
          SliverToBoxAdapter(
            child: WisCard(
                margin: EdgeInsets.only(left: 15.pt, right: 15.pt, top: 10.pt),
                padding: EdgeInsets.symmetric(horizontal: 20.pt),
                color: Colors.white,
                child: detailInfo(
                  detail: detail,
                )),
          ),
          SliverToBoxAdapter(
            child: WisCard(
                margin:
                    EdgeInsets.symmetric(horizontal: 15.pt, vertical: 10.pt),
                color: Colors.white,
                child: Wisdom.column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  padding:
                      EdgeInsets.symmetric(horizontal: 20.pt, vertical: 25.pt),
                  color: Colors.white,
                  children: [
                    Wisdom.row(children: [
                      WisText(
                        '金额详情',
                        size: 17.pt,
                        weight: FontWeight.w600,
                        color: colorScheme.mainTitle,
                      ),
                      if (detail?.moneyFlow == 'out')
                        WisText(
                          '（退费）',
                          size: 17.pt,
                          weight: FontWeight.w600,
                          color: colorScheme.mainTitle,
                        ),
                    ]),

                    Divider(
                      color: colorScheme.placeholder2,
                      height: 25.pt,
                    ),

                    /// 将相同的收费项目名称的进行账期合并
                    for (int j = 0; j < store.feeTypes.length; j++)
                      Wisdom.column(
                        margin: EdgeInsets.only(
                          top: 10.pt,
                        ),
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Wisdom.row(
                            margin: EdgeInsets.only(left: 10.pt, right: 10.pt),
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              WisText(
                                store.feeTypes[j],
                                size: 16.pt,
                                bold: true,
                                color: colorScheme.mainTitle,
                              ),
                              WisText(
                                '￥${calcFeeCount(store.feeTypes[j])}',
                                size: 16.pt,
                                bold: true,
                                color: detail?.moneyFlow == 'out'
                                    ? Color(0xffFF495E)
                                    : Color(0xff00C78C),
                              ),
                            ],
                          ),
                          Wisdom.column(
                            color: Color.fromRGBO(246, 247, 252, 1),
                            margin: EdgeInsets.symmetric(vertical: 10.pt),
                            padding: EdgeInsets.symmetric(horizontal: 10.pt),
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.pt)),
                            children: [
                              if (detail?.list != null &&
                                  detail!.list!.length > 0) ...[
                                for (int i = 0; i < detail.list!.length; i++)
                                  Column(children: [
                                    if (detail.list![i].feeType ==
                                        store.feeTypes[j]) ...[
                                      InfoItem2(
                                        title:
                                            '${detail.list![i].feeType ?? '--'}',
                                        content: detail.list![i].fee != null
                                            ? '¥ ' +
                                                detail.list![i].fee.toString()
                                            : '0',
                                        chargeYearMonth:
                                            detail.list![i].chargeYearMonth,
                                      ),
                                    ]
                                  ]),
                              ],
                            ],
                          ),
                        ],
                      )
                  ],
                )),
          ),
        ],
      ),
    );
  }
}

class detailInfo extends StatelessWidget {
  const detailInfo({Key? key, this.detail}) : super(key: key);
  final detail;
  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    final store = Provider.of<PrivateIndexStore>(context);

    return Wisdom.column(
      color: Colors.white,
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      padding: EdgeInsets.only(top: 10.pt),
      margin: EdgeInsets.only(bottom: 15.pt),
      children: <Widget>[
        InfoItem(
          title: '缴费类型',
          content: '${store.getBillTypeText(detail)}',
        ),
        InfoItem(
          title: '缴费人',
          content: detail?.payer ?? '--',
        ),
        InfoItem(
          title: '缴费时间',
          content: detail?.payAt ?? '--',
          showTag: detail?.supplement ?? false,
          tagName: '补录',
        ),
        InfoItem(
          title: '缴费资产',
          content: detail?.assetName ?? '--',
        ),
        InfoItem(
          title: '支付方式',
          content: '${detail?.payWay ?? ''} ${detail?.payType ?? ''}',
        ),
        if (detail?.tranNo != null)
          InfoItem(
            title: '第三方订单号',
            content: '${detail?.tranNo ?? '--'}',
          ),
        if (detail?.createBy != null)
          InfoItem(
            title: '创建人',
            content: detail?.createBy ?? '--',
          ),
        InfoItem(
          title: '创建时间',
          content: detail?.createAt ?? '--',
        ),
        if (detail?.bankAccount?.bankAccount != null)
          InfoItem(
            title: '入账账户',
            content: detail?.bankAccount != null
                ? '${detail?.bankAccount?.bank ?? '-'}' +
                    '/' +
                    '${detail?.bankAccount?.bankAccount ?? '-'}'
                : '--',
          ),
        if (detail?.accountAt != null)
          InfoItem(
            title: '到账时间',
            content: detail?.accountAt ?? '--',
          ),
        InfoItem(
          title: '收支编号',
          content: detail?.id ?? '--',
        ),
        InfoItem(
          title: '备注',
          content: detail?.remark == null || detail?.remark == ''
              ? '--'
              : detail?.remark,
        ),
        if ((detail?.invoiceTickets != null &&
                detail!.invoiceTickets!.length > 0) ||
            detail?.receiptTickets != null &&
                detail.receiptTickets!.length > 0) ...[
          Divider(
            height: 10.pt,
            color: Colors.white,
          ),
          DottedLine(
            color: Color(0xffE5E5E5),
          ),
          Wisdom.column(
            color: Color.fromRGBO(246, 247, 252, 1),
            margin: EdgeInsets.symmetric(vertical: 10.pt),
            padding: EdgeInsets.symmetric(horizontal: 10.pt, vertical: 5.pt),
            borderRadius: BorderRadius.all(Radius.circular(8.pt)),
            children: [
              if (detail?.invoiceTickets != null &&
                  detail!.invoiceTickets!.length > 0) ...[
                for (int i = 0; i < detail.invoiceTickets!.length; i++)
                  Wisdom.row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    padding: EdgeInsets.symmetric(vertical: 5.pt),
                    children: [
                      Wisdom(
                        padding: EdgeInsets.symmetric(
                            vertical: 1.5.pt, horizontal: 5.pt),
                        color: detail.invoiceTickets![i].type == 'electronic'
                            ? Color(0xffEAF3FD)
                            : detail.invoiceTickets![i].type == 'redSpecial'
                                ? Color(0xffFEEDEC)
                                : colorScheme.background3,
                        border: Border.all(
                          width: 1.pt,
                          color: detail.invoiceTickets![i].type == 'electronic'
                              ? Color(0xff2D8CF0)
                              : detail.invoiceTickets![i].type == 'redSpecial'
                                  ? Color(0xffF94F48)
                                  : colorScheme.minor,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(2.pt)),
                        child: WisText(
                          " ${store.InvoiceTypes['${detail.invoiceTickets![i].type}'] ?? '--'}",
                          size: 13.pt,
                          color: detail.invoiceTickets![i].type == 'electronic'
                              ? Color(0xff2D8CF0)
                              : detail.invoiceTickets![i].type == 'redSpecial'
                                  ? Color(0xffF94F48)
                                  : colorScheme.minor,
                        ),
                      ),
                      WisText(
                        detail.invoiceTickets![i].ticketNo ?? '--',
                        size: 13.pt,
                      )
                    ],
                  ),
                if (detail?.receiptTickets != null &&
                    detail.receiptTickets!.length > 0) ...[
                  for (int i = 0; i < detail.receiptTickets!.length; i++)
                    Wisdom.row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      padding: EdgeInsets.symmetric(vertical: 5.pt),
                      children: [
                        Wisdom(
                          padding: EdgeInsets.symmetric(
                              vertical: 1.5.pt, horizontal: 5.pt),
                          color: Color(0xffEAF3FD),
                          border:
                              Border.all(width: 1.pt, color: Color(0xff2D8CF0)),
                          borderRadius: BorderRadius.all(Radius.circular(2.pt)),
                          child: WisText(
                              " ${store.InvoiceTypes['${detail.receiptTickets![i].type}'] ?? '--'}",
                              color: Color(0xff2D8CF0)),
                        ),
                        WisText(
                          detail.receiptTickets![i].ticketNo ?? '--',
                        )
                      ],
                    ),
                ],
              ],
            ],
          ),
        ],
      ],
    );
  }
}

class InfoItem extends StatelessWidget {
  const InfoItem({
    Key? key,
    this.title,
    this.content,
    this.chargeYearMonth,
    this.showTag = false,
    this.tagName = '',
  }) : super(key: key);
  final String? title;
  final content;
  final showTag;
  final tagName;
  final chargeYearMonth;
  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;

    return Wisdom.row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      padding: EdgeInsets.symmetric(vertical: 10.pt),
      children: <Widget>[
        if (chargeYearMonth != null) ...[
          WisText(
            chargeYearMonth ?? '',
            size: 15.pt,
            weight: FontWeight.w600,
          ),
          SizedBox(width: 10.pt),
        ],
        WisText(
          title!,
          size: 15.pt,
          weight: FontWeight.w300,
        ),
        SizedBox(width: 15.pt),
        Wisdom.row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            if (showTag)
              WTag(
                plain: true,
                color: Color(0xffBC68F3),
                border: Border.all(color: Color(0xffBC68F3)),
                backgroundColor: Color(0xffBC68F3).withOpacity(0.1),
                child: WisText(
                  '${tagName}',
                  size: 13.pt,
                ),
              ),
            WisText(
              content,
              color: colorScheme.minor,
              size: 15.pt,
              weight: FontWeight.bold,
              textAlign: TextAlign.right,
              // overflow: TextOverflow.ellipsis,
              // maxLines: 1,
            ).asExpanded()
          ],
        ).asFlexible(flex: 1),
      ],
    );
  }
}

class InfoItem2 extends StatelessWidget {
  const InfoItem2({
    Key? key,
    this.title,
    this.content,
    this.chargeYearMonth,
    this.showTag = false,
    this.tagName = '',
  }) : super(key: key);
  final String? title;
  final content;
  final showTag;
  final tagName;
  final chargeYearMonth;
  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;

    return Wisdom.row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      padding: EdgeInsets.symmetric(vertical: 10.pt),
      children: <Widget>[
        if (chargeYearMonth != null) ...[
          WisText(
            chargeYearMonth ?? '',
            size: 15.pt,
            color: colorScheme.minor,
          ),
          SizedBox(width: 10.pt),
        ],
        Wisdom.row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            if (showTag)
              WTag(
                plain: true,
                color: Color(0xffBC68F3),
                border: Border.all(color: Color(0xffBC68F3)),
                backgroundColor: Color(0xffBC68F3).withOpacity(0.1),
                child: WisText(
                  '${tagName}',
                  size: 13.pt,
                ),
              ),
            WisText(
              content,
              color: colorScheme.minor,
              size: 15.pt,
              // weight: FontWeight.bold,
              textAlign: TextAlign.right,
              // overflow: TextOverflow.ellipsis,
              // maxLines: 1,
            ).asExpanded()
          ],
        ).asFlexible(flex: 1),
      ],
    );
  }
}

class DottedLine extends StatelessWidget {
  final double height;
  final Color color;
  final Axis direction;

  const DottedLine({
    this.height = 1,
    this.color = Colors.black,
    this.direction = Axis.horizontal,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final boxWidth = direction == Axis.horizontal
            ? constraints.constrainWidth()
            : constraints.constrainHeight();
        final dashWidth = 10.0;
        final dashHeight = height;
        final dashCount = (boxWidth / (2 * dashWidth)).floor();
        return Flex(
          children: List.generate(dashCount, (_) {
            return SizedBox(
              width: direction == Axis.horizontal ? dashWidth : dashHeight,
              height: direction == Axis.horizontal ? dashHeight : dashWidth,
              child: DecoratedBox(
                decoration: BoxDecoration(color: color),
              ),
            );
          }),
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          direction: direction,
        );
      },
    );
  }
}
