import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:hyzp_ybqx/components/commonFun.dart';

import '../../../components/customDialogH.dart';
import '../../../components/customDialogJ.dart';
import '../../../components/dioFun.dart';
//import 'package:hyzp_ybqx/widget/player_pro.dart';
import '../../../components/doJSON.dart';
import '../../../components/hyxx_data_handle.dart';

class DwxxContent extends StatefulWidget {
  //SbglContent({Key key, this.title, this.mapData}) : super(key: key);
  DwxxContent({
    @required this.title,
    @required this.index,
    @required this.hyshlx,
    Key key,
  }) : super(key: key);
  String title;
  int index = -1;
  String hyshlx;

  _SbglPageState createState() => _SbglPageState();
}

class _SbglPageState extends State<DwxxContent> {
  Map _mapGetSbglGetDataText = {
    "id": "主键ID",
    "dwip": "点位IP",
    "dwmc": '点位名称',
    "dwbh": '点位编号',
    "dwinfo": '点位信息',
    "dwzb": '点位坐标',
    "dwms": '点位描述',
    "dwzt": '点位状态',
  };

  //点位信息数据
  Map _mapGetSbglGetData = {
    "id": 1,
    "dwip": "172.16.3.1",
    "dwmc": "江北振兴大道",
    "dwbh": 1,
    "dwinfo": "江北振兴大道入城方向",
    "dwzb": "104.607091|28.807061",
    "dwms": "江北振兴大道入城方向，识别孜岩、红坝路入城排放黑烟车辆",
    "dwzt": "正常"
  };

  List<TextEditingController> _listController = [];
  int listLen = 0;
  String nums = '';
  int _selectedRadio = 0;

  void initState() {
    // TODO: implement initState
    super.initState();
    listLen = listSbglGetList2.length;
    getListFlields();
  }

  //监听登录页面销毁的事件
  dispose() {
    _controller.dispose();
    getingDwVideo = false;
    super.dispose();
  }

  getListFlields() async {
    //获取指定id的sbgl记录数据返回 _mapGetSbglGetData。由于 sbgl 信息需要进行查核处理，所以要重新读取最新的记录数据
    // _mapGetSbglGetData =
    //     await getLedXsxxGetData(id: listSbglGetList2[widget.index]['id'], theSbgllx: widget.hyshlx);
    _mapGetSbglGetData = listSbglGetList2[widget.index];
    print('_mapGetSbglGetData = ${_mapGetSbglGetData}');

    //_mapGetSbglGetData = listSbglGetList2[widget.index];
    _listController = List.generate(_mapGetSbglGetData.length, (index) {
      String key = _mapGetSbglGetData.keys.elementAt(index);

      String strContent = _mapGetSbglGetData[key].toString();
      //时间戳转换
      if (strContent.isNotEmpty && 'addtime' == key) {
        strContent = getDate(strContent);
      }
      //workflow转换
      if (strContent.isNotEmpty && 'workflow' == key) {
        strContent = strContent == '999' ? '已处理' : '待处理';
      }
      var controller = TextEditingController(text: strContent);

      controller.selection = TextSelection.fromPosition(
        TextPosition(affinity: TextAffinity.downstream, offset: '${controller.text}'.length),
      );
      return controller;
    });
    getPreBtn_NextBtn();
    nums = '${(widget.index + 1).toString()} / $listLen';
    setState(() {});
  }

  Widget getTrail(String key, int index, double widthTrail) {
    if (0 == _listController.length) {
      return Container(width: widthTrail);
    }

    //print('key = $key');
    if ('avatar' == key) {
      imagePath = _listController[index].text;
      return getAvatar(width: widthTrail);
    } else {
      return Container(
        alignment: Alignment(-1, 0),
        //widthTrail = 400报错，360刚能显示，300换行，260
        width: widthTrail,
        //解决信息显示不全问题
        child: Text(_listController[index].text,
            style: TextStyle(fontSize: 'dwms' == key ? 14 : 16), textAlign: TextAlign.left),
      );
    }
  }

  Widget getTrail0(String key, int index, double widthTrail) {
    if (0 == _listController.length) {
      return Container(width: widthTrail);
    }

    //print('key = $key');
    if ('avatar' == key) {
      imagePath = _listController[index].text;
      return getAvatar(width: widthTrail);
    } else {
      return Container(
        alignment: Alignment(1, 0),
        //widthTrail = 400报错，360刚能显示，300换行，260
        width: widthTrail,
        child: TextField(
          //textAlign: TextAlign.right,
          style: TextStyle(fontSize: 16),
          decoration: InputDecoration(
            //hintText: '請輸入字段信息',
            border: InputBorder.none, //TextField去掉下划线
            contentPadding: EdgeInsets.only(right: 0),
          ),
          controller: _listController[index],
          enabled: false,
          //利用控制器初始化文本
          onChanged: (value) {},
        ),
      );
    }
  }

  Future<String> doContacts() async {
    bFlash = false;
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return customDialogH(
          title: "请选择头像修改操作",
          content: "头像修改",
          index: 0,
        );
      },
    ).then((value) {
      imagePath = value;
      print('Page2_Contacts bFlash = $bFlash');
      if (imagePath.isNotEmpty) {
        _image = Image.file(File(imagePath), fit: BoxFit.cover);
        setState(() {});
      }
    });
  }

  //Image.file(this._image);
  String imagePath = '';
  Image _image;

  Widget getAvatar({double width = 260.0}) {
    if (imagePath.isEmpty) {
      _image = Image.asset('assets/images/user.png', fit: BoxFit.cover);
    } else {
      String head = imagePath.substring(0, 4).trim().toLowerCase();
      if ('http' == head) {
        _image = Image.network(imagePath, fit: BoxFit.cover);
      }
    }
    return Container(
      alignment: Alignment(-1, 0),
      width: width,
      child: InkWell(
        onTap: () async {
          doContacts();
        },
        child: Container(
          width: 40,
          child: _image,
        ),
      ),
    );
  }

  //添加、修改、删除联系人对话框
  doContacts2(String key, int index) async {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CustomDialogJ(
          theKey: key,
          index: index,
        );
      },
    );
  }

  static onNullFun() {}

  Widget _getListTile(String key, int index, double widthTrail,
      {onTapFun = onNullFun, onLongPressFun = onNullFun, size = 16.0}) {
    //print('key = $key, index = $index');
    return ListTile(
      //leading: new Icon(Icons.phone),
      title: Text((index + 1).toString() + ". " + '${_mapGetSbglGetDataText[key]} ：',
          style: TextStyle(fontSize: 16)),
      trailing: getTrail(key, index, widthTrail),
      contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0),
      enabled: true,
      onTap: () async {
        // print('第 $index 项被点击了');
        // await doContacts2(key, index);
        // if ('avatar' == key) {
        //   print('选择图片或拍照');
        //   await doContacts();
        // }
      },
      onLongPress: () {},
    );
  }

  TextEditingController _controller = TextEditingController.fromValue(TextEditingValue(
      text: '已做简单处理。低级故障，不影响系统运行',
      // 保持光标在最后
      selection: TextSelection.fromPosition(
          TextPosition(affinity: TextAffinity.downstream, offset: '已处理'.length))));

  double _heigth = 30;
  double _fontSize = 16;
  double _marginLeft = 15;

  @override
  Widget build(BuildContext context) {
    bool bCheck = _mapGetSbglGetData['workflow'] == 999; //已处理
    return Scaffold(
      // appBar: AppBar(
      //   title: Text("设备点位信息详情（$nums）"),
      //   centerTitle: true,
      // ),
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(ScreenUtil().setHeight(173)), // 设置appBar高度
        // 设置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.center,
              children: [
                getIconAndTextButton(
                  iconColor: Colors.white,
                  iconData: Icons.chevron_left_outlined,
                  onPress: () {
                    getingDwVideo = false;
                    Navigator.pop(context);
                  },
                ),
                Expanded(
                  child: Text("设备点位信息详情（$nums）",
                      style: TextStyle(color: Colors.white, fontSize: 20),
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis),
                ),
                SizedBox(width: 50),
              ],
            ),
          ),
        ),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              //https://www.it1352.com/2028416.html
              //用Map而不是List的Flutter ListView.builder(Flutter listview with Map instead of List)
              //使用ListView.separated设置分割线ListView.separated(
              //child: ListView.separated(  //这种方式不能设置每项高度，每页只能有7项
              child: ListView.builder(
                //这种方式可以通过itemExtent设置每项高度，每页可以有9项
                //separatorBuilder: (BuildContext context, int index) => index %2 ==0? Divider(color: Colors.green) : Divider(color: Colors.red),//index为偶数，创建绿色分割线；index为奇数，则创建红色分割线
                //separatorBuilder: (BuildContext context, int index) => Divider(),
                //itemExtent: 57.0, //列表项高度。56越界、57刚好。还是自动计算最好
                itemCount: _mapGetSbglGetData.length,
                itemBuilder: (BuildContext context, index) {
                  String key = _mapGetSbglGetData.keys.elementAt(index);
                  return Column(
                    children: <Widget>[
                      _getListTile(key, index, 200.0),
                      Divider(
                        height: 1.0,
                      ),
                    ],
                  );
                },
              ),
            ),
            //7、得到核查处理意见组件
            Divider(height: 1.0, color: Colors.blue),
            SizedBox(height: 15),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                // getBtnSizeX(
                //     text: "复制",
                //     onPressedFun: () {
                //       // Flutter 复制文本到剪贴板
                //       Clipboard.setData(
                //           ClipboardData(text: listSbglGetList2[widget.index].toString()));
                //       Fluttertoast.showToast(msg: '点位信息已复制到剪贴板', gravity: ToastGravity.CENTER);
                //     }),
                //getBtnSizeX(text: "删除", onPressedFun: () async {}),
                getBtnSizeX(
                    text: "视频",
                    onPressedFun: () {
                      //getDwspUrl(index: widget.index, context: context);
                      getDwspUrlNew(indexRecord: widget.index, context: context);

                      // getDwspUrl(index: widget.index + 1).then((url) {
                      //   print('index = ${(widget.index + 1).toString()}, url = $url');
                      //   urlnew = url;
                      //
                      //   //获取视频地址失败
                      //   if (!isVideoUrl(urlnew)) {
                      //     return;
                      //   }
                      //
                      //   var ret = Navigator.of(context).push(MaterialPageRoute(
                      //       builder: (context) => PlayerPro(
                      //             url: urlnew,
                      //             title:
                      //                 '点位视频\n${(widget.index + 1)}、${listDwinfoGetList2[widget.index]['dwmc']}',
                      //             //initVideoSize: Size(704.0, 576.0),
                      //           )));
                      //   print('ret = $ret');
                      // });

                      //getDwVideoUrl(index: widget.index);
                      //getData();
                      // Flutter 复制文本到剪贴板
                      // Clipboard.setData(
                      //     ClipboardData(text: listSbglGetList2[widget.index].toString()));
                      // Fluttertoast.showToast(msg: '点位信息已复制到剪贴板', gravity: ToastGravity.CENTER);
                    }),
                preBtn,
                nextBtn,
              ],
            ),
            SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  //解决第一次进入报错问题。因为getPreBtn_NextBtn()还未执行，preBtn和nextBtn为空
  Widget preBtn = Container(
    color: Colors.white12, //onPressedFun为null时无效
    width: 70.0,
    height: 35.0,
    child: RaisedButton(
      padding: EdgeInsets.all(0),
      textColor: Colors.black,
      child: Text('上一条'),
      onPressed: null,
    ),
  );

  Widget nextBtn = Container(
    color: Colors.white12, //onPressedFun为null时无效
    width: 70.0,
    height: 35.0,
    child: RaisedButton(
      padding: EdgeInsets.all(0),
      textColor: Colors.black,
      child: Text('下一条'),
      onPressed: null,
    ),
  );

  getPreBtn_NextBtn() {
    preBtn = getBtnSizeX(
      text: "上一条",
      onPressedFun: null,
    );
    nextBtn = getBtnSizeX(
      text: "下一条",
      onPressedFun: null,
    );

    if (widget.index > 0 && listLen > 0) {
      preBtn = getBtnSizeX(
        text: "上一条",
        onPressedFun: () async {
          if (widget.index > 0) {
            widget.index--;
            getListFlields();
          }
        },
      );
    }

    if (widget.index < (listLen - 1) && listLen > 0) {
      nextBtn = getBtnSizeX(
        text: "下一条",
        onPressedFun: () async {
          if (widget.index < listLen - 1) {
            widget.index++;
            getListFlields();
          }
        },
      );
    }
  }

  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,
      ),
    );
  }
}
