import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/services/customer.service.dart';
import 'package:echo_app/widgets/no_data.widget.dart';
import '../../theme/variables.dart';
import './widgets/total_box.dart';
import 'package:echo_app/shared/core.session.dart';

import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'widgets/soa_report_Item.page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

// ignore: must_be_immutable
class SOAReprot extends StatefulWidget {
  @override
  _SOAReprotState createState() => _SOAReprotState();
}

class _SOAReprotState extends State<SOAReprot> {
  var textStyle = TextStyle(fontSize: 16);
  var textStyle2 = TextStyle(fontSize: 16, fontWeight: FontWeight.bold);
  var textStyleToDate =
      TextStyle(fontSize: 16, color: Colors.grey, fontWeight: FontWeight.bold);
  var customerService = new CustomerService();
  var allTransactions = [];
  var segment;
  var transactions = [];
  double netTotal = 0;
  String totalClass = '';

  initState() {
    this.allTransactions = [];
    this.transactions = [];
    this.netTotal = 0;
    this.getSOA();
    super.initState();
  }

  getSOA() async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await this.customerService.getCustomerSOA();
    EasyLoading.dismiss();
    setState(() {
      if (response['status'] == GlobalErrors.Success.index &&
          response['data'].length > 0) {
        this.allTransactions = response['data'];
      } else {
        this.allTransactions = [];
      }
      this.segment =
          CoreSession.currentOperator['operatorCustomers'][0]['mainDivisionId'];
      this.populateSOA(CoreSession.currentOperator['operatorCustomers'][0]);
    });
  }

  populateSOA(user) {
    setState(() {
      this.transactions = this
          .allTransactions
          .where((op) =>
              op['customerId'] == user['customerId'] &&
              op['outletId'] == user['outletId'])
          .toList();

      this.netTotal = 0;
      for (var a in this.transactions) {
        if (a['typeId'] == 1) {
          a['class'] = 'debit';
          this.netTotal = this.netTotal + a['remainingAmount'];
        } else {
          a['class'] = 'credit';
          this.netTotal = this.netTotal - a['remainingAmount'];
        }
      }

      if (this.netTotal >= 0) {
        this.totalClass = 'debit';
      } else {
        this.totalClass = 'credit';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
           backgroundColor: Variables.color_primary,
            title: Text("soa".tr),
            automaticallyImplyLeading: false,
            actions: <Widget>[
              IconButton(
                  icon: Icon(Icons.close),
                  onPressed: () {
                    Navigator.pop(context);
                  }),
            ]),
        body:  this.transactions.length ==0 ? NoDataWidget():Column(
          children: [
            Expanded(
              flex: 10,
              child: GridView.builder(
                  padding: const EdgeInsets.all(10.0),
                  itemCount: this.transactions.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: size.width >= 768 ? 3 : 2,
                    //childAspectRatio: itemWidth / itemHeight,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                  ),
                  itemBuilder: (ctx, i) => SOAReportItem(this.transactions[i])),
            ),
            Expanded(
              flex: 1,
              child: TotalBox(this.netTotal, this.totalClass),
            )
          ],
        ),
      ),
    );

    // Container(
    //   height: size.height,
    //   child: ListView.builder(
    //       itemBuilder: (ctx, index) {
    //         return Card(
    //           child: Container(
    //             padding: EdgeInsets.symmetric(vertical: 15, horizontal: 15),
    //             child: Column(
    //               children: <Widget>[
    //                 Container(
    //                   padding: EdgeInsets.only(bottom: 5),
    //                   child: Row(
    //                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
    //                     children: <Widget>[
    //                       Text(
    //                         "trans-id".tr + ": CN-S1-000001",
    //                         style: textStyle,
    //                       ),
    //                       Text(
    //                         "20/01/2021",
    //                         style: textStyleToDate,
    //                       )
    //                     ],
    //                   ),
    //                 ),
    //                 Container(
    //                   child: Row(
    //                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
    //                     children: <Widget>[
    //                       Wrap(children: <Widget>[
    //                         Text(
    //                           "original".tr + "(SAR): ",
    //                           style: textStyle,
    //                         ),
    //                         Text(
    //                           "1500",
    //                           style: textStyle2,
    //                         )
    //                       ]),
    //                       Wrap(children: <Widget>[
    //                         Text(
    //                           "remaining".tr + "(SAR): ",
    //                           style: textStyle,
    //                         ),
    //                         Text(
    //                           "1301.54",
    //                           style: textStyle2,
    //                         )
    //                       ])
    //                     ],
    //                   ),
    //                 )
    //               ],
    //             ),
    //           ),
    //         );
    //       },
    //       itemCount: 20),
    // ),
  }
}
