import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hyzp_ybqx/services/EventBus.dart';
import 'package:hyzp_ybqx/widget/JdButton.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';

import '../../../components/commonFun.dart';
import '../../../components/dioFun.dart';
import '../../../components/hyxx_data_handle.dart';
import '../../../widget/DropdownItem.dart';

class LedXsxxContent extends StatefulWidget {
  LedXsxxContent({
    @required this.sbgllx, //sbgllx: 'led_xsxx', //设备管理类型：LED显示信息
    @required this.title,
    @required this.id,
    Key key,
  }) : super(key: key);
  String title;
  int id;
  String sbgllx;

  _LedXsxxPageState createState() => _LedXsxxPageState();
}

//用TabController实现顶部tab切换
class _LedXsxxPageState extends State<LedXsxxContent> {
  //try_setState();   //避免异常报错
  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  dispose() {
    super.dispose();
  }

  String _title = '';

  //flutter_screenUtil 4.x 用法，ScreenUtil.screenWidth   (sdk>=2.6 : 1.sw)   //设备宽度
  double _screenWidth = 1.sw;

  double _marginLeft = 15;
  double _marginCenter = 5;
  double _marginCenterHeight = 20;
  double _widgetHeight = 35;
  double _fontSize = 16;
  double _widthLeft = 40; // = _screenWidth / 3;
  double _iconSize = 18;
  double _stampSize = 100;
  double _listTileHeight = 30;
  Color _iconColor = Colors.blue;
  double _titleWidth = 130;

  //处理全部记录
  bool _modifyAll = false;

  void initState() {
    super.initState();

    // listLedXsxxGetList2.clear();
    // ///从接口 mapHyshlx[hyshlx]['api'] 获取第 iPage 页的列表数据，返回 list
    // getPageList().then((value) {
    //   listLedXsxxGetList2 = value;
    //   //按照用户选择的_selectedValue、_descending对listLedXsxxGetList2进行排序，并延时更新
    // });

    ///从接口 mapHyshlx[theHyshlx]['api'] 获取指定类型第 page 页的列表数据，返回 list
    ///获取点位信息数据
    listDwinfoGetList2.clear();
    getThePageList(theHyshlx: 'dwxx').then((value) {
      listDwinfoGetList2 = value;
      print('listDwinfoGetList2 = \n$listDwinfoGetList2');
      getListFlields();
    });
    //listDwinfoGetList2 = [{
    //    "id": 1,
    //    "dwip": "172.16.3.1",
    //    "dwmc": "江北振兴大道",
    //    "dwbh": 1,
    //    "dwinfo": "江北振兴大道入城方向",
    //    "dwzb": "104.607091|28.807061",
    //    "dwms": "江北振兴大道入城方向，识别孜岩、红坝路入城排放黑烟车辆"
    //},
    //{
    //    "id": 2,
    //    "dwip": "172.16.3.2",
    //    "dwmc": "宜飞路",
    //    "dwbh": 2,
    //    "dwinfo": "宜宾南收费站宜飞路入城方向",
    //    "dwzb": "104.589904|28.787078",
    //    "dwms": "宜宾南收费站宜飞路入城方向，识别屏山、菜坝入城排放黑烟车辆"
    //},];

    _widthLeft = _screenWidth / 2.6;

    //监听 选择LED点位 更新事件
    eventBus.on<SelectLedDwUpdateEvent>().listen((event) async {
      //获取用户选择项对应的记录id
      widget.id = _listItems.indexOf(event.selectedValue);
      print('原生 widget.id = ${widget.id}');
      if (widget.id < 1) {
        _modifyAll = true; //处理全部记录
        widget.id = 1;
      } else {
        _modifyAll = false; //处理全部记录
      }
      print('widget.id = ${widget.id}');

      //刷新页面数据
      await getListFlields();

      //刷新 显示违章记录 Dropdown
      // print('_mapGetLedXsxxGetData = ${_mapGetLedXsxxGetData}');
      // print('_mapGetLedXsxxGetData["xsts"] = ${_mapGetLedXsxxGetData["xsts"]}');
      // print(
      //     'getWzjlString(_mapGetLedXsxxGetData["xsts"]) = ${getWzjlString(_mapGetLedXsxxGetData["xsts"])}');
      eventBus.fire(SelectWzjlUpdateEvent(
          'external_SelectWzjlUpdateEvent', getWzjlString(_mapGetLedXsxxGetData["xsts"])));

      try_setState(); //避免异常报错
      print(event.str);
    });

    //监听 选择显示违章记录 更新事件
    eventBus.on<SelectWzjlUpdateEvent>().listen((event) async {
      print('SelectWzjlUpdateEvent: ${event.str}');
      print('SelectWzjlUpdateEvent: ${event.selectedValue}');
      _selectedValue = event.selectedValue;
      _xsts = getWzjlCount(event.selectedValue);
      //只响应内部发送的'insider_SelectWzjlUpdateEvent'
      //不响应外部发送的'external_SelectWzjlUpdateEvent'
      if (event.str == 'external_SelectWzjlUpdateEvent') {
        //刷新页面数据
        try_setState(); //避免异常报错
      }
    });
  }

  //App.Car_Led.Get接口获取的记录数据结构（比App.Car_Led.GetList接口获取的丰富）
  Map _mapGetLedXsxxGetData = {
    "id": 2,
    "dwip": "172.16.3.2",
    "xsnr": "绿水青山就是金山银山     宜宾市生态环境局宣。",
    "xsts": 0, //显示抓拍到的多少条违章记录
    "stime": "07:00",
    "etime": "23:00",
    "addtime": "2021-01-20 10:16:07",
    "updatetime": "2021-02-13 11:48:51"
  };

  //Web管理平台LED点位名称。除第一项外，估计后面都按ID号排列
  // 全部
  // 1   '江北振兴大道',
  // 2   '宜飞路',
  // 3   '宜宾南收费站',
  // 4   '一曼路',
  // 5   '柏溪收费站',
  // 6   '七星路万达广场',
  // 7   '宜宾财政局',
  // 8   '宜威路南广镇',
  // 9   '宜长路',
  // 10  '宜南快速通道',
  // 11  '观斗山隧道',
  // 12  '大麦坝',
  // 13  '外江路',

  //LED点位名称List，除第一项外，后面都按ID号排列
  List _listItems = [
    // '全部',
    // '1、江北振兴大道',
    // '2、宜飞路',
    // '3、宜宾南收费站',
    // '4、一曼路',
    // '5、柏溪收费站',
    // '6、七星路万达广场',
    // '7、宜宾财政局',
    // '8、宜威路南广镇',
    // '9、宜长路',
    // '10、宜南快速通道',
    // '11、观斗山隧道',
    // '12、大麦坝',
    // '13、外江路',
  ];

  String _selectedValue = '不显示';
  int _xsts = 0;
  String _startTime = '';
  String _endTime = '';
  String _ledMessage = '';

  //App.Car_Led.Get接口获取的记录数据结构（比App.Car_Led.GetList接口获取的丰富）
  // Map _mapGetLedXsxxGetData = {
  //   "id": 2,
  //   "dwip": "172.16.3.2",
  //   "xsnr": "绿水青山就是金山银山     宜宾市生态环境局宣。",
  //   "xsts": 0, //显示抓拍到的多少条违章记录
  //   "stime": "07:00",
  //   "etime": "23:00",
  //   "addtime": "2021-01-20 10:16:07",
  //   "updatetime": "2021-02-13 11:48:51"
  // };

  Future getListFlields() async {
    //实时更新_listItems内容
    _listItems = ['全部']; //LED点位名称List，除第一项外，后面都按ID号排列
    int len = listDwinfoGetList2.length;
    for (int i = 0; i < len; i++) {
      _listItems.add('${i + 1}、${listDwinfoGetList2[i]['dwmc']}');
      // _listItems.add('${listDwinfoGetList2[i]['id']}、${listDwinfoGetList2[i]['dwmc']}');
    }
    print('_listItems = $_listItems');
    //兴文： I/flutter ( 7562): _listItems = [全部, 21、大礼村, 22、石海收费站, 23、高铁站, 24、温水溪, 25、古高路]

    //获取指定id的LED记录数据返回 _mapGetLedXsxxGetData
    // _mapGetLedXsxxGetData = await getLedXsxxGetData(id: widget.id, theSbgllx: widget.sbgllx);
    _mapGetLedXsxxGetData = await getLedXsxxGetData(
        id: listDwinfoGetList2[widget.id - 1]['id'], theSbgllx: widget.sbgllx);
    //printWrapped('_mapGetLedXsxxGetData = ${_mapGetLedXsxxGetData}');
    //_mapGetLedXsxxGetData = {
    //         "id": 1,
    //         "dwip": "172.16.3.1",
    //         "xsnr": "绿水青山就是金山银山     宜宾市生态环境局宣。",
    //         "xsts": 0,
    //         "stime": "07:00",
    //         "etime": "23:00",
    //         "addtime": "2021-01-06 00:59:43",
    //         "updatetime": "2021-02-03 19:57:55"
    //     };

    if (_mapGetLedXsxxGetData.length > 0) {
      _xsts = _mapGetLedXsxxGetData['xsts'];
      _ledMessage = _mapGetLedXsxxGetData['xsnr'];
      _startTime = _mapGetLedXsxxGetData['stime'];
      _endTime = _mapGetLedXsxxGetData['etime'];
    }

    try {
      // _title =listDwinfoGetList2
      //     '${widget.title}（${(getIndex(widget.id) + 1).toString()} / ${listLedXsxxGetList2.length}）id:${widget.id.toString()}';
      //_title = '${widget.title}（${widget.id.toString()} / ${listDwinfoGetList2.length}）id:${widget.id.toString()}';
      //_title = '${widget.title}（${widget.id.toString()} / ${listDwinfoGetList2.length}）${listDwinfoGetList2[widget.id - 1]['dwmc']}';
      _title = '${widget.title}（${widget.id.toString()} / ${listDwinfoGetList2.length}）';
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }

    // List listLedXsxxGetData = [];
    // for(int i = 0; i < 13; i++) {
    //   listLedXsxxGetData.add(await getLedXsxxGetData(i + 1));
    // }
    // print('listLedXsxxGetData = \nlistLedXsxxGetData');
  }

  //获取 listLedXsxxGetList2 中ID号为 _id 的索引号
  // int getIndex(int _id) {
  //   int len = listLedXsxxGetList2.length;
  //   int _index;
  //   for (_index = 0; _index < len; _index++) {
  //     if (listLedXsxxGetList2[_index]['id'] == _id) {
  //       break;
  //     }
  //   }
  //   return _index;
  // }

  Widget getTitleText(String text, {double fontSize = 16}) {
    return Text(text,
        style: TextStyle(fontSize: fontSize),
        textAlign: TextAlign.left,
        overflow: TextOverflow.ellipsis);
  }

  Widget getSizeText(String text, {double fontSize = 16, double width = 100, double top = 0}) {
    return Container(
      margin: EdgeInsets.only(top: top),
      width: width,
      child: Text(text,
          style: TextStyle(fontSize: fontSize),
          textAlign: TextAlign.left,
          overflow: TextOverflow.ellipsis),
    );
  }

  Widget getIcon(IconData _iconData) {
    return Container(
      width: _iconSize - 2,
      height: _iconSize,
      child: Padding(
        padding: EdgeInsets.only(top: 2),
        child: Icon(_iconData, size: _iconSize, color: _iconColor),
      ),
    );
  }

  //5、得到LED显示信息确认组件
  Widget getLedQr() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        JdButton(
          height: 126,
          //JdText中已经使用ScreenUtil().setHeight(126)，此处不能传 ScreenUtil().setHeight(126) ，否则严重错位
          width: 350,
          text: "更新",
          color: Color.fromRGBO(45, 202, 115, 1),
          onTop: () {
            printWrapped('_message = ${_ledMessage}');
            print('_xsts = ${_xsts}');
            print('_startTime = ${_startTime}');
            print('_endTime = ${_endTime}');

            //updateLedData({@required int id, @required String theSbgllx, @required Map map})
            //_modifyAll = true; //id = -1，处理全部记录
            // updateLedData(id: _modifyAll ? -1 : widget.id, theSbgllx: 'led_update', map: {
            updateLedData(
                id: _modifyAll ? -1 : listDwinfoGetList2[widget.id - 1]['id'],
                theSbgllx: 'led_update',
                map: {
                  'xsnr': _ledMessage,
                  'xsts': _xsts,
                  'stime': _startTime,
                  'etime': _endTime,
                });
            Navigator.pop(context);
          },
        ),
        JdButton(
          height: 126,
          //JdText中已经使用ScreenUtil().setHeight(126)，此处不能传 ScreenUtil().setHeight(126) ，否则严重错位
          width: 350,
          text: "取消",
          color: Color.fromRGBO(43, 163, 255, 1),
          onTop: () {
            Navigator.pop(context);
          },
        ),
      ],
    );
  }

  //得到LED信息页面组件
  //1、得到 选择LED点位 组件
  Widget getSelectLedDw() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        SizedBox(width: _marginLeft),
        getSizeText('选择点位：', width: _titleWidth),
        //SizedBox(width: _marginCenter),
        //Expanded(child: SizedBox.shrink()),
        DropdownItem(
          listItems: _listItems,
          //初始值 initValue 必须是 listItems 中的已有元素
          initValue: _listItems[widget.id],
          dropdownEvent: 'SelectLedDwUpdateEvent',
          width: ScreenUtil().setWidth(590),
          height: _widgetHeight,
        ), //SizedBox(width: _marginLeft),
        SizedBox(width: _marginLeft),
      ],
    );
  }

  //2、得到选择 显示违章记录 组件
  Widget getSelectWzjl() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        SizedBox(width: _marginLeft),
        getSizeText('显示违章记录：', width: _titleWidth),
        // Expanded(child: SizedBox.shrink()),

        DropdownItem(
          listItems: _listItemsWzjl,
          initValue: getWzjlString(_xsts),
          width: ScreenUtil().setWidth(590),
          height: _widgetHeight,
          dropdownEvent: 'SelectWzjlUpdateEvent',
        ),
        SizedBox(width: _marginLeft),
      ],
    );
  }

  List _listItemsWzjl = [
    '不显示',
    '显示3条',
    '显示5条',
    '显示10条',
  ];

  //通过违章信息的条数得到显示的字符串
  String getWzjlString(int wzjlCount) {
    String _wzjlString = '';
    switch (wzjlCount) {
      case 0:
        _wzjlString = _listItemsWzjl[0];
        break;
      case 3:
        _wzjlString = _listItemsWzjl[1];
        break;
      case 5:
        _wzjlString = _listItemsWzjl[2];
        break;
      case 10:
        _wzjlString = _listItemsWzjl[3];
        break;
      default:
        break;
    }
    return _wzjlString;
  }

  //通过字符串得到显示违章信息的条数
  int getWzjlCount(String wzjlString) {
    int _wzjlCount = -1;
    switch (wzjlString) {
      case '不显示':
        _wzjlCount = 0;
        break;
      case '显示3条':
        _wzjlCount = 3;
        break;
      case '显示5条':
        _wzjlCount = 5;
        break;
      case '显示10条':
        _wzjlCount = 10;
        break;
      default:
        break;
    }
    return _wzjlCount;
  }

  //3、得到 启用时段 组件
  Widget getOpenTime() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        SizedBox(width: _marginLeft),
        getSizeText('启用时段：', width: _titleWidth),
        //SizedBox(width: _marginCenter),
        getInBox(0, _widgetHeight), //whichTime：0为_startTime，1为_endTime
        Text('  -  '),
        getInBox(1, _widgetHeight), //whichTime：0为_startTime，1为_endTime
      ],
    );
  }

  //4、得到 显示信息 组件
  Widget getLedMessage(double _width, double _height) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(width: _marginLeft),
            getSizeText('显示信息：', width: _titleWidth, top: 2),
          ],
        ),
        SizedBox(height: ScreenUtil().setHeight(10)),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(width: _marginLeft),
            getInBoxMsg(_width, _height), //whichTime：0为_startTime，1为_endTime
          ],
        ),
      ],
    );
  }

  //显示信息 输入框
  Widget getInBoxMsg(double _width, double _height) {
    return ConstrainedBox(
      constraints: BoxConstraints(
        minHeight: ScreenUtil().setHeight(_height),
        maxHeight: ScreenUtil().setHeight(_height),
        minWidth: ScreenUtil().setWidth(_width),
        maxWidth: ScreenUtil().setWidth(_width),
      ),
      child: TextField(
        keyboardType: TextInputType.multiline,
        maxLines: 10,
        //不限制行数
        textAlign: TextAlign.justify,
        style: TextStyle(fontSize: my_fontSize),
        decoration: InputDecoration(
          hintText: '请输入LED显示信息',
          contentPadding: EdgeInsets.only(top: 4, left: 8, bottom: 4, right: 8),
          focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey, width: 2.0),
              borderRadius: BorderRadius.circular(3.0)),
          enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey, width: 2.0),
              borderRadius: BorderRadius.circular(3.0)),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(3),
            borderSide: BorderSide(
              color: Colors.grey,
              width: 2.0,
            ),
          ),
          // border: OutlineInputBorder(
          //     borderRadius: BorderRadius.circular(3.0),
          //     borderSide: BorderSide(color: Colors.grey, width: 0)),
        ),
        controller: TextEditingController.fromValue(TextEditingValue(
          text: null == _ledMessage ? '' : _ledMessage,
          // 保持光标在最后
          // selection: TextSelection.fromPosition(
          //     TextPosition(affinity: TextAffinity.downstream, offset: _message.length))
        )),
        enabled: true,
        onChanged: (value) {
          _ledMessage = value;
          printWrapped(_ledMessage);
        },
      ),
    );
  }

  //whichTime：0为_startTime，1为_endTime
  Widget getInBox(int _whichTime, double _height) {
    return Container(
      alignment: Alignment(0, 0),
      height: _height,
      width: 90,
      // decoration: BoxDecoration(
      //   border: Border.all(color: Colors.grey, width: 2),
      //   borderRadius: BorderRadius.all(Radius.circular(3.0)),
      // ),
      child: TextField(
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: my_fontSize),
        decoration: InputDecoration(
          hintText: _whichTime == 0 ? '启用时间' : '关闭时间',
          contentPadding: EdgeInsets.all(0),
          focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey, width: 2.0),
              borderRadius: BorderRadius.circular(3.0)),
          enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey, width: 2.0),
              borderRadius: BorderRadius.circular(3.0)),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(3),
            borderSide: BorderSide(
              color: Colors.grey,
              width: 2.0,
            ),
          ),
          // border: OutlineInputBorder(
          //     borderRadius: BorderRadius.circular(3.0),
          //     borderSide: BorderSide(color: Colors.grey, width: 0)),
        ),
        controller: TextEditingController.fromValue(TextEditingValue(
          text: (_whichTime == 0
              ? (null == _startTime ? '' : _startTime)
              : (null == _endTime ? '' : _endTime)),
          // 保持光标在最后
          selection: TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: (_whichTime == 0
                      ? (null == _startTime ? '' : _startTime)
                      : (null == _endTime ? '' : _endTime))
                  .length)),
        )),
        enabled: true,
        onChanged: (value) {
          if (_whichTime == 0) {
            _startTime = value;
          } else {
            _endTime = value;
          }
        },
      ),
    );
  }

  String _sizedropDown = 'brown';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomPadding: false,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(ScreenUtil().setHeight(173)), // 设置appBar高度
        child: AppBar(
          automaticallyImplyLeading: false,
          centerTitle: true,
          titleSpacing: 0.0,
          //设置title的左边距
          flexibleSpace: Container(
            //SizedBox(height: ScreenUtil().statusBarHeight), //显示顶部状态栏
            // SizedBox(height: ScreenUtil().setHeight(10)), //显示顶部状态栏
            padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight), //留出顶部状态栏高度
            child: Container(
              //height: ScreenUtil().setHeight(173),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color.fromRGBO(12, 186, 156, 1),
                    Color.fromRGBO(39, 127, 235, 1),
                  ],
                ),
              ),
              // decoration: BoxDecoration(
              //   gradient: LinearGradient(colors: [
              //     Color(0xFF0018EB),
              //     Color(0xFF01C1D9),
              //   ], begin: Alignment.bottomCenter, end: Alignment.topCenter),
              // ),
            ),
          ),
          title: Padding(
            padding: EdgeInsets.only(left: 0, right: 0),
            child: Row(
              //mainAxisAlignment: MainAxisAlignment.start,
              children: [
                getIconAndTextButton(
                  iconColor: Colors.white,
                  iconData: Icons.chevron_left_outlined,
                  onPress: () {
                    Navigator.pop(context);
                  },
                ),
                Expanded(
                  child: Text(_title,
                      style: TextStyle(color: Colors.white, fontSize: 20),
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis),
                ),
                SizedBox(width: 30),
              ],
            ),
          ),
        ),
      ),
      body: _listItems.isEmpty || _mapGetLedXsxxGetData == null
          ? getMoreWidget(color: Colors.grey)
          : KeyboardAvoider(
              autoScroll: true,
              child: Container(
                child: Column(
                  children: <Widget>[
                    //1、得到选择LED点位组件
                    SizedBox(height: _marginCenterHeight),
                    getSelectLedDw(),
                    Divider(height: _marginCenterHeight),
                    //2、得到选择 显示违章记录 组件
                    getSelectWzjl(),
                    Divider(height: _marginCenterHeight),
                    //3、得到 启用时段 组件
                    getOpenTime(),
                    Divider(height: _marginCenterHeight),
                    //4、得到 显示信息 组件
                    getLedMessage(980, 570),
                    Divider(height: _marginCenterHeight),
                    SizedBox(height: _marginCenterHeight),
                    //5、得到Led确认组件
                    getLedQr(),
                    SizedBox(height: _marginCenterHeight),
                  ],
                ),
              ),
            ),
    );
  }

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