import 'dart:io';
import 'dart:math';

import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:dartin/dartin.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/application.dart';
import 'package:sport/pages/login/login_widget.dart';
import 'package:sport/pages/social/user_friend_add_page.dart';
import 'package:sport/provider/login_info_model.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/router/routes.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/city_picker.dart';
import 'package:sport/widgets/city_picker_data.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:sport/widgets/dialog/request_dialog.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/list_tile.dart';

class UserInfoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<UserInfoPage> with InjectLoginApi {
  LoginInfoModel _loginInfoModel = inject();
  int _genderController = 1; // 默认选中男
  String _name; // 用户名
  File _lastCropped;

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

  @override
  void dispose() {
    super.dispose();
  }

  void fetchUploadProductBanner(File path) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    var resp = await loginApi.setAvatar(path);
    String uploadUrl = resp.data;
    prefs.setString('avatar', uploadUrl);
    Provider.of<UserModel>(context, listen: false)
        .saveUserInfoAvator(uploadUrl);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[buildSliverAppBar(context, "个人信息")];
          },
          body: ListView(
            padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 12.0),
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            children: divideTiles(
              context: context,
              includeLast: true,
              tiles: [
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("头像"),
                      Consumer<UserModel>(
                        builder: (_, model, __) {
                          return Container(
                            width: 40.0,
                            height: 40.0,
                            child: CircleAvatar(
                              radius: 100,
                              backgroundImage: _lastCropped == null
                                  ? NetworkImage(model.user.avatar)
                                  : FileImage(
                                      _lastCropped,
                                    ),
                            ),
                          );
                        },
                      )
                    ],
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
                  trailing: arrowRight5(),
                  onTap: () async {
                    dynamic data = await Navigator.push(context,
                        MaterialPageRoute(builder: (context) {
                      return BuildCroppingImagePage();
                    }));
                    setState(() {
                      _lastCropped = data;
                    });
                  },
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("用户名称"),
                      Consumer<UserModel>(
                        builder: (_, model, __) {
                          return Text(model.user.name,
                              style: Theme.of(context).textTheme.bodyText2);
                        },
                      )
                    ],
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
                  trailing: arrowRight5(),
                  onTap: () {
                    _showDialog((TextEditingValue name) async {
                      await request(context, () async {
                        await _loginInfoModel.updateUserInfo(
                            context,
                            name.text,
                            Provider.of<UserModel>(context, listen: false)
                                .user
                                .gender);
                      });
                    });
                  },
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("性别"),
                      Consumer<UserModel>(
                        builder: (_, model, __) {
                          return Text(model.user.gender == 1 ? "男" : "女",
                              style: Theme.of(context).textTheme.bodyText2);
                        },
                      )
                    ],
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
                  trailing: arrowRight5(),
                  onTap: () {
                    var user =
                        Provider.of<UserModel>(context, listen: false).user;
                    _showGenderDialog(user.gender, (int _gender) async {
                      await request(context, () async {
                        await _loginInfoModel.updateUserInfo(
                            context,
                            Provider.of<UserModel>(context, listen: false)
                                .user
                                .name,
                            _gender);
                      });
                    });
                  },
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("年龄"),
                      Consumer<UserModel>(
                        builder: (_, model, __) {
                          return Text(
                              model.user.age != null
                                  ? "${model.user.age}岁"
                                  : "请选择你的年龄",
                              style: Theme.of(context).textTheme.bodyText2);
                        },
                      )
                    ],
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
                  trailing: arrowRight5(),
                  onTap: () {
                    var user =
                        Provider.of<UserModel>(context, listen: false).user;
                    _showAgeDialog(user.age, (int age) async {
                      await request(context, () async {
                        await _loginInfoModel.updateUserInfo(
                            context,
                            Provider.of<UserModel>(context, listen: false)
                                .user
                                .name,
                            Provider.of<UserModel>(context, listen: false)
                                .user
                                .gender,
                            age: age);
                      });
                    });
                  },
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("城市"),
                      Consumer<UserModel>(
                        builder: (_, model, __) {
                          String province = model.user.province;
                          String city = model.user.city;
                          String district = model.user.district;
                          String _address = "";
//                          print(_address);
                          if (province != null &&
                              city != null &&
                              district != null) {
                            _address = "$province-$city";
                          }
                          print(_address);
                          return Text(_address != "" ? "$_address" : "请选择你的城市",
                              style: Theme.of(context).textTheme.bodyText2);
                        },
                      )
                    ],
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
                  trailing: arrowRight5(),
                  onTap: () async {
                    if (await showDialog(
                          context: context,
                          builder: (context) => CustomAlertDialog(
                              title: '是否重新定位？',
                              ok: () => Navigator.of(context).pop(true)),
                        ) ==
                        true) {
                      await request(context, () async {
                        Location location = await Application.location();
                        if (location != null) {
                          await _loginInfoModel.updateUserInfo(
                              context,
                              Provider.of<UserModel>(context, listen: false)
                                  .user
                                  .name,
                              Provider.of<UserModel>(context, listen: false)
                                  .user
                                  .gender,
                              districtId: int.parse(location.adCode));
                        }
                      });
                    }

                    //
                    // var user = Provider.of<UserModel>(context, listen: false).user;
                    // CityResult initCity = CityResult();
                    // initCity.province = user.province;
                    // initCity.city = user.city;
                    // initCity.county = user.district;
                    // CityResult result = await showCityPicker(context,initCity: initCity);
                    //
                    // if(result == null)
                    //   return;
                    //
                    // print(result.county);
                    // print(result.city);
                    // print(result.province);
                    //
                    // print(result.cityCode);
                    // print(result.countyCode);
                    // print(result.provinceCode);
                    //
                    // await _loginInfoModel.updateUserInfo(
                    //     context, Provider.of<UserModel>(context, listen: false).user.name, Provider.of<UserModel>(context, listen: false).user.gender,
                    //     cityId: int.parse(result.cityCode), districtId: int.parse(result.countyCode), provinceId: int.parse(result.provinceCode));
                  },
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("二维码名片"),
                      Container(
                        width: 22.0,
                        height: 22.0,
                        child: Image.asset("lib/assets/img/mine_icon_code.png"),
                      ),
                    ],
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
                  trailing: arrowRight5(),
                  onTap: () async {
                    NavigatorUtil.goPage(context, (context) => UserFriendAddPage());
                  },
                ),
              ],
            ).toList(),
          ),
        ));
    ;
  }

  _showDialog(Function callBack) {
    TextEditingController _controller = new TextEditingController();
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return AlertDialog(
            contentPadding: EdgeInsets.all(6.0),
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            content: Container(
              width: 300,
              height: 200,
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      IconButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          icon: Text("取消")),
                      Expanded(
                          child: Center(
                              child: Text(
                        "修改用户名",
                        style: Theme.of(context).textTheme.headline3,
                      ))),
                      IconButton(
                          onPressed: () {
//                            print(_controller.value);
                            callBack(_controller.value);
                            Navigator.of(context).pop();
                          },
                          icon: Text(
                            "确认",
                            style: Theme.of(context)
                                .textTheme
                                .subtitle1
                                .copyWith(color: Theme.of(context).accentColor),
                          )),
                    ],
                  ),
                  Divider(),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: TextField(
                        textAlign: TextAlign.center,
                        controller: _controller,
                        autofocus: true,
                        maxLength: 10,
                        decoration: InputDecoration(
                            counterText: '',
                            helperText: '用户名长度为2-10个字母，数字，中文',
                            helperMaxLines: 1,
                            focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                                  color: Theme.of(context).accentColor),
                            ))),
                  ),
                ],
              ),
            ),
          );
        });
  }

  _showGenderDialog(int gender, Function callback) {
    var array = ["男", "女"];
    int _index = gender == 2 ? 1 : 0;
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return AlertDialog(
            contentPadding: EdgeInsets.all(6.0),
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            content: Container(
              width: 300,
              height: 200,
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      IconButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          icon: Text("取消")),
                      Expanded(
                          child: Center(
                              child: Text(
                        "修改性别",
                        style: Theme.of(context).textTheme.headline3,
                      ))),
                      IconButton(
                          onPressed: () {
                            callback(_index);
                            Navigator.of(context).pop();
                          },
                          icon: Text(
                            "确认",
                            style: Theme.of(context)
                                .textTheme
                                .subtitle1
                                .copyWith(color: Theme.of(context).accentColor),
                          )),
                    ],
                  ),
                  Divider(),
                  Expanded(
                    child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: CupertinoPicker.builder(
                          scrollController:
                              FixedExtentScrollController(initialItem: _index),
                          itemExtent: 40,
                          backgroundColor: Colors.white,
                          onSelectedItemChanged: (index) {
//                            print(index);
                            _index = index + 1;
                          },
                          itemBuilder: (context, index) {
                            return Text("${array[index]}");
                          },
                          childCount: array.length,
                        )),
                  ),
                ],
              ),
            ),
          );
        });
  }

  _showAgeDialog(int age, Function callback) {
    List<int> _ages = List.generate(100, (index) => index);
    int _index = min(100, age);
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return AlertDialog(
            contentPadding: EdgeInsets.all(6.0),
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            content: Container(
              width: 300,
              height: 200,
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      IconButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          icon: Text("取消")),
                      Expanded(
                          child: Center(
                              child: Text(
                        "修改年龄",
                        style: Theme.of(context).textTheme.headline3,
                      ))),
                      IconButton(
                          onPressed: () {
                            callback(_index);
                            Navigator.of(context).pop();
                          },
                          icon: Text(
                            "确认",
                            style: Theme.of(context)
                                .textTheme
                                .subtitle1
                                .copyWith(color: Theme.of(context).accentColor),
                          )),
                    ],
                  ),
                  Divider(),
                  Expanded(
                    child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: CupertinoPicker.builder(
                          scrollController:
                              FixedExtentScrollController(initialItem: _index),
                          itemExtent: 40,
                          backgroundColor: Colors.white,
                          onSelectedItemChanged: (index) {
//                            print(index);
                            _index = index;
                          },
                          itemBuilder: (context, index) {
                            return Text("${_ages[index]}");
                          },
                          childCount: _ages.length,
                        )),
                  ),
                ],
              ),
            ),
          );
        });
  }

  void _selectAvatar() async {
    List<Asset> resultList;
    String error;

    try {
      resultList = await MultiImagePicker.pickImages(
          maxImages: 2,
          materialOptions: MaterialOptions(
            actionBarTitle: "选择图片",
            allViewTitle: "选择图片",
            startInAllView: true,
            selectionLimitReachedText: "不能选择更多了~",
          ));
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {});
  }
}
