import 'dart:io';

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

import '../../../components/customDialogH.dart';
import '../../../components/hyxx_data_handle.dart';
import '../../../res/listContacts.dart';
import '../../../services/EventBus.dart';
import '../../../services/Storage.dart';
import '../../../widget/JdButton.dart';

class PersonalData extends StatefulWidget {
  PersonalData({Key key}) : super(key: key);

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<PersonalData> {
  List<TextEditingController> listController = [];
  String imagePath = '';
  Image _image;

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

  //监听登录页面销毁的事件
  dispose() {
    super.dispose();
    eventBus.fire(new UserEvent('登录成功...'));
  }

  getListFlields() async {
    Storage.getString('userAvatarPath').then((value) {
      if (null != value) {
        imagePath = value;
      }
    });
    print('imagePath = $imagePath');

    //mapUserInfo = mapUserInfoRet['data']['profile'];
    await getMyUserinfo();
    // print('mapUserInfoRet = $mapUserInfoRet');
    // print('mapUserInfo = $mapUserInfo');

    listController = List.generate(mapUserInfo.length, (index) {
      String key = mapUserInfo.keys.elementAt(index);
      if ("reg_time" == key) {
        var strtime = DateTime.fromMillisecondsSinceEpoch(mapUserInfo[key]); //将拿到的时间戳转化为日期
        print('时间戳：${mapUserInfo[key]}');
        print('转换为日期时间：${strtime.toLocal().toString()}');
        // I/flutter (25364): 时间戳：1606653977
        // I/flutter (25364): 转换为日期时间：1970-01-19 14:17:33.977
        return TextEditingController(text: strtime.toLocal().toString());
      } else {
        var controller = TextEditingController(text: mapUserInfo[key].toString());
        controller.selection = TextSelection.fromPosition(
          TextPosition(affinity: TextAffinity.downstream, offset: '${controller.text}'.length),
        );
        return controller;
      }
    });
    setState(() {});
  }

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

    //print('key = $key');
    if ('avatar' == key) {
      if (imagePath.isEmpty) {
        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: mapUserInfoModifyable[key],
          //利用控制器初始化文本
          onChanged: (value) {
            mapUserInfo[key] = value;
          },
        ),
      );
    }
  }

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

  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);
      } else {
        _image = Image.file(File(imagePath), fit: BoxFit.cover);
      }
    }
    return Container(
      alignment: Alignment(-1, 0),
      width: width,
      child: InkWell(
        onTap: () async {
          //doContacts();
        },
        child: Container(
          width: 40,
          child: _image,
        ),
      ),
    );
  }

  static onNullFun() {}

  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.containsKey(key) ? '${mapUserInfoText[key]} ：' : '$key ：',
          style: TextStyle(fontSize: 16)),
      trailing: getTrail(key, index, widthTrail),
      contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0),
      enabled: true,
      onTap: () async {
        // if ('avatar' == key) {
        //   print('选择图片或拍照');
        //   await doContacts();
        // }
      },
      onLongPress: () {},
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      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.start,
              children: [
                getIconAndTextButton(
                  iconColor: Colors.white,
                  iconData: Icons.chevron_left_outlined,
                  onPress: () {
                    Navigator.pop(context);
                  },
                ),
                Expanded(
                  child: Text("个人资料",
                      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)
              child: ListView.builder(
                itemCount: mapUserInfo.length,
                itemBuilder: (BuildContext context, index) {
                  String key = mapUserInfo.keys.elementAt(index);
                  return Column(
                    children: <Widget>[
                      _getListTile(key, index, 220.0),
                      Divider(
                        height: 1.0,
                      ),
                    ],
                  );
                },
              ),
            ),
            SizedBox(height: 40),
            JdButton(
              height: 126,
              width: 899,
              text: "确认",
              color: Colors.blueAccent,
              onTop: () async {
                Navigator.pop(context);
              },
            ),
            SizedBox(height: 40),
          ],
        ),
      ),
    );
  }
}
