import 'dart:convert';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/electric.dart';
import 'package:mwf_app/service/api.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';
import 'package:flutter_echarts/flutter_echarts.dart';

class ElectricStatistics extends StatefulWidget {
  @override
  _ElectricStatisticsState createState() => _ElectricStatisticsState();
}

TextEditingController startDate = TextEditingController(); //วันเริ่มต้น
TextEditingController endDate = TextEditingController(); //วันสิ้นสุด
String staticName = '';
dynamic dataChart;

class _ElectricStatisticsState extends State<ElectricStatistics> {
  String strStartDate = "";
  String strEndDate = "";
  List<dynamic> months = [];
  List<dynamic> val = [];
  bool isSearh = false;
  bool isLoading = false;
  final sepnumber = new NumberFormat("#,##0");
  //  เดือน 12 เดือน
  int month1,
      month2,
      month3,
      month4,
      month5,
      month6,
      month7,
      month8,
      month9,
      month10,
      month11,
      month12;
  List<KeyValueModel> _dropdownStatistic = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownPeaNolist = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  var data = [
    new ClicksPerYear('ม.ค.', 290, AppColors.color_gold),
    new ClicksPerYear('ก.พ.', 790, AppColors.color_gold),
    new ClicksPerYear('มี.ค.', 690, AppColors.color_gold),
    new ClicksPerYear('เม.ย..', 290, AppColors.color_gold),
    new ClicksPerYear('พ.ค..', 650, AppColors.color_gold),
    new ClicksPerYear('มิ.ย.', 1090, AppColors.color_gold),
    new ClicksPerYear('ก.ค.', 590, AppColors.color_gold),
    new ClicksPerYear('ส.ค.', 890, AppColors.color_gold),
    new ClicksPerYear('ก.ย..', 1190, AppColors.color_gold),
    new ClicksPerYear('ต.ค..', 1090, AppColors.color_gold),
    new ClicksPerYear('พ.ย.', 880, AppColors.color_gold),
    new ClicksPerYear('ธ.ค.', 1430, AppColors.color_gold),
  ];
  static List<ElectricDropdown> dataStatistic = [];
  String selectedStatisticName = "";
  String selectedPeaNo = "";
  @override
  void initState() {
    //SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.portraitUp]);
    super.initState();
    //getData();
    print("AppUrl.Electric_ID ::: " + AppUrl.Electric_ID);
    loadDatalistStatisticType();
    startDate.text = "";
    endDate.text = "";
    if (startDate.text.isEmpty && endDate.text.isEmpty) {
      startDate.text =
          AppConvert.dateToBud(DateTime(DateTime.now().year, 1, 1).toString())
              .toString();
      strStartDate = DateTime(DateTime.now().year, 1, 1).toString();
      endDate.text =
          AppConvert.dateToBud(DateTime(DateTime.now().year, 12, 31).toString())
              .toString();
      strEndDate = DateTime(DateTime.now().year, 12, 31).toString();
    }
    Intl.defaultLocale = 'th';
    initializeDateFormatting();
  }

  @override
  void dispose() {
    //SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    super.dispose();
  }

  loadDatalistStatisticType() async {
    setState(() {
      isLoading = true;
    });
    final listStatistic =
        await getDataStatisticName(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
//    listGroupType.forEach((v) {
    for (var i = 0; i < listStatistic.length; i++) {
      setState(() {
        _dropdownStatistic.add(
          KeyValueModel(
            key: listStatistic[i]['StatisticName'].toString(),
            // key คือค่าที่แสดง
            value: listStatistic[i]['StatisticCode']
                .toString(), // value ค่าที่บันทึก
          ),
        );
      });
      //print(_dropdownStatistic);
    }
//    });
    final listPeaNolist = await getDataPeaNolist();
//    listPeaNolist.forEach((v) {
    for (var i = 0; i < listPeaNolist.length; i++) {
      //print(listPeaNolist[i]);
      setState(() {
        _dropdownPeaNolist.add(
          KeyValueModel(
            key: (i + 1).toString() +
                '. รหัสเครื่องวัด : ' +
                listPeaNolist[i]['PeaNo'].toString() +
                "\nที่อยู่ : " +
                listPeaNolist[i]['InstallationAddress'].toString() +
                "\n",
            // key คือค่าที่แสดง
            value: listPeaNolist[i]['PeaNo'].toString(), // value ค่าที่บันทึก
          ),
        );
        selectedPeaNo = _dropdownPeaNolist[1].value;
      });
    }
//    });
    setState(() {
      isLoading = false;
    });
    return "xx";
  }

  static getDataStatisticName() async {
    final response = await AppApi.apiGetRequest(AppUrl.Eletric_Dropdownlist +
        "?AuthenKey=" +
        AppUrl.AuthenKey); // เรียกใช้ api

    dataStatistic.clear(); // เคลียข้อมูลเดิมออกก่อน
    return response;
  }

  static getDataPeaNolist() async {
    final response = await AppApi.apiGetRequest(AppUrl.PeaNolist +
        "?CA=" +
        AppUrl.CA +
        "&AuthenKey=" +
        AppUrl.AuthenKey); // เรียกใช้ api

    dataStatistic.clear(); // เคลียข้อมูลเดิมออกก่อน
    return response;
  }

  //ต้องทำ api อันนี้มานะครับ เป็น 12 เดือน ทำเสร็จแล้วไปเปิดเรียกใช้ที่ initState ด้วย แล้วก็ปิดข้อมูลเทสข้างล่าง
  getData() async {
    var res = await Electric.getData();
    print(res);
    //  ถ้ามี api เปิดอันนี้นะ

    setState(() {
      // month1 = res['data']['month1'];
      // month2 = res['data']['month2'];
      // month3 = res['data']['month3'];
      // month4 = res['data']['month4'];
      // month5 = res['data']['month5'];
      // month6 = res['data']['month6'];
      // month7 = res['data']['month7'];
      // month8 = res['data']['month8'];
      // month9 = res['data']['month9'];
      // month10 = res['data']['month10'];
      // month11 = res['data']['month11'];
      // month12 = res['data']['month12'];
    });

    setState(() {
      var data = [
        // new ClicksPerYear('ม.ค.', month1, AppColors.color_gold),
        // new ClicksPerYear('ก.พ.', month2, AppColors.color_gold),
        // new ClicksPerYear('มี.ค.', month3, AppColors.color_gold),
        // new ClicksPerYear('เม.ย..', month4, AppColors.color_gold),
        // new ClicksPerYear('พ.ค..', month5, AppColors.color_gold),
        // new ClicksPerYear('มิ.ย.', month6, AppColors.color_gold),
        // new ClicksPerYear('ก.ค.', month7, AppColors.color_gold),
        // new ClicksPerYear('ส.ค.', month8, AppColors.color_gold),
        // new ClicksPerYear('ก.ย..', month9, AppColors.color_gold),
        // new ClicksPerYear('ต.ค..', month10, AppColors.color_gold),
        // new ClicksPerYear('พ.ย.', month11, AppColors.color_gold),
        // new ClicksPerYear('ธ.ค.', month12, AppColors.color_gold),
        // new ClicksPerYear('ธ.ค.', month12, AppColors.color_gold),
      ];
    });
  }

  reloadDataChart() async {
    var year;
    var month;
    var monthOfYears;
    data.clear();
    val.clear();
    months.clear();
    print("elec data len : " + Electric.data.length.toString());
    for (int i = 0; i < Electric.data.length; i++) {
//        setState(() {
      year = int.parse(Electric.data[i].text.split(".").last);
      month = Electric.data[i].text.split("2").first;
      monthOfYears = month + " " + year.toString();

      val.add(double.parse(Electric.data[i].value).toInt());
      months.add(monthOfYears);
    }
    print("data len :: " + data.length.toString());
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;
    // print("Width size :: "+_width.toString());
    // print("Height size :: "+_height.toString());

    var series = [
      charts.Series(
        domainFn: (ClicksPerYear clickData, _) => clickData.year,
        measureFn: (ClicksPerYear clickData, _) => clickData.clicks,
        colorFn: (ClicksPerYear clickData, _) => clickData.color,
        id: 'Clicks',
        data: data,
      ),
    ];

    // print(months);
    // print("len months : "+months.length.toString());
    // print("-----------");
    // print(val);
    // print("len val : "+val.length.toString());
    var _results = jsonEncode(months);
    var _val = jsonEncode(val);
    var _spaceLeft = mediaQuery(context, "w", 59);
    print(_val);
    var newGraph = Container(
      child: Echarts(
        option: '''
        {
          xAxis: [{
            type: 'category',
            data: $_results,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              rotate: 45
            }
          }],
          grid: {
            left: "$_spaceLeft%",
            right: "0%"
          },
          yAxis: {
            type: 'value'
          },
          dataZoom: [
            {
              type: 'inside'
            }
          ],
          series: [{
            data: $_val,
            label: {
              show: true,
              position: 'insideBottom',
              distance: 15,
              verticalAlign: 'middle',
              align: 'left',
              rotate: 90,
            },
            type: 'bar',
            itemStyle: {
              color: "rgba(164,129,64,1)",
            }
          }]
        }
      ''',
      ),
      width: mediaQuery(context, 'w', 1125),
      height: mediaQuery(context, 'h', 1700),
    );

    var chart = charts.BarChart(
      series,
      animate: false,

      // domainAxis: charts.OrdinalAxisSpec(
      //   renderSpec: charts.SmallTickRendererSpec(labelRotation: 0),
      // ),
    );

    // var chartWidget = Padding(
    //   padding: EdgeInsets.all(
    //     mediaQuery(context, 'h', 10),
    //   ),
    //   child: SizedBox(
    //     height: 1000,
    //     child: chart
    //   ),
    // );

    var chartWidget = SizedBox(child: chart);

    Widget _landscape() {
      return Stack(
        children: <Widget>[
          Header.headerLandscape(context),
          Header.footermenuLandScape(context),
          Container(
            width: mediaQuery(context, 'w', 1125),
            height: mediaQuery(context, 'h', 1700),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 480),
              left: mediaQuery(context, 'w', 60),
              right: mediaQuery(context, 'w', 60),
            ),
            child: ListView(
              padding: EdgeInsets.only(top: 0),
              children: <Widget>[
                SizedBox(
                  height: mediaQuery(context, 'h', 50),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'รหัสเครื่องวัด',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 70),
                            color: Color(0xFF383838),
                          ),
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 20),
                        ),
                        _buildDropDownPeaListNoLandScape(context),
                      ],
                    ),
                  ],
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 20),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'เลือกสถิติ :',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 70),
                            color: Color(0xFF383838),
                          ),
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 20),
                        ),
                        _buildDropDownStatisticLandScape(context),
                      ],
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'วันเริ่มต้น :',
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 70),
                          ),
                        ),
                        Container(
                          height: mediaQuery(context, 'h', 200),
                          width: mediaQuery(context, 'w', 500),
                          child: GestureDetector(
                            onTap: () async {
                              DateTime newDate = await showRoundedDatePicker(
                                context: context,
                                initialDate: DateTime.parse(strStartDate),
                                firstDate: DateTime(DateTime.now().year - 10),
                                lastDate: DateTime(DateTime.now().year + 10),
                                locale: Locale('th', 'TH'),
                                era: EraMode.BUDDHIST_YEAR,
                                theme:
                                    ThemeData(primarySwatch: Colors.deepPurple),
                                height: 280,
                              );
                              if (newDate != null) {
                                var dtArray = newDate.toString().split(" ");
                                setState(() {
                                  var formatter = DateFormat.yMd();
                                  var showDate = formatter
                                      .formatInBuddhistCalendarThai(newDate);
                                  startDate.text = showDate;
                                  strStartDate = dtArray[0];
                                  print(strStartDate);
                                });
                              }
                            },
                            child: Container(
                              height: mediaQuery(context, 'h', 105),
                              width: mediaQuery(context, 'w', 490),
                              padding: EdgeInsets.only(
                                left: mediaQuery(context, 'h', 50),
                                right: mediaQuery(context, 'h', 80),
                              ),
                              decoration: BoxDecoration(
                                borderRadius: new BorderRadius.all(
                                  Radius.circular(
                                    mediaQuery(
                                      context,
                                      'h',
                                      150,
                                    ),
                                  ),
                                ),
                                border: Border.all(
                                  color: Colors.grey[500],
                                ),
                                color: Colors.white,
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text(startDate.text),
                                  Icon(
                                    Icons.calendar_today,
                                    color: Colors.grey,
                                    size: mediaQuery(
                                      context,
                                      'h',
                                      120,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'วันสิ้นสุด :',
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 70),
                          ),
                        ),
                        Container(
                          height: mediaQuery(context, 'h', 200),
                          width: mediaQuery(context, 'w', 500),
                          child: GestureDetector(
                            onTap: () async {
                              DateTime newDate = await showRoundedDatePicker(
                                context: context,
                                initialDate: DateTime.parse(strEndDate),
                                firstDate: DateTime(DateTime.now().year - 10),
                                lastDate: DateTime(DateTime.now().year + 10),
                                locale: Locale('th', 'TH'),
                                era: EraMode.BUDDHIST_YEAR,
                                theme:
                                    ThemeData(primarySwatch: Colors.deepPurple),
                                height: 280,
                              );
                              if (newDate != null) {
                                var dtArray = newDate.toString().split(" ");
                                setState(() {
                                  var formatter = DateFormat.yMd();
                                  var showDate = formatter
                                      .formatInBuddhistCalendarThai(newDate);
                                  endDate.text = showDate;
                                  strEndDate = dtArray[0];
                                  print("strEndDate $strEndDate");
                                });
                              }
                            },
                            child: Container(
                              height: mediaQuery(context, 'h', 105),
                              width: mediaQuery(context, 'w', 490),
                              padding: EdgeInsets.only(
                                left: mediaQuery(context, 'h', 50),
                                right: mediaQuery(context, 'h', 80),
                              ),
                              decoration: BoxDecoration(
                                borderRadius: new BorderRadius.all(
                                  Radius.circular(
                                    mediaQuery(
                                      context,
                                      'h',
                                      150,
                                    ),
                                  ),
                                ),
                                border: Border.all(
                                  color: Colors.grey[500],
                                ),
                                color: Colors.white,
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text(endDate.text),
                                  Icon(
                                    Icons.calendar_today,
                                    color: Colors.grey,
                                    size: mediaQuery(
                                      context,
                                      'h',
                                      120,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 50),
                ),
                Column(
                  children: <Widget>[
                    SizedBox(
                      width: 700,
                      height: 37,
                      child: RaisedButton(
                        onPressed: () => {
                          searchStatistics(context),
                        },
                        color: AppColors.color_gold,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(18),
                        ),
                        child: Text(
                          'ค้นหา',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                ),
                isSearh == true
                    ? Row(
                        children: [
                          RotatedBox(
                            quarterTurns: -1,
                            child: Text(
                              staticName,
                              style: TextStyle(
                                fontWeight: FontWeight.normal,
                                fontSize: mediaQuery(context, "w", 30),
                                //height: 2,
                                color: AppColors.color_serviceCompany,
                              ),
                            ),
                          ),
                          Expanded(
                            child: Container(
                              //width: mediaQuery(context, 'w', 1300),
                              height: mediaQuery(context, 'h', 1700),
                              margin: EdgeInsets.only(
                                top: mediaQuery(context, 'h', 60),
                              ),
                              padding: EdgeInsets.only(
                                right: mediaQuery(context, 'w', 30),
                              ),
                              decoration: BoxDecoration(
                                borderRadius: new BorderRadius.all(
                                  Radius.circular(
                                    mediaQuery(context, 'h', 40),
                                  ),
                                ),
                                color: Colors.white,
                              ),
                              // child: chartWidget,
                              child: newGraph,
                            ),
                          ),
                        ],
                      )
                    : SizedBox(width: 12, height: 0),
                isSearh == true
                    ? Container(
                        //width: mediaQuery(context, 'w', 1125),
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(
                          top: mediaQuery(context, 'h', 5),
                        ),
                        child: Text(
                          "เดือน",
                          style: TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: mediaQuery(context, "w", 30),
                              color: AppColors.color_serviceCompany),
                        ),
                      )
                    : SizedBox(width: 12, height: 0),
              ],
            ),
          ),
        ],
      );
    }

    Widget _porait() {
      return Stack(
        children: <Widget>[
          Header.header1(context),
          Header.mainMenu(context),
          Container(
            width: mediaQuery(context, 'w', 1125),
            height: mediaQuery(context, 'h', 1200),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 950),
              left: mediaQuery(context, 'w', 60),
              right: mediaQuery(context, 'w', 60),
            ),
            child: ListView(
              padding: EdgeInsets.only(top: 0),
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      'สถิติการใช้ไฟฟ้า',
                      style: TextStyle(
                        color: Color(0xFFB58E38),
                        fontSize: mediaQuery(context, 'h', 58),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 20),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          //'เลือกหมายเลขเครื่องวัด :',
                          'รหัสเครื่องวัด',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 40),
                            color: Color(0xFF383838),
                          ),
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 20),
                        ),
                        _buildDropDownPeaListNo(context),
                      ],
                    ),
                  ],
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 20),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'เลือกสถิติ :',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 40),
                            color: Color(0xFF383838),
                          ),
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 20),
                        ),
                        _buildDropDownStatistic(context),
                      ],
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'วันเริ่มต้น :',
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                        Container(
                          height: mediaQuery(context, 'h', 110),
                          width: mediaQuery(context, 'w', 487),
                          child: GestureDetector(
                            onTap: () async {
                              DateTime newDate = await showRoundedDatePicker(
                                context: context,
                                initialDate: DateTime.parse(strStartDate),
                                firstDate: DateTime(DateTime.now().year - 10),
                                lastDate: DateTime(DateTime.now().year + 10),
                                locale: Locale('th', 'TH'),
                                era: EraMode.BUDDHIST_YEAR,
                                theme:
                                    ThemeData(primarySwatch: Colors.deepPurple),
                                height: 280,
                              );
                              if (newDate != null) {
                                var dtArray = newDate.toString().split(" ");
                                setState(() {
                                  var formatter = DateFormat.yMd();
                                  var showDate = formatter
                                      .formatInBuddhistCalendarThai(newDate);
                                  startDate.text = showDate;
                                  strStartDate = dtArray[0];
                                  print(strStartDate);
                                });
                              }
                            },
                            child: Container(
                              height: mediaQuery(context, 'h', 105),
                              width: mediaQuery(context, 'w', 490),
                              padding: EdgeInsets.only(
                                left: mediaQuery(context, 'h', 20),
                                right: mediaQuery(context, 'h', 20),
                              ),
                              decoration: BoxDecoration(
                                borderRadius: new BorderRadius.all(
                                  Radius.circular(
                                    mediaQuery(
                                      context,
                                      'h',
                                      150,
                                    ),
                                  ),
                                ),
                                border: Border.all(
                                  color: Colors.grey[500],
                                ),
                                color: Colors.white,
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text(startDate.text),
                                  Icon(
                                    Icons.calendar_today,
                                    color: Colors.grey,
                                    size: mediaQuery(
                                      context,
                                      'h',
                                      80,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'วันสิ้นสุด :',
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                        Container(
                          height: mediaQuery(context, 'h', 110),
                          width: mediaQuery(context, 'w', 487),
                          child: GestureDetector(
                            onTap: () async {
                              DateTime newDate = await showRoundedDatePicker(
                                context: context,
                                initialDate: DateTime.parse(strEndDate),
                                firstDate: DateTime(DateTime.now().year - 10),
                                lastDate: DateTime(DateTime.now().year + 10),
                                locale: Locale('th', 'TH'),
                                era: EraMode.BUDDHIST_YEAR,
                                theme:
                                    ThemeData(primarySwatch: Colors.deepPurple),
                                height: 280,
                              );
                              if (newDate != null) {
                                var dtArray = newDate.toString().split(" ");
                                setState(() {
                                  var formatter = DateFormat.yMd();
                                  var showDate = formatter
                                      .formatInBuddhistCalendarThai(newDate);
                                  endDate.text = showDate;
                                  strEndDate = dtArray[0];
                                  print("strEndDate $strEndDate");
                                });
                              }
                            },
                            child: Container(
                              height: mediaQuery(context, 'h', 105),
                              width: mediaQuery(context, 'w', 490),
                              padding: EdgeInsets.only(
                                left: mediaQuery(context, 'h', 20),
                                right: mediaQuery(context, 'h', 20),
                              ),
                              decoration: BoxDecoration(
                                borderRadius: new BorderRadius.all(
                                  Radius.circular(
                                    mediaQuery(
                                      context,
                                      'h',
                                      150,
                                    ),
                                  ),
                                ),
                                border: Border.all(
                                  color: Colors.grey[500],
                                ),
                                color: Colors.white,
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text(endDate.text),
                                  Icon(
                                    Icons.calendar_today,
                                    color: Colors.grey,
                                    size: mediaQuery(
                                      context,
                                      'h',
                                      80,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 50),
                ),
                Column(
                  children: <Widget>[
                    SizedBox(
                      width: 700,
                      height: 37,
                      child: RaisedButton(
                        onPressed: () => {
                          searchStatistics(context),
                        },
                        color: AppColors.color_gold,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(18),
                        ),
                        child: Text(
                          'ค้นหา',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                ),
                isSearh == true
                    ? Row(
                        children: [
                          RotatedBox(
                            quarterTurns: -1,
                            child: Text(
                              staticName,
                              style: TextStyle(
                                  fontWeight: FontWeight.normal,
                                  fontSize: mediaQuery(context, "w", 40),
                                  //height: 2,
                                  color: AppColors.color_serviceCompany),
                            ),
                          ),
                          Expanded(
                            child: Container(
                              //width: mediaQuery(context, 'w', 1120),
                              height: mediaQuery(context, 'h', 1000),
                              margin: EdgeInsets.only(
                                top: mediaQuery(context, 'h', 60),
                              ),
                              decoration: BoxDecoration(
                                borderRadius: new BorderRadius.all(
                                  Radius.circular(
                                    mediaQuery(context, 'h', 40),
                                  ),
                                ),
                                color: Colors.white,
                              ),
                              // child: chartWidget,
                              child: newGraph,
                            ),
                          ),
                        ],
                      )
                    : SizedBox(width: 12, height: 0),
                isSearh == true
                    ? Container(
                        width: mediaQuery(context, 'w', 1125),
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(
                          top: mediaQuery(context, 'h', 5),
                        ),
                        child: Text(
                          "เดือน",
                          style: TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: mediaQuery(context, "w", 40),
                              color: AppColors.color_serviceCompany),
                        ),
                      )
                    : SizedBox(width: 12, height: 0),
              ],
            ),
          ),
        ],
      );
    }

    return Material(
      color: AppColors.bgColor,
      child: OrientationBuilder(
        builder: (BuildContext context, orientation) {
          if (MediaQuery.of(context).orientation == Orientation.landscape) {
            print(orientation);
            return _landscape();
          } else {
            return _porait();
          }
        },
      ),
    );
  }

  searchStatistics(context) async {
    if (selectedPeaNo.toString() != '' &&
        selectedStatisticName.toString().isNotEmpty &&
        strStartDate.toString() != '' &&
        strEndDate.toString() != '') {
      setState(() {
        isLoading = true;
      });
      Map<String, dynamic> data = {
        "EmployeeID": AppUrl.EmployeeID,
        "Eletric_DropdownlistID": "",
        "Eletric_Dropdownlist": "",
        "CA": AppUrl.CA.toString(),
        //  "Startdate_Eletric_Usage": startDate.text,
        //  "Enddate_Eletric_Usage": endDate.text,
        "AuthenKey": AppUrl.AuthenKey.toString(),
        "statisticCode": selectedStatisticName.toString(),
        "startDate": startDate.text,
        "endDate": endDate.text,
      };
      print("=========================DATA================================");
      print(data);
      print("=========================API================================");

      if (strStartDate == "" || strEndDate == "") {
        if (strStartDate != "" && strEndDate == "") {
          print('เลือกวันเริ่มต้น');
          setState(() {
            strEndDate = DateTime(DateTime.now().year, 12, 31).toString();
          });
        } else if (strStartDate == "" && strEndDate != "") {
          print('เลือกวันสิ้นสุด');
          setState(() {
            strStartDate = DateTime(DateTime.now().year, 1, 1).toString();
          });
        } else {
          print('ไม่เลือกวันเริ่มต้น และสิ้นสุด');
          setState(() {
            strStartDate = DateTime(DateTime.now().year, 1, 1).toString();
            strEndDate = DateTime(DateTime.now().year, 12, 31).toString();
          });
        }
      }

      print(
        AppUrl.Electric_Read +
            "?statisticCode=" +
            selectedStatisticName +
            "&ca=" +
            AppUrl.CA +
            "&peaNo=" +
            selectedPeaNo +
            "&startDate=" +
            strStartDate +
            "&endDate=" +
            strEndDate +
            "&AuthenKey=" +
            AppUrl.AuthenKey,
      );

      final list = await AppApi.apiGetRequest(
        AppUrl.Electric_Read +
            "?statisticCode=" +
            selectedStatisticName +
            "&ca=" +
            AppUrl.CA +
            "&peaNo=" +
            selectedPeaNo +
            "&startDate=" +
            strStartDate +
            "&endDate=" +
            strEndDate +
            "&AuthenKey=" +
            AppUrl.AuthenKey,
      ); // เรียกใช้ api
      print("=========================data2================================");
      print(data);
      data.clear(); // เคลียข้อมูลเดิมออกก่อน
      print("=========================list================================");
      print(list);
      print("=========================data2================================");
      print(data);
      //if (list['statusCode'] != 0) {
      // var lists = await Electric.searchData(data);
      // print(lists);

      Electric.data.clear();
      print("=========================forEach================================");

      setState(() {
        isSearh = true;
        final listChart = list['StatisticValues'];
        listChart.forEach((v) {
          final statisticsList = Electric.fromJson(v);
          Electric.data.add(statisticsList);
        });
        reloadDataChart();
      });
      //await new Future.delayed(const Duration(seconds: 2));
      setState(() {
        isLoading = false;
      });
    } else {
      print('strStartDate' + strStartDate);
      print('strEndDate' + strEndDate);
      alertForm(context, "แจ้งเตือน", "กระรุณาระบุเงื่อนไขการค้นหา");
    }
  }

  findData() async {
    bool chk = await checkForm([
      startDate.text,
      endDate.text,
    ]);

    if (chk == false) {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      Map<String, dynamic> data = {
        "startdateElectricUsage": startDate.text, //วันเริ่มต้น
        "enddateElectricUsage": endDate.text //วันสิ้นสุด
      };
      print("Replace");
      print(strStartDate.replaceAll("-", " "));
      // if(){
      print("Ok");
      //}
      await Electric.searchData(data).then((res) {
        getData(); // เปิดเมื่อ api พร้อม มันจะรีเฟส ข้อมูลใหม่่
      });
    }
  }

  _buildDropDownStatistic(context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 110),
          width: mediaQuery(context, 'w', 1005),
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(53.0),
            border: Border.all(
                color: AppColors.color_border,
                style: BorderStyle.solid,
                width: 0.80),
          ),
          child: DropdownButtonHideUnderline(
            child: new DropdownButton<String>(
              iconSize: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownStatistic
                  .map(
                    (data) => DropdownMenuItem<String>(
                      child: Container(
                        child: Text(
                          data.key,
                          style: TextStyle(
                            fontSize: mediaQuery(context, "h", 50),
                          ),
                          textScaleFactor: 0.7,
                        ),
                      ),
                      value: data.value,
                    ),
                  )
                  .toList(),
              isExpanded: true,
              onChanged: (String value) {
                setState(() {
                  selectedStatisticName = value;
                  for (var i = 0; i < _dropdownStatistic.length; i++) {
                    if (_dropdownStatistic[i].value == selectedStatisticName) {
                      staticName = _dropdownStatistic[i].key.toString();
                      print(staticName);
                    }
                  }
                });
              },
              value: selectedStatisticName,
            ),
          ),
        ),
      ],
    );
  }

  _buildDropDownStatisticLandScape(context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 200),
          width: mediaQuery(context, 'w', 500),
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(53.0),
            border: Border.all(
                color: AppColors.color_border,
                style: BorderStyle.solid,
                width: 0.80),
          ),
          child: DropdownButtonHideUnderline(
            child: new DropdownButton<String>(
              iconSize: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownStatistic
                  .map(
                    (data) => DropdownMenuItem<String>(
                      child: Container(
                        child: Text(
                          data.key,
                          style: TextStyle(
                            fontSize: mediaQuery(context, "h", 90),
                          ),
                          textScaleFactor: 0.7,
                        ),
                      ),
                      value: data.value,
                    ),
                  )
                  .toList(),
              isExpanded: true,
              onChanged: (String value) {
                setState(() {
                  selectedStatisticName = value;

                  for (var i = 0; i < _dropdownStatistic.length; i++) {
                    if (_dropdownStatistic[i].value == selectedStatisticName) {
                      staticName = _dropdownStatistic[i].key.toString();
                      print(staticName);
                    }
                  }
                });
              },
              value: selectedStatisticName,
            ),
          ),
        ),
      ],
    );
  }

  _buildDropDownPeaListNo(context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 110),
          width: mediaQuery(context, 'w', 1005),
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(53.0),
            border: Border.all(
                color: AppColors.color_border,
                style: BorderStyle.solid,
                width: 0.80),
          ),
          child: DropdownButtonHideUnderline(
            child: new DropdownButton<String>(
              iconSize: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownPeaNolist
                  .map(
                    (data) => DropdownMenuItem<String>(
                      child: Row(children: <Widget>[
                        Flexible(
                          child: Text(
                            data.key,
                            style: TextStyle(
                              fontSize: mediaQuery(context, "h", 50),
                            ),
                            textScaleFactor: 0.7,
                          ),
                        ),
                      ]),
                      value: data.value,
                    ),
                  )
                  .toList(),
              isExpanded: true,
              onChanged: (String value) {
                setState(() {
                  selectedPeaNo = value;
                  print(selectedPeaNo);
                });
              },
              value: selectedPeaNo,
            ),
          ),
        ),
      ],
    );
  }

  _buildDropDownPeaListNoLandScape(context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 200),
          width: mediaQuery(context, 'w', 500),
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(53.0),
            border: Border.all(
                color: AppColors.color_border,
                style: BorderStyle.solid,
                width: 0.80),
          ),
          child: DropdownButtonHideUnderline(
            child: new DropdownButton<String>(
              iconSize: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownPeaNolist
                  .map(
                    (data) => DropdownMenuItem<String>(
                      child: Row(children: <Widget>[
                        Flexible(
                          child: Text(
                            data.key,
                            style: TextStyle(
                              fontSize: mediaQuery(context, "h", 90),
                            ),
                            textScaleFactor: 0.7,
                          ),
                        ),
                      ]),
                      value: data.value,
                    ),
                  )
                  .toList(),
              isExpanded: true,
              onChanged: (String value) {
                setState(() {
                  selectedPeaNo = value;
                  print(selectedPeaNo);
                });
              },
              value: selectedPeaNo,
            ),
          ),
        ),
      ],
    );
  }
} //class

class SalesData {
  SalesData(this.year, this.sales, this.segmentColor);

  final String year;
  final double sales;
  final Color segmentColor;
}

class ClicksPerYear {
  final String year;
  final int clicks;
  final charts.Color color;

  ClicksPerYear(this.year, this.clicks, Color color)
      : this.color = new charts.Color(
            r: color.red, g: color.green, b: color.blue, a: color.alpha);
}

class KeyValueModel {
  String key;
  String value;

  KeyValueModel({this.key, this.value});
}
