/// Flutter code sample for BottomNavigationBar

// This example shows a [BottomNavigationBar] as it is used within a [Scaffold]
// widget. The [BottomNavigationBar] has four [BottomNavigationBarItem]
// widgets, which means it defaults to [BottomNavigationBarType.shifting], and
// the [currentIndex] is set to index 0. The selected item is amber in color.
// With each [BottomNavigationBarItem] widget, backgroundColor property is
// also defined, which changes the background color of [BottomNavigationBar],
// when that item is selected. The `_onItemTapped` function changes the
// selected item's index and displays a corresponding message in the center of
// the [Scaffold].

import 'package:flutter/material.dart';
import 'package:jubo/event.dart';
import 'package:jubo/model/modelEvent_Artist.dart';
import 'package:jubo/ui/formDirect.dart';
import 'package:jubo/ui/loading.dart';
import 'model/modelDirect.dart';
import 'splash.dart';
import 'event.dart';
import 'model/modelOrder.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'util/params.dart';
import 'dart:convert';
import 'formOrder.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:jubo/control/genericService.dart' as generic;

class OrderCustomer extends StatefulWidget {
  OrderCustomer(
      {this.idEvent_Artist,
      this.person_artist_name,
      this.person_artist_id,
      this.note,
      this.person_customer_id,
      this.id_event});
  final int idEvent_Artist;
  final String person_artist_name;
  final int person_artist_id;
  final String note;
  final int person_customer_id;
  final int id_event;

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

class OrderCustomerState extends State<OrderCustomer> {
  static BuildContext contextGlobal;
  bool loading = false;
  List<ModelOrder> listOrder;
  List<ModelDirect> listDirect;
  double totalOrder;

  void _onItemTapped(int index) {
    setState(() {});
  }

  void initState() {
    super.initState();
    getOrders();
  }

  @override
  Widget build(BuildContext context) {
    contextGlobal = context;
    return Scaffold(
      appBar: PreferredSize(
          preferredSize: Size.fromHeight(60.0),
          child: AppBar(
              leading: ElevatedButton(
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all<Color>(
                        Color.fromRGBO(68, 49, 122, 1.0))),
                child: Icon(
                  Icons.arrow_back,
                  color: Color.fromRGBO(103, 197, 180, 1.0),
                ),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              centerTitle: true,
              title: Image.asset(
                'assets/images/Jubo_Logo_White.png',
                width: 200,
              ),
              backgroundColor: Color.fromRGBO(68, 49, 122, 1.0))),
      body: Container(
        color: COLOR_TERTIARY,
        child: Column(mainAxisSize: MainAxisSize.max, children: [
          Container(
            color: COLOR_LINE_1,
            width: double.infinity,
            height: 100,
            child: Row(
              children: [
                Container(
                  color: COLOR_PRIMARY,
                  width: 100,
                  height: 100,
                  child: Image(
                    fit: BoxFit.fill,
                    image: NetworkImage(
                        "$urlPrincipal/ws_jubo/service/v1/person/photo/${widget.person_artist_id}"),
                  ),
                ),
                Expanded(
                  child: ListTile(
                    dense: true,
                    title: Text(
                      this.widget.person_artist_name,
                      style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: COLOR_PRIMARY),
                    ),
                    subtitle: Text(
                      this.widget.note,
                      style: TextStyle(
                        fontSize: 12,
                        color: COLOR_TERTIARY,
                      ),
                    ),
                  ),
                ),
                Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Container(
                      padding: EdgeInsets.only(top: 2, bottom: 2, right: 5),
                      width: 80,
                      height: 35,
                      child: ElevatedButton(
                          onPressed: () => goForm(0, "", "", 0.00, ""),
                          style: ElevatedButton.styleFrom(
                            primary: Color.fromRGBO(47, 99, 41, 1.0),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5),
                                side: BorderSide(color: COLOR_PRIMARY)),
                          ),
                          child: Icon(
                            Icons.add,
                            size: 16,
                          )
                          /*
                        Text(
                          '+',
                          style: TextStyle(

                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),*/
                          ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 2, bottom: 2, right: 5),
                      width: 80,
                      height: 35,
                      child: ElevatedButton(
                          onPressed: () => goFormDirect(),
                          style: ElevatedButton.styleFrom(
                            primary: Color.fromRGBO(86, 114, 147, 1.0),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5),
                                side: BorderSide(
                                    color: Color.fromRGBO(62, 82, 104, 1.0))),
                          ),
                          child: Icon(
                            Icons.chat,
                            size: 16,
                          )
                          /*
                        Text(
                          '...',
                          style: TextStyle(

                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),*/
                          ),
                    ),
                    //Container(color: COLOR_PRIMARY,height: 2,width: 80,),
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.only(top: 2, bottom: 2, right: 5),
                        child: ClipRRect(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(5),
                              bottomRight: Radius.circular(5),
                              topLeft: Radius.circular(5),
                              topRight: Radius.circular(5)),
                          child: Container(
                            color: Color.fromRGBO(99, 41, 64, 1.0),
                            width: 75,
                            child: Center(
                              child: Text(
                                NumberFormat.currency(
                                        locale: 'pt_BR',
                                        decimalDigits: 2,
                                        customPattern: '#,###.#')
                                    .format(loading ? 0.00 : totalOrder),
                                style: TextStyle(
                                    color: COLOR_FONT_1,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ],
            ),
          ),
          Expanded(
            child: loading
                ? Loading()
                : RefreshIndicator(
                    onRefresh: () => getOrders(),
                    child: Container(
                      child: Column(mainAxisSize: MainAxisSize.max,
                          //color: COLOR_TERTIARY,
                          children: [
                            //SizedBox(height: 4),
                            listDirect.isNotEmpty
                                ? Container(
                                    height: 45,
                                    width: double.infinity,
                                    padding: EdgeInsets.only(left: 20),
                                    alignment: Alignment.centerLeft,
                                    child: Text(
                                      "Directs",
                                      style: TextStyle(
                                        color: COLOR_FONT_1,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    decoration: BoxDecoration(
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.black26,
                                          offset: Offset(0, 2),
                                          blurRadius: 6.0,
                                        ),
                                      ],
                                      color: COLOR_PRIMARY,
                                      borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(0),
                                          topRight: Radius.circular(0)),
                                    ),
                                  )
                                : SizedBox(),
                            listDirect.isNotEmpty
                                ? Container(
                                    height: 100,
                                    child: directsListView(listDirect))
                                : SizedBox(),

                            Container(
                              height: 45,
                              width: double.infinity,
                              padding: EdgeInsets.only(left: 20),
                              alignment: Alignment.centerLeft,
                              child: Text(
                                "Musicas",
                                style: TextStyle(
                                  color: COLOR_FONT_1,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              decoration: BoxDecoration(
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black26,
                                    offset: Offset(0, 2),
                                    blurRadius: 6.0,
                                  ),
                                ],
                                color: COLOR_PRIMARY,
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(0),
                                    topRight: Radius.circular(0)),
                              ),
                            ),
                            Expanded(child: ordersListView(listOrder)),
                          ]
                          /*FutureBuilder<List<ModelOrder>>(
                  future: getOrders(),
                  builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        List<ModelOrder> data = snapshot.data;
                        return ordersListView(data);
                      } else if (snapshot.hasError) {
                        return Text("${snapshot.error}");
                      }
                      return CircularProgressIndicator();
                  },
                ),*/
                          ),
                    ),
                  ),
          )
        ]),
      ),

      /*persistentFooterButtons: <Widget>[
        IconButton(icon: Icon(Icons.insert_emoticon),onPressed: () {}),
      ],*/
    );
  }

  Future<void> getOrders() async {
    setState(() {
      loading = true;
      totalOrder = 0.0;
    });

    await Future.delayed(Duration(seconds: 1));
    List<ModelOrder> list_order;
    List<ModelDirect> list_direct;
    List<ModelOrder> filteredList = [];
    double valueOrder = 0.0;
    print("aqui");
    print(widget.person_customer_id);
    print(widget.idEvent_Artist);
    final response1 = await http.get(
        "$urlPrincipal/ws_jubo/service/v1/direct/all?"
        "id_person_customer=${widget.person_customer_id}"
        "&id_event_artist=${widget.idEvent_Artist}",
        headers: {"Accept": "application/json"});

    if (response1.statusCode == 200) {
      List jsonResponse = json.decode(response1.body)['data'];
      list_direct =
          jsonResponse.map((job) => new ModelDirect.fromJson(job)).toList();

      for (var item in list_direct) {
        valueOrder = valueOrder + item.value;
      }

      final response2 = await http.get(
          "$urlPrincipal/ws_jubo/service/v1/order/all?"
          "id_person_customer=${widget.person_customer_id}"
          "&id_event_artist=${widget.idEvent_Artist}",
          headers: {"Accept": "application/json"});

      if (response2.statusCode == 200) {
        List jsonResponse = json.decode(response2.body)['data'];
        list_order =
            jsonResponse.map((job) => new ModelOrder.fromJson(job)).toList();

        for (var item in list_order) {
          filteredList.add(item);
          if (item.status == 'Finalized') {
            valueOrder = valueOrder + item.value;
          }
        }

        setState(() {
          loading = false;
          listOrder = filteredList;
          listDirect = list_direct;
          totalOrder = valueOrder;
        });
        //return jsonResponse.map((job) => new ModelOrder.fromJson(job)).toList();
      } else {
        setState(() {
          loading = false;
        });
        throw Exception('Failed to load jobs from API');
      }
    } else {
      setState(() {
        loading = false;
      });
      throw Exception('Failed to load jobs from API');
    }
  }

  Future<void> deleteOrder(int id) async {
    setState(() {
      loading = true;
    });
    await Future.delayed(Duration(seconds: 1));

    String method = "/ws_jubo/service/v1/order/";

    http.Response result = await generic.requestDelete(id, method, "");

    Map<String, dynamic> body = jsonDecode(result.body);

    if (result.statusCode == 200 && body['error'] != true) {
      await getOrders();
      //return jsonResponse.map((job) => new ModelOrder.fromJson(job)).toList();
    } else {
      setState(() {
        loading = false;
      });
      throw Exception('Failed to load jobs from API');
    }
  }

  Container eventsListView(data) {
    return Container(
      child: Text(data.person_artist_name),
    );
  }

  ListView ordersListView(data) {
    return ListView.builder(
        itemCount: data.length,
        padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
        itemBuilder: (context, index) {
          return _card(
              data[index].id,
              data[index].value,
              data[index].text_artist,
              data[index].text_music,
              data[index].person_customer_name,
              data[index].person_customer_id,
              data[index].note,
              data[index].status);
        });
  }

  ListView directsListView(data) {
    return ListView.builder(
        itemCount: data.length,
        padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
        itemBuilder: (context, index) {
          return _cardDirects(
              data[index].id, data[index].value, data[index].note);
        });
  }

  void clickAlert(id) {
    showDialog(
        context: contextGlobal,
        builder: (contextGlobal) {
          return AlertDialog(
            title: new Text("Evento"),
            content: new Text("Selecionado: " + id.toString()),
          );
        });
  }

  clickViewImage(int image) {
    showDialog(
        context: contextGlobal,
        builder: (contextGlobal) {
          return Container(
            width: 200,
            height: 200,
            child: Image(
              image: NetworkImage(
                  "$urlPrincipal/ws_jubo/service/v1/person/photo/$image"),
            ),
          );
        });
  }

  String removeAcento(String text) {
    text = text.toLowerCase();
    text = text.replaceAll(new RegExp(r'[ÁÀÂÃ]', caseSensitive: false), 'a');
    text = text.replaceAll(new RegExp(r'[ÉÈÊ]', caseSensitive: false), 'e');
    text = text.replaceAll(new RegExp(r'[ÍÌÎ]', caseSensitive: false), 'i');
    text = text.replaceAll(new RegExp(r'[ÓÒÔÕ]', caseSensitive: false), 'o');
    text = text.replaceAll(new RegExp(r'[ÚÙÛ]', caseSensitive: false), 'u');
    text = text.replaceAll(new RegExp(r'[Ç]', caseSensitive: false), 'c');
    text = text.replaceAll(new RegExp(r"\s+\b|\b\s"), '-');
    return text;
  }

  void goForm(int idOrder, String artist_name, String music_name, double value,
      String note) {
    print(idOrder);
    if (idOrder == 0) {
      Navigator.push(
          contextGlobal,
          MaterialPageRoute(
              builder: (context) => FormOrder(
                    id_person_customer: widget.person_customer_id,
                    id_event: widget.id_event,
                    id_person_artist: widget.person_artist_id,
                    id_event_artist: widget.idEvent_Artist,
                    artist_name: "",
                    music_name: "",
                    value: 5.00,
                    note: "",
                    status: "Pending",
                  ))).then((value) {
        bool reload = value;
        if (reload) {
          getOrders();
        }
      });
    } else {
      Navigator.push(
          contextGlobal,
          MaterialPageRoute(
              builder: (context) => FormOrder(
                    idOrder: idOrder,
                    id_person_customer: widget.person_customer_id,
                    id_event: widget.id_event,
                    id_person_artist: widget.person_artist_id,
                    id_event_artist: widget.idEvent_Artist,
                    artist_name: artist_name,
                    music_name: music_name,
                    value: value,
                    note: note,
                    status: "Pending",
                  ))).then((value) {
        bool reload = value;
        if (reload) {
          getOrders();
        }
      });
    }
  }

  void goFormDirect() {
    Navigator.push(
        contextGlobal,
        MaterialPageRoute(
            builder: (context) => FormDirect(
                person_customer_id: widget.person_customer_id,
                id_event: widget.id_event,
                id_person_artist: widget.person_artist_id,
                id_event_artist: widget.idEvent_Artist))).then((value) {
      bool reload = value;
      if (reload) {
        getOrders();
      }
    });
  }

  abrirUrl(url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  void clickEvent(id, text_artist, text_music, value, note) {
    showDialog(
        context: contextGlobal,
        builder: (context) {
          return Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                MaterialButton(
                  color: Colors.orange,
                  padding: EdgeInsets.all(20),
                  elevation: 5,
                  onPressed: () {
                    if (text_artist == '') {
                      abrirUrl('https://m.cifraclub.com.br/?q=' +
                          removeAcento(text_music));
                    } else {
                      abrirUrl('https://m.cifraclub.com.br/' +
                          removeAcento(text_artist) +
                          '/' +
                          removeAcento(text_music));
                    }
                  },
                  child: Icon(
                    Icons.music_note_rounded,
                    color: Colors.white,
                  ),
                ),
                MaterialButton(
                  color: Colors.blue,
                  padding: EdgeInsets.all(20),
                  onPressed: () {
                    Navigator.pop(context);
                    goForm(id, text_artist, text_music, value, note);
                  },
                  child: Icon(
                    Icons.search_rounded,
                    color: Colors.white,
                  ),
                ),
                MaterialButton(
                  color: Colors.redAccent,
                  padding: EdgeInsets.all(20),
                  onPressed: () {
                    deleteOrder(id);
                    Navigator.pop(context);
                  },
                  child: Icon(
                    Icons.delete_outline_rounded,
                    color: Colors.white,
                  ),
                )
              ]);
        });
  }

  /*
   new Card(
                child: new Container(
                  padding: new EdgeInsets.all(32.0),
                  child: new Column(
                    children: <Widget>[
                      new Text('Hello World'),
                      new Text('How are you?')
                    ],
                  ),
                ),
              ),
   */

  Card _cardDirects(int id, double value, String note) => Card(
      color: Color.fromRGBO(68, 49, 122, 0.5450980392156862),
      borderOnForeground: true,
      child: ListTile(
        enabled: false,
        dense: false,
        onTap: () {
          // clickEvent(id, text_artist, text_music, value, note);
        },
        shape: null,
        title: Text(note,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 12,
              color: COLOR_FONT_1_DISABLED,
            )),
        subtitle: Text(""),
        trailing: ClipRRect(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(5),
              bottomRight: Radius.circular(5),
              topLeft: Radius.circular(5),
              topRight: Radius.circular(5)),
          child: Container(
            padding: EdgeInsets.all(4),
            color: COLOR_SECONDARY_DISABLED,
            child: Text(
              NumberFormat.currency(
                      locale: 'pt_BR',
                      decimalDigits: 2,
                      customPattern: '#,###.#')
                  .format(value.toDouble()),
              style: TextStyle(
                  color: Color.fromRGBO(68, 49, 122, 1.0),
                  fontWeight: FontWeight.bold),
            ),
          ),
        ),
        isThreeLine: true,
      ));

  Card _card(
          int id,
          double value,
          String text_artist,
          String text_music,
          String person_customer_name,
          int person_customer_id,
          String note,
          String status) =>
      Card(
          color: status == "Pending"
              ? Color.fromRGBO(68, 49, 122, 1.0)
              : status == "Finalized"
                  ? Color.fromRGBO(68, 49, 122, 0.5450980392156862)
                  : Color.fromRGBO(99, 41, 64, 1.0),
          borderOnForeground: true,
          child: ListTile(
            enabled: status == "Pending",
            dense: true,
            onTap: () {
              clickEvent(id, text_artist, text_music, value, note);
            },
            shape: null,
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    text_artist == ""
                        ? Text("")
                        : Icon(
                            Icons.person,
                            size: 14,
                            color: status == "Pending"
                                ? COLOR_FONT_1
                                : COLOR_FONT_1_DISABLED,
                          ),
                    Text(" " + text_artist,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: status == "Pending"
                              ? COLOR_FONT_1
                              : COLOR_FONT_1_DISABLED,
                        )),
                  ],
                ),
                SizedBox(
                  height: 6,
                ),
                Row(
                  children: [
                    text_music == ""
                        ? Text("")
                        : Icon(
                            Icons.music_note,
                            size: 14,
                            color: status == "Pending"
                                ? COLOR_FONT_1
                                : COLOR_FONT_1_DISABLED,
                          ),
                    Text(" " + text_music,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: status == "Pending"
                              ? COLOR_FONT_1
                              : COLOR_FONT_1_DISABLED,
                        )),
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
              ],
            ),
            subtitle: Text(
              note,
              style: TextStyle(
                color: COLOR_LINE_1,
              ),
            ),
            trailing: ClipRRect(
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(5),
                  bottomRight: Radius.circular(5),
                  topLeft: Radius.circular(5),
                  topRight: Radius.circular(5)),
              child: Container(
                padding: EdgeInsets.all(4),
                color: status == "Pending"
                    ? COLOR_SECONDARY
                    : COLOR_SECONDARY_DISABLED,
                child: Text(
                  status == "Finalized"
                      ? "Finalizado"
                      : status == "Canceled"
                          ? "Cancelado"
                          : status == "Pending"
                              ? NumberFormat.currency(
                                      locale: 'pt_BR',
                                      decimalDigits: 2,
                                      customPattern: '#,###.#')
                                  .format(value.toDouble())
                              : Text(""),
                  style: TextStyle(
                      color: Color.fromRGBO(68, 49, 122, 1.0),
                      fontWeight: FontWeight.bold),
                ),
              ),
            ),
            isThreeLine: true,
          ));
}
