import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:zhiying_base_widget/pages/mine_detail_page/mine_detail_bloc.dart';
import 'package:zhiying_base_widget/pages/mine_detail_page/models/mine_detail_model.dart';
import 'package:zhiying_base_widget/widgets/others/action_date_alert/action_date_alert.dart';
import 'package:zhiying_base_widget/widgets/others/action_list_alert/action_list_alert.dart';
import 'package:zhiying_base_widget/widgets/others/action_selected_alert/action_selected_alert.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class MineDetailPage extends StatefulWidget {
  @override
  _MineDetailPageState createState() => _MineDetailPageState();
}

class _MineDetailPageState extends State<MineDetailPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff9f9f9),
      appBar: _createNav(),
      body: SafeArea(
        child: BlocProvider<MineDetailBloc>(
          bloc: MineDetailBloc(),
          child: _MineDetailContainer(),
        ),
      ),
    );
  }

  // 导航栏
  Widget _createNav() {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: Colors.white,
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        '个人信息',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xff333333),
        ),
      ),
    );
  }
}

class _MineDetailContainer extends StatefulWidget {
  @override
  _MineDetailContainerState createState() => _MineDetailContainerState();
}

class _MineDetailContainerState extends State<_MineDetailContainer> {
  MineDetailBloc _bloc;
  TextEditingController _nickController = TextEditingController();

  @override
  void initState() {
    _bloc = BlocProvider.of<MineDetailBloc>(context);
    _bloc.loadData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<MineDetailModel>(
        stream: _bloc.outData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          MineDetailModel user = snapshot.data;
          if (user == null) {
            return Container();
          }
          int birthday = int.tryParse(user?.birthday) ?? 0;
          int registTime = int.tryParse(user?.registerTime) ?? 0;
          _nickController.text = user?.nickname ?? '';

          return SingleChildScrollView(
            child: Column(
              children: <Widget>[
                _creteHeader(user, onTap: () {
                  _selectImage();
                }),
                _createInput('昵称', _nickController, onTap: () {}),
                _createLine(),
                _createItem('性别', user?.gender, onTap: () {
                  _selectSex();
                }),
                _createLine(),
                _createItem(
                    '出生日期',
                    birthday > 0
                        ? DateFormat('yyyy-MM-dd').format(
                            DateTime.fromMillisecondsSinceEpoch(
                                birthday * 1000))
                        : user?.birthday ?? '', onTap: () {
                  _selectBrithday();
                }),
                _createLine(),
                _createItem(
                    '注册时间',
                    registTime > 0
                        ? DateFormat('yyyy-MM-dd').format(
                            DateTime.fromMillisecondsSinceEpoch(
                                registTime * 1000))
                        : user?.registerTime ?? ''),
              ],
            ),
          );
        });
  }

  // 头像
  Widget _creteHeader(MineDetailModel user, {VoidCallback onTap}) {
    return GestureDetector(
      child: Container(
        height: 140,
        width: double.infinity,
        margin: EdgeInsets.only(top: 5),
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Container(
              width: 80,
              height: 80,
              margin: EdgeInsets.only(top: 15),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(40),
                  color: Colors.black12),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(40),
                child: CachedNetworkImage(
                  imageUrl: user?.avatar ?? '',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(6.0),
              child: Text(
                user == null ? '' : '点击更换头像',
                style: TextStyle(fontSize: 11, color: Color(0xff999999)),
              ),
            )
          ],
        ),
      ),
      onTap: onTap,
    );
  }

  Widget _createItem(String title, String desc, {VoidCallback onTap}) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.only(left: 12.5, right: 12.5),
        height: 48,
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                title ?? '',
                style: TextStyle(
                    fontSize: 13,
                    color: Color(0xff333333),
                    fontWeight: FontWeight.bold),
              ),
            ),
            Text(
              desc ?? '',
              style: TextStyle(
                fontSize: 13,
                color: Color(0xff999999),
              ),
            ),
            onTap == null
                ? Container()
                : Icon(
                    Icons.arrow_forward_ios,
                    size: 12,
                    color: Color(0xff999999),
                  )
          ],
        ),
      ),
      onTap: onTap,
    );
  }

  Widget _createInput(String title, TextEditingController controller,
      {VoidCallback onTap}) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.only(left: 12.5, right: 12.5),
        height: 48,
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                title ?? '',
                style: TextStyle(
                    fontSize: 13,
                    color: Color(0xff333333),
                    fontWeight: FontWeight.bold),
              ),
            ),
            Expanded(
              child: CupertinoTextField(
                decoration: BoxDecoration(color: Colors.transparent),
                textInputAction: TextInputAction.done,
                controller: controller,
                textAlign: TextAlign.right,
                placeholder: '输入昵称',
                style: TextStyle(
                  fontSize: 13,
                  color: Color(0xff999999),
                ),
                onSubmitted: (value) {
                  if (value == null || value == '') {
                    Fluttertoast.showToast(msg: '昵称不为空');
                    return;
                  }
                  _bloc.updateUser(nickname: value);
                },
              ),
            ),
            onTap == null
                ? Container()
                : Icon(
                    Icons.arrow_forward_ios,
                    size: 12,
                    color: Color(0xff999999),
                  )
          ],
        ),
      ),
      onTap: onTap,
    );
  }

  Widget _createLine() {
    return Container(
      width: double.infinity,
      height: 0.5,
      margin: EdgeInsets.only(left: 12.5, right: 12.5),
      color: Color(0xfff4f4f4),
    );
  }

  void _selectImage() async {
    final picker = ImagePicker();
    PickedFile file;
    int index = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return ActionSelectedAlert(
            // title: '拍照/选择图片',
            actions: ['拍照', '从相册选择图片'],
          );
        },
        isScrollControlled: false,
        backgroundColor: Colors.transparent);
    if (index != null) {
      if (index == 0) {
        file = await picker.getImage(source: ImageSource.camera);
      } else {
        file = await picker.getImage(source: ImageSource.gallery);
      }

      if (file == null) return;
      File cropperFile = await ImageCropper.cropImage(
          sourcePath: file.path,
          aspectRatioPresets: [
            CropAspectRatioPreset.square,
          ],
          androidUiSettings: AndroidUiSettings(
              toolbarTitle: '图片剪裁',
              toolbarColor: HexColor.fromHex('#E52425'),
              toolbarWidgetColor: Colors.white,
              initAspectRatio: CropAspectRatioPreset.original,
              lockAspectRatio: true),
          iosUiSettings: IOSUiSettings(
              minimumAspectRatio: 1.0, aspectRatioLockEnabled: true));
      File resultFile = await EncodeUtil.compressImage(cropperFile, 800);
      _bloc.uploadAvatar(resultFile);
    }
  }

  // 选择性别
  void _selectSex() async {
    int index = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return ActionListAlert(
            title: '选择性别',
            actions: ['女', '男'],
          );
        },
        isScrollControlled: false,
        backgroundColor: Colors.transparent);
    if (index != null) {
      print(index);
      _bloc.updateUser(gender: index == 0 ? '1' : '2');
    }
  }

  void _selectBrithday() async {
    DateTime dateTime = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return ActionDateAlert(
            title: '选择出生日期',
          );
        },
        isScrollControlled: false,
        backgroundColor: Colors.transparent);
    if (dateTime != null) {
      String timeStamp =
          (dateTime.millisecondsSinceEpoch / 1000).ceil().toString();
      _bloc.updateUser(birthday: timeStamp);
    }
  }
}
