import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../basic/Common.dart';
import '../../basic/Entities.dart';
import '../../basic/Method.dart';
import 'Avatar.dart';
import 'Images.dart';
import 'ItemBuilder.dart';

const double _cardHeight = 180;

// 用户信息卡
class UserProfileCard extends StatefulWidget {
  const UserProfileCard({Key? key, required this.load}) : super(key: key);

  final Future<Profile?> Function() load;

  @override
  State<StatefulWidget> createState() => _UserProfileCardState();
}

class _UserProfileCardState extends State<UserProfileCard> {
  late Future<Profile?> _future = widget.load();

  // Future<UserProfile?> _load() async {
  //   var profile = await method.getProfile(widget.name);
  //   return profile;
  // }

  @override
  Widget build(BuildContext context) {
    var nameStyle = const TextStyle(
      fontSize: 14,
      fontWeight: FontWeight.bold,
    );
    var nameStrutStyle = const StrutStyle(
      fontSize: 14,
      forceStrutHeight: true,
      fontWeight: FontWeight.bold,
    );
    return ItemBuilder(
      future: _future,
      onRefresh: () async {
        setState(() => _future = widget.load());
      },
      height: _cardHeight,
      successBuilder:
          (BuildContext context, AsyncSnapshot<Profile?> snapshot) {
        Profile profile = snapshot.data!;
        return Stack(
          children: [
            SizedBox(
              height: _cardHeight,
              child: Column(
                children: [
                  Expanded(child: Container()),
                  GestureDetector(
                    onTap: () async {
                      if (Platform.isAndroid || Platform.isIOS) {
                        await _updateAvatarPhone();
                      }
                    },
                    child: Avatar(profile.avatar, size: 65),
                  ),
                  Container(height: 5),
                  Text(
                    profile.name,
                    style: nameStyle,
                    strutStyle: nameStrutStyle,
                  ),
                  Container(height: 8),
                  Expanded(child: Container()),
                ],
              ),
            )
          ],
        );
      },
    );
  }

  void _reload() {
    setState(() {
      _future = widget.load();
    });
  }

  Future _updateAvatarPhone() async {
    final assets = await AssetPicker.pickAssets(context,
        pickerConfig: const AssetPickerConfig(maxAssets: 1));
    if (assets == null || assets.isEmpty) return;
    final image = await assets.first.file;
    // final ImagePicker _picker = ImagePicker();
    // final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      final cropper = ImageCropper();
      final croppedFile = await cropper.cropImage(
        sourcePath: image.path,
        aspectRatioPresets: [
          CropAspectRatioPreset.square,
        ],
        aspectRatio: const CropAspectRatio(ratioX: 200, ratioY: 200),
        maxWidth: 200,
        maxHeight: 200,
        uiSettings: [AndroidUiSettings(
          toolbarTitle: "修改头像",
          toolbarColor: Colors.blue,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.original,
          lockAspectRatio: true,
        ),
        IOSUiSettings(
          resetAspectRatioEnabled: true,
          aspectRatioLockEnabled: true,
          title: "修改头像",
        ),]
      );
      if (croppedFile != null) {
        final path = image.path;
        final suf = path.substring(path.lastIndexOf('.'));
        var buff = await croppedFile.readAsBytes();
        // var data = base64Encode(buff);
        await method.updateAvatar(buff, suf);
        _reload();
      }
      // final buff = image.readAsBytesSync();
      // await method.updateAvatar(buff);
      // _reload();
    }
  }
}
