import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hyzp_ybqx/components/EncryptUtil.dart';
import 'package:hyzp_ybqx/components/customDialogF.dart';
import 'package:hyzp_ybqx/components/customDialogHysh.dart';
import 'package:hyzp_ybqx/components/dioFun.dart';

import '../../../components/doJSON.dart';
import '../../../components/hyxx_data_handle.dart';
import '../../../services/EventBus.dart';
import '../../../widget/CheckboxButtonItem.dart';

class HyshGroup extends StatefulWidget {
  HyshGroup(
      {@required this.index,
      @required this.hyshlx,
      this.size = const Size(30, 30),
      this.fontSize = 16,
      this.selectedRadio = 0,
      this.id = -1});

  //I don't know what is this index for but I will put it in anyway
  final int index;
  Size size;
  double fontSize;
  String hyshlx;
  int selectedRadio;
  int id;

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

class _HyshGroupState extends State<HyshGroup> {
  //try_setState();   //避免如下异常报错
  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  int _selectedRadio = 0;
  String _sfcyTextTrue = '当前时间 > 抓拍时间 + 审核间隔，只能审核，不推送交警';
  String _sfcyTextFalse = '当前时间 < 抓拍时间 + 审核间隔，复审后可以推送交警';

  void initState() {
    _selectedRadio = widget.selectedRadio;

    //黑烟审核推送交警Checkbox改变事件
    eventBus.on<HycsDataAuditSfyc>().listen((event) {
      print(event.str);
      try_setState(); //避免如下异常报错
    });

    super.initState();
  }

  Widget getRadio(int index, Size size) {
    return Container(
      alignment: Alignment(-1, 1),
      width: size.width,
      height: size.height,
      child: Radio(
        value: index,
        onChanged: (value) {
          _selectedRadio = value;
          //黑烟初审数据审核Radio选项改变广播
          eventBus.fire(HycsDataAuditRadioEvent('黑烟初审数据审核Radio选项已改变', _selectedRadio));
          setState(() {});
          print('selectedRadio = ${_selectedRadio.toString()}');
        },
        groupValue: _selectedRadio,
      ),
    );
  }

  //Couldn't infer type parameter 'T'. Tried to infer 'dynamic' for 'T' which doesn't work:
  // Parameter 'onChanged' declared as 'void Function(T)' but argument is 'Null Function(String)'.
  // The type 'dynamic' was inferred from: Parameter 'value' declared as 'T' but argument is 'String'.
  // Parameter 'groupValue' declared as 'T' but argument is 'dynamic'.
  // Consider passing explicit type argument(s) to the generic.

  //原因是selectedRadio的类型为int，示例中_radValue为String
  //无法推断类型参数“t”。试图推断“T”的“dynamic”无效：参数“onChanged”声明为“void Function（T）”，
  // 但参数为“Null Function（String）”。类型“dynamic”的推断依据：参数“value”声明为“T”，
  // 但参数为“String”。参数“groupValue”声明为“T”，但参数为“dynamic”。考虑将显式类型参数传递给泛型。

  //5、得到黑烟审核组件
  getHyshItems(int index) {
    return Container(
      width: ScreenUtil().setWidth(1022),
      height: ScreenUtil().setHeight(550),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(
          Radius.circular(12),
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(height: ScreenUtil().setHeight(20)),
          //5.1、车牌号码、车牌颜色
          topTabs_map['carNumberAndCpys_List'][index],
          SizedBox(height: ScreenUtil().setHeight(15)),
          //5.2、审核意见
          getShyj(widget.index),
          //SizedBox(height: ScreenUtil().setHeight(25)),
          //5.3、得到审核结果组件
          getShjg(widget.index),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        //5、得到黑烟审核组件
        getHyshItems(widget.index),
        SizedBox(height: ScreenUtil().setHeight(6)),
        //6、得到审核确认组件
        getShqr(widget.index),
      ],
    );
  }

  //6、得到审核确认组件
  Widget getShqr(int index) {
    return Container(
      //padding: EdgeInsets.only(top: ScreenUtil().setWidth(6)),
      width: ScreenUtil().setWidth(1022),
      height: ScreenUtil()
          .setHeight(widget.hyshlx == 'hyfh' ? (1 == sfyc ? 215 : 150) : (1 == sfyc ? 215 : 150)),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(
          Radius.circular(12),
        ),
      ),
      child: Column(
        children: [
          SizedBox(height: ScreenUtil().setHeight(20)),
          1 == sfyc
              ? Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
                  child: Text(
                    _sfcyTextTrue,
                    textAlign: TextAlign.left,
                    style: TextStyle(color: Colors.blue, fontSize: 13),
                  ))
              : SizedBox.shrink(),
          SizedBox(height: ScreenUtil().setHeight(1 == sfyc ? 6 : 0)),
          widget.hyshlx == 'hyfh'
              ? Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    CheckboxButtonItem(widget.index),
                    //_getShjgImage(widget.tabController, _selectedRadio, 35),
                    Container(
                      width: ScreenUtil().setWidth(100),
                      height: ScreenUtil().setHeight(100),
                      decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage(_selectedRadio == 0
                                ? "assets/images/hyc.png"
                                : "assets/images/fhyc.png"),
                            fit: BoxFit.contain),
                      ),
                    ),
                    getBtnSizeX(
                        text: '复审提交',
                        fontColor: 0 == _selectedRadio ? Colors.red : Colors.green,
                        // onPressedFun: 1 == sfyc
                        //     ? null
                        //     : () async {
                        onPressedFun: () async {
                          int ret = -1;
                          print('等待复审提交确认');
                          await Navigator.of(context)
                              .push(
                            PageRouteBuilder(
                              opaque: false,
                              pageBuilder: (context, animation, secondaryAnimation) => CustomDialogHysh(
                                  shjg: 0 == _selectedRadio ? hyc_text : fhyc_text,
                                  title: '复审',
                                  content:
                                      '是否进行复审提交${tsjj && 0 == sfyc ? '、同时推送交警' : ''}？\n${1 == sfyc ? _sfcyTextTrue : ''}'),
                            ),
                          )
                              .then((value) async {
                            print('value = $value');
                            if (value) {
                              print('用户已确认，开始处理复审提交！');

//复审接口增加是否延迟字段 sfyc	（是否延迟）整型	必须	是否延误，0-正常 1-延误。延误状态的不推送
// 初审不用判断，sfyc 直接提交0即可。只有复审的时候才判断时间
// 	A、若在规定时间内，则 int sfyc = 0，审核完毕后正常推送交警。
// 	B、若超出规定时间，即当前时间>抓拍时间+间隔时间，则 sfyc = 1，不推送交警。

                              //设置 sfyc 和 tsjj
                              set_sfyc_tsjj(int.parse(listGetZpjl[widget.index]['zpsj']))
                                  .then((value) async {
                                hyshContentFirstAudit(
                                  widget.id,
                                  widget.index,
                                  mapHyshlx[hyshlx]['audit_workflow'],
                                  topTabs_map['auditShuoming_Controller_List'][widget.index].text,
                                  topTabs_map['auditTitle'][widget.index],
                                  sfyc: sfyc,
                                ).then((value) {
                                  eventBus.fire(
                                      HycsDataUpdateEvent('${mapHyshlx[hyshlx]['text']}数据已更新'));
                                  //必须等待审核过程完成后，再处理同时推送交警，否则推送交警总是失败
                                  print('tsjj = $tsjj');
                                  if (tsjj) {
                                    print('before tsjjFun(widget.id, _plateAndID)');

                                    String _plateAndID = topTabs_map['car_number_List'].toString() +
                                        '(ID:${widget.id.toString()})';

                                    tsjjFun(widget.id, _plateAndID);

                                    print('after tsjjFun(widget.id, _plateAndID)');

                                    Fluttertoast.showToast(
                                        msg: '$_plateAndID 已推送交警，请等待返回结果。',
                                        gravity: ToastGravity.CENTER);
                                  }
                                });
                              });
                            } else {
                              print('用户取消了复审提交');
                            }
                          });
                          Navigator.pop(context, ret);
                        },
                        width: 90.0,
                        height: 34.0), //'复审提交'
                    getBtnSizeX(
                        text: "取消",
                        onPressedFun: () async {
                          Navigator.pop(context);
                        },
                        width: 60.0,
                        height: 34.0), //'取消'
                  ],
                )
              : Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    //_getShjgImage(widget.tabController, _selectedRadio, 35),
                    Container(
                      width: 35,
                      height: 35,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage(_selectedRadio == 0
                                ? "assets/images/hyc.png"
                                : "assets/images/fhyc.png"),
                            fit: BoxFit.contain),
                      ),
                    ),
                    getBtnSizeX(
                        text: '初审提交',
                        fontColor: 0 == _selectedRadio ? Colors.red : Colors.green,
                        // onPressedFun: 1 == sfyc
                        //     ? null
                        //     : () async {
                        onPressedFun: () async {
                          int ret = -1;
                          print('等待初审提交确认');
                          await Navigator.of(context)
                              .push(
                            PageRouteBuilder(
                              opaque: false,
                              pageBuilder: (context, animation, secondaryAnimation) =>
                                  CustomDialogHysh(
                                      shjg: 0 == _selectedRadio ? hyc_text : fhyc_text,
                                      title: '初审',
                                      content: '是否进行初审提交？'),
                            ),
                          )
                              .then((value) async {
                            print('value = $value');
                            if (value) {
                              print('用户已确认，开始处理初审提交！');
                              //return;

                              hyshContentFirstAudit(
                                widget.id,
                                widget.index,
                                mapHyshlx[hyshlx]['audit_workflow'],
                                topTabs_map['auditShuoming_Controller_List'][widget.index].text,
                                topTabs_map['auditTitle'][widget.index],
                                sfyc: 0,
                              ).then((value) {
                                eventBus
                                    .fire(HycsDataUpdateEvent('${mapHyshlx[hyshlx]['text']}数据已更新'));
                              });
                            } else {
                              print('用户取消了初审提交');
                            }
                          });
                          Navigator.pop(context, ret);
                        },
                        width: 90.0), //'初审提交'
                    getBtnSizeX(
                        text: "取消",
                        onPressedFun: () async {
                          Navigator.pop(context);
                        },
                        width: 60.0), //'取消'
                  ],
                ),
        ],
      ),
    );
  }

  //5.3、得到审核结果组件
  Widget getShjg(int index) {
    return Container(
      width: ScreenUtil().setWidth(1022),
      height: ScreenUtil().setHeight(175),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              SizedBox(width: my_marginLeft),
              Text((widget.hyshlx == 'hyfh' ? '复审' : '初审') + '结果: ',
                  style: TextStyle(
                      fontSize: widget.fontSize,
                      color: 0 == _selectedRadio ? Colors.red : Colors.green)),
              CustomRadioWidget(
                value: 0,
                title: mapHyshlx[hyshlx]['nick_text'] + "为黑烟车",
                fontSize: widget.fontSize,
                width: ScreenUtil().setWidth(400),
                groupValue: _selectedRadio,
                onChanged: (int value) {
                  _selectedRadio = value;
                  fh_hyc = true; //复审为黑烟车
                  tsjj = true; //同时推送交警
                  //黑烟初审数据审核Radio选项改变广播
                  eventBus.fire(HycsDataAuditRadioEvent('黑烟初审数据审核Radio选项已改变', _selectedRadio));
                  setState(() {});
                  print('selectedRadio = ${_selectedRadio.toString()}');
                },
              ),
            ],
          ),
          SizedBox(height: ScreenUtil().setHeight(15)),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              SizedBox(width: my_marginLeft),
              Text((widget.hyshlx == 'hyfh' ? '复审' : '初审') + '结果: ',
                  style: TextStyle(fontSize: widget.fontSize, color: Colors.white)),
              CustomRadioWidget(
                value: 1,
                title: "非黑烟车",
                fontSize: widget.fontSize,
                width: ScreenUtil().setWidth(400),
                groupValue: _selectedRadio,
                onChanged: (int value) {
                  _selectedRadio = value;
                  fh_hyc = false; //复审为黑烟车
                  tsjj = false; //同时推送交警
                  //黑烟初审数据审核Radio选项改变广播
                  eventBus.fire(HycsDataAuditRadioEvent('黑烟初审数据审核Radio选项已改变', _selectedRadio));
                  setState(() {});
                  print('selectedRadio = ${_selectedRadio.toString()}');
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  //5.2、得到审核意见组件
  Widget getShyj(int index) {
    // return ConstrainedBox(
    //   constraints: BoxConstraints(
    //     minWidth: double.infinity, //宽度尽可能大
    //     //minHeight: _listTileHeight, //最小高度
    //     maxHeight: my_listTileHeight, //最大高度
    //   ),
    return Container(
      width: ScreenUtil().setWidth(1022),
      height: ScreenUtil().setHeight(120),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.baseline,
        children: <Widget>[
          SizedBox(width: my_marginLeft),
          Text((widget.hyshlx == 'hyfh' ? '复审' : '初审') + '意见: ',
              style: TextStyle(
                  fontSize: my_fontSize, color: 0 == _selectedRadio ? Colors.red : Colors.green)),
          Container(
            alignment: Alignment(-1, 0),
            height: 120,
            //widthTrail = 400报错，360刚能显示，300换行，266
            width: ScreenUtil().setWidth(775),
            child: TextField(
              //textAlign: TextAlign.right,
              //style: TextStyle(fontSize: _fontSize, color: cpysList[getIndexOfCpysList(colorText: topTabs_map['cpysText_List'][i])].cpysFont),
              //style: TextStyle(fontSize: _fontSize, color: cpysList[getIndexOfCpysList(colorText: myCpys)].cpysFont),
              style: TextStyle(fontSize: my_fontSize),
              textAlign: TextAlign.left,
              decoration: InputDecoration(
                hintText: '請輸入审核意见',
                //border: InputBorder.none, //TextField去掉下划线
                //contentPadding: EdgeInsets.only(right: 0),
                //contentPadding: EdgeInsets.symmetric(vertical: my_textFieldHeight),
                contentPadding: EdgeInsets.only(left: 4, right: 4), //这行代码是关键，设置这个之后，居中
                //contentPadding: EdgeInsets.zero, //这行代码是关键，设置这个之后，居中
                border: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey[600]),
                  //borderSide: BorderSide.none,
                  borderRadius: BorderRadius.circular(3),
                ),
              ),
              controller: topTabs_map['auditShuoming_Controller_List'][index],
              maxLines: 1,
              minLines: 1,
              //maxLengthEnforced: false,
              //maxLength: 10,
              enabled: true,
              //利用控制器初始化文本
              onChanged: (value) {
                topTabs_map['auditShuoming_Controller_List'][index].text = value;
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget getBtnSizeX(
      {@required text, width = 70.0, height = 35.0, onPressedFun, fontColor = Colors.black}) {
    return Container(
      color: Colors.white12, //onPressedFun为null时无效
      width: width,
      height: height,
      child: RaisedButton(
        padding: EdgeInsets.all(0),
        textColor: Colors.black,
        child: Text(text, style: TextStyle(color: fontColor)),
        onPressed: onPressedFun,
      ),
    );
  }
}

class CustomRadioWidget<T> extends StatelessWidget {
  final T value;
  final String title;
  final double fontSize;
  final T groupValue;
  final ValueChanged<T> onChanged;
  final double width;
  final double height;

  CustomRadioWidget(
      {this.value,
      this.title = '',
      this.fontSize = 16,
      this.groupValue,
      this.onChanged,
      this.width = 25,
      this.height = 25});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(0),
      child: GestureDetector(
        onTap: () {
          onChanged(this.value);
        },
        child: Container(
          //alignment: Alignment(0, 0),
          height: this.height,
          width: this.width,
          child: value == groupValue
              ? Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(top: 2),
                      child: Icon(Icons.radio_button_checked_rounded,
                          color: onChanged == null ? Colors.grey : Colors.blue),
                    ),
                    SizedBox(width: title.isEmpty ? 0 : 2),
                    Text(
                      title,
                      style: TextStyle(
                        fontSize: fontSize,
                        color: onChanged == null ? Colors.grey : Colors.blue,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                )
              : Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(top: 2),
                      child: Icon(Icons.radio_button_unchecked_rounded,
                          color: onChanged == null ? Colors.grey : Colors.black),
                    ),
                    SizedBox(width: title.isEmpty ? 0 : 2),
                    Text(title,
                        style: TextStyle(
                            fontSize: fontSize,
                            color: onChanged == null ? Colors.grey : Colors.black)),
                  ],
                ),
        ),
      ),
    );
  }
}
