import 'package:flutter/material.dart';
import '../services/EventBus.dart';

class DropdownItem extends StatefulWidget {
  DropdownItem(
      {@required this.listItems,
      @required this.initValue,
      @required this.dropdownEvent,
      this.width = 180,
      this.height = 35,
      this.fontSize = 16});

  List listItems;
  String initValue;
  double width;
  double height;
  double fontSize;
  String dropdownEvent;

  //处理Dropdown选项改变广播
  //如果传递函数，将导致App崩溃
  //eventBus.fire(widget.dropdownEvent('Dropdown选项已改变', _selectedValue));
  //通过传字符串，用 switch 处理不会导致App崩溃
  //widget.dropdownEvent 取值：
  //case 'SelectLedDwUpdateEvent':   //监听 选择LED点位 更新事件
  //case 'SelectWzjlUpdateEvent':    //监听 选择显示违章记录 更新事件

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

class _DropdownItemState extends State<DropdownItem> {
  List<DropdownMenuItem<String>> _dropDownMenuItems;
  String _selectedValue;

  //try_setState();   //避免异常报错
  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  @override
  void initState() {
    _selectedValue = widget.initValue;
    _dropDownMenuItems = getDropDownMenuItems();

    if (widget.dropdownEvent == 'SelectWzjlUpdateEvent') {
      //eventBus.fire(SelectWzjlUpdateEvent('external_SelectWzjlUpdateEvent', getWzjlString(_mapGetLedXsxxGetData["xsts"])));
      ///监听 选择显示违章记录 更新事件
      eventBus.on<SelectWzjlUpdateEvent>().listen((event) async {
        print(event.str);
        //只响应外部发送的'external_SelectWzjlUpdateEvent'
        //不响应内部发送的'insider_SelectWzjlUpdateEvent'
        if (event.str == 'external_SelectWzjlUpdateEvent') {
          //刷新页面数据
          //print('external_SelectWzjlUpdateEvent：' '_selectedValue = $_selectedValue');
          _selectedValue = event.selectedValue;
          _dropDownMenuItems = getDropDownMenuItems();
          try_setState(); //避免异常报错
        }
      });
    }

    super.initState();
  }

  List<DropdownMenuItem<String>> getDropDownMenuItems() {
    List<DropdownMenuItem<String>> items = [];
    int len = widget.listItems.length;
    for (int i = 0; i < len; i++) {
      items.add(
        DropdownMenuItem(
          value: widget.listItems[i],
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              (_selectedValue == widget.listItems[i])
                  ? Container(
                      color: Colors.black12,
                      child: Text(widget.listItems[i], style: TextStyle(fontSize: widget.fontSize)),
                    )
                  : Text(widget.listItems[i], style: TextStyle(fontSize: widget.fontSize)),
              SizedBox(width: 2),
              (_selectedValue == widget.listItems[i])
                  ? Icon(Icons.check, size: 18)
                  : SizedBox(width: 0),
            ],
          ),
        ),
      );
    }
    return items;
  }

  Widget getDropdownButton() {
    //_selectedValue = initValue;
    return DropdownButtonHideUnderline(
      child: DropdownButton(
        isExpanded: true, //让下拉图标始终位于末尾
        value: _selectedValue,
        items: _dropDownMenuItems,
        onChanged: (String _selValue) {
          _selectedValue = _selValue;
          print('_selectedValue = $_selectedValue');
          _dropDownMenuItems = getDropDownMenuItems();
          setState(() {});

          ///处理Dropdown选项改变广播
          //如果传递函数，将导致App崩溃
          //eventBus.fire(widget.dropdownEvent('Dropdown选项已改变', _selectedValue));
          //通过传字符串，用 switch 处理不会导致App崩溃
          //widget.dropdownEvent 取值：
          //case 'SelectLedDwUpdateEvent':   //监听 选择LED点位 更新事件
          //case 'SelectWzjlUpdateEvent':    //监听 选择显示违章记录 更新事件
          switch (widget.dropdownEvent) {
            case 'SelectDwfliterUpdateEvent': //监听 选择点位 更新事件
              eventBus.fire(SelectDwfliterUpdateEvent('Dropdown选项已改变', _selectedValue));
              break;
            case 'SelectLedDwUpdateEvent': //监听 选择LED点位 更新事件
              eventBus.fire(SelectLedDwUpdateEvent('Dropdown选项已改变', _selectedValue));
              break;
            case 'SelectWzjlUpdateEvent': //监听 选择显示违章记录 更新事件
              eventBus.fire(SelectWzjlUpdateEvent('insider_SelectWzjlUpdateEvent', _selectedValue));
              break;
            default:
              break;
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment(-1, 0),
      margin: EdgeInsets.only(bottom: 0),
      padding: EdgeInsets.only(left: 5),
      height: widget.height,
      width: widget.width,
      decoration: BoxDecoration(
        //color: Colors.white,
        border: Border.all(color: Colors.grey, width: 2),
        borderRadius: BorderRadius.all(Radius.circular(3.0)),
      ),
      child: getDropdownButton(),
      //child: Text('getDropdownButton'),
    );
  }
}
