import 'package:flutter/material.dart';

import '../../../services/EventBus.dart';
import '../01_messages/messages_manage.dart';
import '../../../components/doJSON.dart';
import '../../../components/hyxx_data_handle.dart';
import 'dart:convert';
import '../../../res/listContacts.dart';

class ContactModify extends StatefulWidget {
  ContactModify({@required this.contactIndex, Key key}) : super(key: key);
  int contactIndex;

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<ContactModify> {
  List<TextEditingController> listController;
  bool changed = false;

  void initState() {
    // TODO: implement initState
    super.initState();
    getListFlields();
  }

  String getUserText3(int index, String key) {
    String str = (listContacts2[index][key] is String) ? listContacts2[index][key] : '';
    return str;
  }

  getListFlields() {
    listController = List.generate(listContacts2[widget.contactIndex].length, (index) {
      String key = listContacts2[widget.contactIndex].keys.elementAt(index);
      //return TextEditingController(text: listContacts2[widget.contactIndex][key]);
      return TextEditingController(text: getUserText3(widget.contactIndex, key));
    });
  }

  //监听登录页面销毁的事件
  dispose() {
    super.dispose();
    if (changed) {
      writeJSON(json.encode(listContacts2), 'listContacts02.json');
    }
    eventBus.fire(new UserEvent('登录成功...'));
  }

  doLogin() async {
    Navigator.pop(context); //返回
    return;
  }

  OnTap_messages_manage() {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) => MessagesManagePage()));
  }

  //自定义方法
  static onNullFun() {}

  Widget getTrail(String key, int index, double widthTrail) {
    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: mapUserInfoModifyable[key],
        //利用控制器初始化文本
        onChanged: (value) {
          listContacts2[widget.contactIndex][key] = value;
          bFlash = changed = true;
          print("ContactAdd bFlash = $bFlash");
        },
      ),
    );
  }

  Widget _getListTile(String key, int index, double widthTrail,
      {onTapFun = onNullFun, onLongPressFun = onNullFun, size = 16.0}) {
    return ListTile(
      //leading: new Icon(Icons.phone),
      title: Text('${mapUserInfoText[key]} ：', style: TextStyle(fontSize: 16)),
      trailing: getTrail(key, index, widthTrail),
      contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0),
      enabled: true,
      onTap: () {},
      onLongPress: () {},
    );
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("修改联系人"),
        centerTitle: true,
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              //Flutter Column套ListView不显示，可将ListView用Expanded包裹起来。
              // child: ListView.builder(
              //   itemCount: listFlields.length,
              //   itemBuilder: _getListTileFields,
              // ),

              //listContacts2[widget.contactIndex]
              child: ListView.builder(
                itemCount: listContacts2[widget.contactIndex].length,
                itemBuilder: (BuildContext context, index) {
                  String key = listContacts2[widget.contactIndex].keys.elementAt(index);
                  return Column(
                    children: <Widget>[
                      _getListTile(key, index, 220.0),
                      Divider(
                        height: 1.0,
                      ),
                    ],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  //https://www.it1352.com/2028416.html
  //用Map而不是List的ListView.builder
  //Its a little late but You could also try this. Map values = snapshot.data;
  getMap() {
    Map values = listContacts2[widget.contactIndex];
    return new ListView.builder(
      itemCount: values.length,
      itemBuilder: (BuildContext context, int index) {
        String key = values.keys.elementAt(index);
        return new Column(
          children: <Widget>[
            new ListTile(
              title: new Text("$key"),
              subtitle: new Text("${values[key]}"),
            ),
            new Divider(
              height: 2.0,
            ),
          ],
        );
      },
    );
  }
}
