import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_crop/image_crop.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/pages/login/license.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/widgets/button_primary.dart';

class Input extends StatefulWidget {
  String labelText;
  Function callBack;
  double height;
  double width;
  bool obscureText;
  FocusNode focusNode;
  TextEditingController controller;
  TextInputAction textInputAction;
  TextInputType textInputType;
  int maxLength;

  Input({
    this.labelText,
    this.callBack,
    this.obscureText = false,
    this.height = 44.0,
    this.width = 300,
    this.focusNode,
    this.controller,
    this.textInputType,
    this.textInputAction,
    this.maxLength,
  });

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _InputState();
  }
}

class _InputState extends State<Input> {
  @override
  Widget build(BuildContext context) {
    return Container(
        height: widget.height,
        width: widget.width,
        margin: EdgeInsets.symmetric(vertical: 6.0),
        child: TextField(
            maxLength: widget.maxLength,
            keyboardType: widget.textInputType,
            style: TextStyle(fontSize: 16.0, color: Color(0xff333333)),
            textInputAction: widget.textInputAction,
            obscureText: widget.obscureText,
            focusNode: widget.focusNode,
            controller: widget.controller,
            inputFormatters: [
              if (widget.textInputType == TextInputType.phone) WhitelistingTextInputFormatter(RegExp("[0-9*#]")),
            ],
            decoration: InputDecoration(
              counterText: "",
              contentPadding: EdgeInsets.symmetric(vertical: widget.height >= 40 ? 14.0: 9.0, horizontal: 16.0),
              border: OutlineInputBorder(
                borderSide: BorderSide(color: Color.fromRGBO(206, 206, 206, 1),width: 0.5),
                borderRadius: BorderRadius.all(Radius.circular(44.0)),
              ),
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Theme.of(context).accentColor,width:1.0),
                borderRadius: BorderRadius.all(Radius.circular(44.0)),
              ),
              enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Color.fromRGBO(206, 206, 206, 1),width: 0.5),
                borderRadius: BorderRadius.all(Radius.circular(44.0)),
              ),
              labelText: widget.labelText,
              labelStyle: TextStyle(fontSize: 14.0, color: Color(0xffc2c2c2)),
              floatingLabelBehavior: FloatingLabelBehavior.never,
             prefixIcon:  widget.textInputType == TextInputType.phone ?Row(children: <Widget>[Padding(
               padding: const EdgeInsets.only(left: 12.0, right: 4.0),
               child: Text("+86", style: Theme.of(context).textTheme.subtitle1,),
             ), VerticalDivider(indent: 8.0, endIndent: 8.0,)],mainAxisSize: MainAxisSize.min,):null
            ),
            onChanged: widget.callBack));
  }
}

Widget button(text, callBack) {
  return Padding(
    padding: const EdgeInsets.only(bottom: 32.0),
    child: PrimaryButton(
      width: 300,
      content: text,
      callback: callBack,
    ),
  );
  //
  //   InkWell(
  //   child: Container(
  //     width: 300,
  //     height: 44.0,
  //     alignment: Alignment.center,
  //     decoration: BoxDecoration(
  //         borderRadius: BorderRadius.all(Radius.circular(44.0)),
  //         gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
  //           Color.fromRGBO(255, 196, 0, 1),
  //           Color.fromRGBO(255, 170, 0, 1),
  //         ])),
  //     child: Text(
  //       text,
  //       style: TextStyle(color: Colors.white, fontSize: 16.0),
  //     ),
  //   ),
  //   onTap: () {
  //     callBack();
  //   },
  // );
}

class BuildCroppingImagePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _BuildCroppingImagePageState();
  }
}

class _BuildCroppingImagePageState extends State<BuildCroppingImagePage> with InjectLoginApi {
  final cropKey = GlobalKey<CropState>();
  File _file;
  File _sample;
  File _lastCropped;

  @override
  void initState() {
    super.initState();
    _openImage();
  }

  @override
  void dispose() {
    super.dispose();
    _file?.delete();
    _sample?.delete();
    _lastCropped?.delete();
  }

  Future<void> _cropImage() async {
    final scale = cropKey.currentState.scale;
    final area = cropKey.currentState.area;
    if (area == null) {
      // cannot crop, widget is not setup
      return;
    }

    // scale up to use maximum possible number of pixels
    // scale up to use maximum possible number of pixels
    // this will sample image in higher resolution to make cropped image larger
    final sample = await ImageCrop.sampleImage(
      file: _file,
      preferredSize: (2000 / scale).round(),
    );

    final file = await ImageCrop.cropImage(
      file: sample,
      area: area,
    );

    sample.delete();

    _lastCropped?.delete();
    _lastCropped = file;
    setState(() {
      _sample = null;
    });
    print(_file);
    fetchUploadProductBanner(_file);
    Navigator.pop(context, _lastCropped);
  }

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

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

  Future<void> _openImage() async {
    final file = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (file == null) {
      Navigator.pop(context, null);
      return;
    }
    final sample = await ImageCrop.sampleImage(
      file: file,
      preferredSize: context.size.longestSide.ceil(),
    );

    _sample?.delete();
    _file?.delete();

    setState(() {
      _sample = sample;
      _file = file;
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return _sample == null
        ? Container()
        : Column(
            children: <Widget>[
              Expanded(
                child: Crop.file(_sample, key: cropKey),
              ),
              Container(
                padding: const EdgeInsets.only(top: 20.0),
                alignment: AlignmentDirectional.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    FlatButton(
                      child: Text(
                        '确定',
                        style: Theme.of(context).textTheme.button.copyWith(color: Colors.white),
                      ),
                      onPressed: () => _cropImage(),
                    ),
                  ],
                ),
              )
            ],
          );
  }
}
