import 'dart:convert';

import 'package:fengshui_compass/models/et_date.dart';
import 'package:fengshui_compass/pages/pan_page.dart';
import 'package:flutter/material.dart';
import 'package:fengshui_compass/components/my_icon.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../models/qimen.dart';

class BirthCalPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _BirthCalState();
}

class _BirthCalState extends State<BirthCalPage> {
  bool isLunar = false;
  int year;
  int month;
  int day;
  int hour;
  int minute;

  int lunar_year;
  int lunar_month;
  int lunar_day;

  // 阴盘或者拆补无闰, 奇门类型
  int qmType = 0;

  Qimen qm;

  WebViewController _controllerWebView;

  final TextEditingController _controllerDate =
      TextEditingController(text: "点击右侧按钮选择日期");
  final TextEditingController _controllerTime =
      TextEditingController(text: "点击右侧按钮选择时间");

  _showDatePicker() async {
    var date = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
      locale: const Locale('zh'),
    );
    if (date == null) return;

    setState(() {
      if (isLunar) {
        lunar_year = date.year;
        lunar_month = date.month;
        lunar_day = date.day;

        _controllerDate.text = "${lunar_year}年${lunar_month}月${lunar_day}日";
      } else {
        year = date.year;
        month = date.month;
        day = date.day;

        _controllerDate.text = "${year}年${month}月${day}日";
      }
      // _controllerDate.text = year.toString()+"年"+month.toString()+"月"+day.toString()+"日";
    });
  }

  _showTimePicker() async {
    DateTime dd = DateTime.now();
    var hhh = dd.hour;
    var mmm = dd.minute;

    var time = await showTimePicker(
      context: context,
      initialTime: TimeOfDay(hour: hhh, minute: mmm),
      builder: (BuildContext context, Widget child) {
        return Localizations(
          locale: const Locale('zh'),
          child: child,
          delegates: const <LocalizationsDelegate>[
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
        );
      },
    );
    if (time == null) return;
    print(time);
    setState(() {
      hour = time.hour;
      minute = time.minute;
      // _controllerTime.text = hour.toString()+"时"+minute.toString()+"分";
      _controllerTime.text = "${hour}时${minute}分";
    });
  }

  // 通过公历算农历
  calLunar() {
    if (_controllerWebView != null) {
      _controllerWebView
          .runJavascriptReturningResult("flutterCallLunar($year,$month,$day)")
          .then((value) {
        String tmp = value
            .replaceAll(r'\"', '"')
            .replaceAll('"{', '{')
            .replaceAll('}"', '}');

        setState(() {
          lunar_year = json.decode(tmp)['lYear'];
          lunar_month = json.decode(tmp)['lMonth'];
          lunar_day = json.decode(tmp)['lDay'];
          year = json.decode(tmp)['cYear'];

          month = json.decode(tmp)['cMonth'];
          day = json.decode(tmp)['cDay'];

          _controllerDate.text = "${lunar_year}年${lunar_month}月${lunar_day}日";
        });
      });
    }
  }

  // 通过农历算公历
  calSolar() {
    if (_controllerWebView != null) {
      _controllerWebView
          .runJavascriptReturningResult(
              "flutterCallSolar($lunar_year,$lunar_month,$lunar_day)")
          .then((value) {
        String tmp = value
            .replaceAll(r'\"', '"')
            .replaceAll('"{', '{')
            .replaceAll('}"', '}');

        setState(() {
          year = json.decode(tmp)['cYear'];
          month = json.decode(tmp)['cMonth'];
          day = json.decode(tmp)['cDay'];
          lunar_year = json.decode(tmp)['lYear'];
          lunar_month = json.decode(tmp)['lMonth'];
          lunar_day = json.decode(tmp)['lDay'];

          _controllerDate.text = "${year}年${month}月${day}日";
        });
      });
    }
  }

  calPan() {
    if (_controllerWebView != null) {
      if(qmType == 0) {
        _controllerWebView
            .runJavascriptReturningResult(
            "flutterCallPaiPan($year, $month, $day, $hour, $minute)")
            .then((value) {
          String tmp = value
              .replaceAll(r'\"', '"')
              .replaceAll('"{', '{')
              .replaceAll('}"', '}');
          qm = Qimen.fromJson(json.decode(tmp));

          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => PanPage(
                      solarDate: EtDate(
                          cYear: year,
                          cMonth: month,
                          cDay: day,
                          lYear: lunar_year,
                          lMonth: lunar_month,
                          lDay: lunar_day,
                          hour: hour,
                          minute: minute)
                          .getSolar(),
                      lunarDate: EtDate(
                          cYear: year,
                          cMonth: month,
                          cDay: day,
                          lYear: lunar_year,
                          lMonth: lunar_month,
                          lDay: lunar_day,
                          hour: hour,
                          minute: minute)
                          .getLunar(),
                      jieqi: qm.jieqi,
                      dunju: qm.dunju,
                      bazi: qm.bazi,
                      zhishi: qm.zhishi,
                      zhifu: qm.zhifu,
                      kong: qm.kong,
                      qimenResult: qm.qimenResult
                  )));
        });
      } else if (qmType == 1) {
        _controllerWebView
            .runJavascriptReturningResult(
            "flutterCallYinPan($year, $month, $day, $hour, $minute)")
            .then((value) {
          String tmp = value
              .replaceAll(r'\"', '"')
              .replaceAll('"{', '{')
              .replaceAll('}"', '}');
          qm = Qimen.fromJson(json.decode(tmp));

          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => PanPage(
                      solarDate: EtDate(
                          cYear: year,
                          cMonth: month,
                          cDay: day,
                          lYear: lunar_year,
                          lMonth: lunar_month,
                          lDay: lunar_day,
                          hour: hour,
                          minute: minute)
                          .getSolar(),
                      lunarDate: EtDate(
                          cYear: year,
                          cMonth: month,
                          cDay: day,
                          lYear: lunar_year,
                          lMonth: lunar_month,
                          lDay: lunar_day,
                          hour: hour,
                          minute: minute)
                          .getLunar(),
                      jieqi: qm.jieqi,
                      dunju: qm.dunju,
                      bazi: qm.bazi,
                      zhishi: qm.zhishi,
                      zhifu: qm.zhifu,
                      kong: qm.kong,
                      qimenResult: qm.qimenResult
                  )));
        });
      } else {
        _controllerWebView
            .runJavascriptReturningResult(
            "flutterCallPaiPan($year, $month, $day, $hour, $minute)")
            .then((value) {
          String tmp = value
              .replaceAll(r'\"', '"')
              .replaceAll('"{', '{')
              .replaceAll('}"', '}');
          qm = Qimen.fromJson(json.decode(tmp));

          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => PanPage(
                      solarDate: EtDate(
                          cYear: year,
                          cMonth: month,
                          cDay: day,
                          lYear: lunar_year,
                          lMonth: lunar_month,
                          lDay: lunar_day,
                          hour: hour,
                          minute: minute)
                          .getSolar(),
                      lunarDate: EtDate(
                          cYear: year,
                          cMonth: month,
                          cDay: day,
                          lYear: lunar_year,
                          lMonth: lunar_month,
                          lDay: lunar_day,
                          hour: hour,
                          minute: minute)
                          .getLunar(),
                      jieqi: qm.jieqi,
                      dunju: qm.dunju,
                      bazi: qm.bazi,
                      zhishi: qm.zhishi,
                      zhifu: qm.zhifu,
                      kong: qm.kong,
                      qimenResult: qm.qimenResult
                  )));
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // webview
    String url = "file:///android_asset/flutter_assets/assets/index.html";

    ///JS显示弹窗使用
    // WebView.platform = SurfaceAndroidWebView();

    return Container(
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("assets/images/bg1.png"), fit: BoxFit.cover)),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          centerTitle: true,
          title: const Text(
            '在线起局',
            style: TextStyle(color: Color(0xCFA77300)),
          ),
        ),
        body: SafeArea(
            child: Container(
          alignment: AlignmentDirectional.topCenter,
          child: Column(
            children: [
              const Padding(padding: EdgeInsets.only(top: 150)),
              Container(
                width: 400,
                height: 400,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30)),
                alignment: Alignment.center,
                child: Column(
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Expanded(
                            child: SizedBox(
                          height: 60,
                          // 阳历按钮
                          child: TextButton(
                            onPressed: () {
                              setState(() {
                                isLunar = !isLunar;
                              });
                              // 如果有农历数据，将农历数据转换成公历，并显示到输入框
                              // calLunar();
                              if (_controllerWebView != null) {
                                _controllerWebView
                                    .runJavascriptReturningResult(
                                        "flutterCallSolar($lunar_year,$lunar_month,$lunar_day)")
                                    .then((value) {
                                  String tmp = value
                                      .replaceAll(r'\"', '"')
                                      .replaceAll('"{', '{')
                                      .replaceAll('}"', '}');

                                  setState(() {
                                    year = json.decode(tmp)['cYear'];
                                    month = json.decode(tmp)['cMonth'];
                                    day = json.decode(tmp)['cDay'];
                                    lunar_year = json.decode(tmp)['lYear'];
                                    lunar_month = json.decode(tmp)['lMonth'];
                                    lunar_day = json.decode(tmp)['lDay'];

                                    _controllerDate.text =
                                        "${year}年${month}月${day}日";
                                  });
                                });
                              }
                            },
                            child: Text(
                              "阳历",
                              style: TextStyle(
                                  fontSize: 20,
                                  color: isLunar ? Colors.black : Colors.white),
                            ),
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    isLunar
                                        ? Colors.transparent
                                        : Color(0xCFA77300)),
                                shape: MaterialStateProperty.all(
                                    RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(30)))),
                          ),
                        )),
                        Expanded(
                            child: SizedBox(
                          height: 60,
                          // 阴历按钮
                          child: TextButton(
                            onPressed: () {
                              setState(() {
                                isLunar = !isLunar;
                              });
                              // 如果有公历数据，将公历数据转换为农历
                              // calLunar();
                              if (_controllerWebView != null) {
                                _controllerWebView
                                    .runJavascriptReturningResult(
                                        "flutterCallLunar($year,$month,$day)")
                                    .then((value) {
                                  String tmp = value
                                      .replaceAll(r'\"', '"')
                                      .replaceAll('"{', '{')
                                      .replaceAll('}"', '}');

                                  setState(() {
                                    lunar_year = json.decode(tmp)['lYear'];
                                    lunar_month = json.decode(tmp)['lMonth'];
                                    lunar_day = json.decode(tmp)['lDay'];
                                    year = json.decode(tmp)['cYear'];

                                    month = json.decode(tmp)['cMonth'];
                                    day = json.decode(tmp)['cDay'];

                                    _controllerDate.text =
                                        "${lunar_year}年${lunar_month}月${lunar_day}日";
                                  });
                                });
                              }
                            },
                            child: Text(
                              "阴历",
                              style: TextStyle(
                                  fontSize: 20,
                                  color: isLunar ? Colors.white : Colors.black),
                            ),
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    isLunar
                                        ? Color(0xCFA77300)
                                        : Colors.transparent),
                                shape: MaterialStateProperty.all(
                                    RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(30)))),
                          ),
                        ))
                      ],
                    ),
                    const Padding(padding: EdgeInsets.only(top: 40)),
                    Row(
                      children: [
                        const Padding(
                          padding: EdgeInsets.only(
                            left: 10,
                            right: 10,
                          ),
                          child: Text("出生日期:", style: TextStyle(fontSize: 18)),
                        ),
                        Expanded(
                            child: TextField(
                          controller: _controllerDate,
                          decoration: InputDecoration(
                              contentPadding: EdgeInsets.all(10.0),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(10.0),
                              )),
                          readOnly: true,
                        )),
                        IconButton(
                            onPressed: _showDatePicker,
                            icon: Icon(MyIcons.icon_rili))
                      ],
                    ),
                    const Padding(padding: EdgeInsets.only(top: 40)),
                    Row(
                      children: [
                        const Padding(
                          padding: EdgeInsets.only(
                            left: 10,
                            right: 10,
                          ),
                          child: Text(
                            "出生时间:",
                            style: TextStyle(fontSize: 18),
                          ),
                        ),
                        Expanded(
                            child: TextField(
                          controller: _controllerTime,
                          decoration: InputDecoration(
                              contentPadding: const EdgeInsets.all(10.0),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(10.0),
                              )),
                          readOnly: true,
                        )),
                        IconButton(
                            onPressed: _showTimePicker,
                            icon: Icon(Icons.timelapse_outlined))
                      ],
                    ),
                    Padding(padding: EdgeInsets.only(top: 40)),
                    // 切换奇门类型，单选框
                    Row(children: [
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Radio(value: 0, groupValue: qmType, onChanged: (v){
                            setState(() {
                              qmType = v;
                            });
                          }),
                          const Text("拆补法")
                        ],
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Radio(value: 1, groupValue: qmType, onChanged: (v){
                            setState(() {
                              qmType = v;
                            });
                          }),
                          const Text("阴盘")
                        ],
                      )
                    ],),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Expanded(
                            child: Padding(
                          padding: const EdgeInsets.only(left: 20, right: 20),
                          child: TextButton(
                            onPressed: () {
                              if ((year != null) &&
                                  (month != null) &&
                                  (day != null) &&
                                  (hour != null) &&
                                  (minute != null) &&
                                  (lunar_year == null)) {
                                // 有公历没农历，先转化农历，再起局
                                calLunar();
                                calPan();
                              } else if ((lunar_year != null) &&
                                  (lunar_month != null) &&
                                  (lunar_day != null) &&
                                  (hour != null) &&
                                  (minute != null) &&
                                  (year == null)) {
                                // 有农历没公历，先转化公历，再起局
                                calSolar();
                                calPan();
                              } else if ((year != null) &&
                                  (lunar_year != null) &&
                                  (hour != null)) {
                                // 直接起局
                                calPan();
                              } else {
                                Fluttertoast.showToast(
                                    msg: "请输入出生日期和时间",
                                    backgroundColor: Colors.red,
                                    textColor: Colors.white,
                                    fontSize: 20.0);
                              }
                            },
                            child: const Text(
                              "奇门遁甲起局",
                              style:
                                  TextStyle(color: Colors.white, fontSize: 22),
                            ),
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    Color(0xCFA77300))),
                          ),
                        ))
                      ],
                    )
                  ],
                ),
              ),
              Offstage(
                  offstage: true,
                  child: Container(
                    width: 1,
                    height: 1,
                    child: WebView(
                      initialUrl: url,
                      javascriptMode: JavascriptMode.unrestricted,
                      javascriptChannels: {
                        JavascriptChannel(
                            name: "toast",
                            onMessageReceived: (message) {
                              // Fluttertoast.showToast(msg: message.message.toString());
                              print(message.message.toString());
                            }),
                      },
                      onWebViewCreated: (controller) {
                        _controllerWebView = controller;
                      },
                    ),
                  ))
            ],
          ),
        )),
      ),
    );
  }
}
