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

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:sport/application.dart';
import 'package:sport/bean/feed_back.dart';
import 'package:sport/bean/login.dart';
import 'package:sport/pages/my/feedback_detail_page.dart';
import 'package:sport/provider/feed_back_model.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/utils/DateFormat.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/button_primary.dart';
import 'package:sport/widgets/decoration.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/space.dart';

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

class _PageState extends State<FeedbackPage> with InjectLoginApi, InjectApi {
  FeedBackModel _feedBackModel = new FeedBackModel();
  bool _isLoading;
  FeedBackInfo _data;
  User _user;

  var _textFieldValue = "";
  TextEditingController _controller;
  FocusNode _focusNode;
  var _posting = false;
  int joinTime = 0;
  ValueNotifier<bool> _postable = ValueNotifier(false);

  @override
  void initState() {
    initData();

    _focusNode = FocusNode();
    _controller = TextEditingController()
      ..addListener(() {
        _postable.value = _controller.value.text.isNotEmpty;
      });

    _isLoading = true;
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode?.dispose();
    _controller?.dispose();
  }

  initData() async {
    _user = Provider.of<UserModel>(context, listen: false).user;
    await _feedBackModel.getFeedBackTypes();
    await refresh();
  }

  refresh() async {
    FeedBackInfo data = await _feedBackModel.getFeedBackInfo(limit: 50);
    List<FeedBackInfoData> list = [];
    var now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    if (data.data?.isNotEmpty == true) {
      list = data.data.reversed.toList();
      int index = 0;
      if (joinTime == 0) {
        joinTime = list[0].createTime;
      } else {
        for (var value in list) {
          if (value.createTime <= joinTime) {
            break;
          }
          index++;
        }
      }
      list.insert(index, FeedBackInfoData(from: "-1", createTime: now));
      list.insert(index, FeedBackInfoData(from: "-2", createTime: now));
    } else {
      list = [
        FeedBackInfoData(from: "-1", createTime: now),
        FeedBackInfoData(from: "-2", createTime: now)
      ];
      joinTime = now;
    }

    List<FeedBackInfoData> fixed = [];
    var t = 0;
    final day = 60 * 60 * 24;
    for (var e in list) {
      if (t == 0) {
        t = e.createTime;
      }
      print(
          "$t ${e.createTime} ${day} ${e.createTime + day} ${t > e.createTime + day}");
      if (t > e.createTime + day) {
        fixed.add(FeedBackInfoData(from: "-3", createTime: t));
      }
      fixed.add(e);
      t = e.createTime;
    }
    if (fixed.length > 2) {
      fixed.add(FeedBackInfoData(
          from: "-3", createTime: fixed[fixed.length - 1].createTime));
    }

    data.data = fixed;
    setState(() {
      _data = data;
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: buildAppBar(context, title: "用户反馈"),
        body: Column(
          children: <Widget>[
            Expanded(
              child: ChangeNotifierProvider<FeedBackModel>(
                create: (context) => _feedBackModel,
                child: Consumer<FeedBackModel>(
                  builder: (context, model, child) {
                    return _isLoading
                        ? RequestLoadingWidget()
                        : CustomScrollView(
                            reverse: (_data.data?.length ?? 0) > 2,
                            slivers: [
                                SliverList(
                                  delegate: SliverChildListDelegate(
                                    _data.data
                                        .map((e) => e.from == "-3"
                                            ? Center(
                                                child: Padding(
                                                    padding:
                                                        EdgeInsets.symmetric(
                                                            vertical: 8.0),
                                                    child: Text(
                                                      "${DateFormat.formatTime(e.createTime)}",
                                                      style: Theme.of(context)
                                                          .textTheme
                                                          .bodyText1,
                                                    )),
                                              )
                                            : e.from == "-1"
                                                ? Padding(
                                                    padding: const EdgeInsets
                                                            .symmetric(
                                                        vertical: 8.0,
                                                        horizontal: 12.0),
                                                    child: Row(
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: <Widget>[
                                                        CircleAvatar(
                                                          backgroundImage:
                                                              CachedNetworkImageProvider(
                                                                  "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2661558467,1288211245&fm=26&gp=0.jpg"),
                                                          radius: 20,
                                                        ),
                                                        Space(
                                                          width: 12,
                                                        ),
                                                        CustomPaint(
                                                          painter:
                                                              BubblePainter(),
                                                          child: Padding(
                                                            padding:
                                                                const EdgeInsets
                                                                        .fromLTRB(
                                                                    20.0,
                                                                    8.0,
                                                                    12,
                                                                    8),
                                                            child: Container(
                                                              child: Text(
                                                                "很高兴认识你",
                                                                style: Theme.of(
                                                                        context)
                                                                    .textTheme
                                                                    .subtitle1
                                                                    .copyWith(
                                                                        fontSize:
                                                                            16),
                                                              ),
                                                            ),
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                  )
                                                : e.from == "-2"
                                                    ? Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                    .symmetric(
                                                                vertical: 8.0,
                                                                horizontal:
                                                                    12.0),
                                                        child: Row(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: <Widget>[
                                                            CircleAvatar(
                                                              backgroundImage:
                                                                  CachedNetworkImageProvider(
                                                                      "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2661558467,1288211245&fm=26&gp=0.jpg"),
                                                              radius: 20,
                                                            ),
                                                            Space(
                                                              width: 12,
                                                            ),
                                                            CustomPaint(
                                                              painter:
                                                                  BubblePainter(),
                                                              child: Padding(
                                                                padding:
                                                                    const EdgeInsets
                                                                            .fromLTRB(
                                                                        20.0,
                                                                        8.0,
                                                                        12,
                                                                        8),
                                                                child: Container(
                                                                    child: Column(
                                                                  crossAxisAlignment:
                                                                      CrossAxisAlignment
                                                                          .start,
                                                                  children: <
                                                                      Widget>[
                                                                    Text(
                                                                      "常见问题",
                                                                      style: Theme.of(
                                                                              context)
                                                                          .textTheme
                                                                          .subtitle1
                                                                          .copyWith(
                                                                              fontSize: 16),
                                                                    ),
                                                                    Column(
                                                                      crossAxisAlignment:
                                                                          CrossAxisAlignment
                                                                              .start,
                                                                      children: model
                                                                          .data
                                                                          .data
                                                                          .map((e) => InkWell(
                                                                              onTap: () {
                                                                                NavigatorUtil.goPage(context, (context) => FeedbackDetailPage(e));
                                                                                // NavigatorUtil.go(context, "${Routes.feedbackDetail}?data=${Uri.encodeComponent(json.encode(e))}");
                                                                              },
                                                                              child: Padding(
                                                                                padding: EdgeInsets.symmetric(vertical: 5.0),
                                                                                child: Text("${model.data.data.indexOf(e) + 1}.${e.groupName}", style: Theme.of(context).textTheme.subtitle1.copyWith(color: Color(0xff666666), fontSize: 16)),
                                                                              )))
                                                                          .toList(),
                                                                    ),
                                                                  ],
                                                                )),
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      )
                                                    : Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                    .symmetric(
                                                                vertical: 8.0,
                                                                horizontal:
                                                                    12.0),
                                                        child: Row(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          mainAxisAlignment: e
                                                                      .from ==
                                                                  "user"
                                                              ? MainAxisAlignment
                                                                  .end
                                                              : MainAxisAlignment
                                                                  .start,
                                                          children:
                                                              e.from == "user"
                                                                  ? <Widget>[
                                                                      CustomPaint(
                                                                          painter:
                                                                              BubblePainterRight(),
                                                                          child:
                                                                              ConstrainedBox(
                                                                            constraints:
                                                                                BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.6),
                                                                            child:
                                                                                Container(
                                                                              padding: EdgeInsets.fromLTRB(12, 6, 20, 8),
                                                                              child: Column(
                                                                                children: <Widget>[
                                                                                  Text(
                                                                                    "${e.content}",
                                                                                    style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16, color: Color(0xff333333)),
                                                                                  ),
                                                                                  if (e.images?.isNotEmpty == true)
                                                                                    GridView.count(
                                                                                        physics: new NeverScrollableScrollPhysics(),
                                                                                        shrinkWrap: true,
                                                                                        padding: EdgeInsets.zero,
                                                                                        crossAxisSpacing: 10.0,
                                                                                        crossAxisCount: e.images?.length ?? 0,
                                                                                        children: e.images
                                                                                            .asMap()
                                                                                            .keys
                                                                                            .map((i) => CachedNetworkImage(
                                                                                                  imageUrl: e.images[i],
                                                                                                  fit: BoxFit.cover,
                                                                                                ))
                                                                                            .toList())
                                                                                ],
                                                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                                              ),
                                                                            ),
                                                                          )),
                                                                      Space(
                                                                        width:
                                                                            12,
                                                                      ),
                                                                      CircleAvatar(
                                                                        backgroundImage:
                                                                            userAvatarProvider(_user?.avatar),
                                                                        radius:
                                                                            20,
                                                                      ),
                                                                    ]
                                                                  : <Widget>[
                                                                      CircleAvatar(
                                                                        backgroundImage:
                                                                            CachedNetworkImageProvider("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2661558467,1288211245&fm=26&gp=0.jpg"),
                                                                        radius:
                                                                            20,
                                                                      ),
                                                                      Space(
                                                                        width:
                                                                            12,
                                                                      ),
                                                                      CustomPaint(
                                                                          painter:
                                                                              BubblePainter(),
                                                                          child:
                                                                              ConstrainedBox(
                                                                            constraints:
                                                                                BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.6),
                                                                            child:
                                                                                Container(
                                                                              padding: EdgeInsets.fromLTRB(12, 6, 20, 8),
                                                                              child: Text(
                                                                                "${e.content}",
                                                                                style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16),
                                                                              ),
                                                                            ),
                                                                          )),
                                                                    ],
                                                        ),
                                                      ))
                                        .toList(),
                                  ),
                                )
                              ]);
                  },
                ),
              ),
            ),
            ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 150, minHeight: 50),
              child: Container(
                decoration: shadowTop(),
                child: Row(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        _postImage();
                      },
                      child: Padding(
                        padding: const EdgeInsets.symmetric(
                            vertical: 8.0, horizontal: 12.0),
                        child:
                            Image.asset("lib/assets/img/bbs_icon_picture.png"),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        child: TextField(
                          controller: _controller,
                          focusNode: _focusNode,
                          keyboardType: TextInputType.multiline,
                          strutStyle:
                              StrutStyle(forceStrutHeight: true, height: 1.4),
                          minLines: 1,
                          maxLines: 3,
                          maxLength: 200,
                          style: TextStyle(fontSize: 16.0),
                          onChanged: (value) {
                            setState(() {
                              _textFieldValue = value;
                            });
                          },
                          decoration: InputDecoration(
                              counterText: "",
                              hintText: "提交你的反馈...",
                              contentPadding:
                                  EdgeInsets.symmetric(vertical: 16.0),
                              border: InputBorder.none,
                            hintStyle: TextStyle(color: Color(0xff999999))
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12.0),
                      child: _posting
                          ? SizedBox(
                              height: 22,
                              width: 22,
                              child: CircularProgressIndicator(),
                            )
                          :
                          ValueListenableBuilder(
                              valueListenable: _postable,
                              builder: (_, able, __) => PrimaryButton(
                                    content: "提交",
                                    width: 80,
                                    height: 35,
                                    callback: () async {
                                      setState(() {
                                        _posting = true;
                                      });
                                      _controller.clear();

                                      await _postFeedBackpostFeedBack(
                                          _textFieldValue);
                                      // ToastUtil.show("提交成功");

                                      setState(() {
                                        _textFieldValue = '';
                                        _posting = false;
                                      });
                                      refresh();
                                    },
                                    shadow: able == true,
                                    buttonColor: able == false
                                        ? Color(0xffFFC400).withOpacity(0.3)
                                        : null,
                                  )),
                    )
                  ],
                ),
              ),
            )
          ],
        ));
  }

  _postImage() async {
    List<Asset> resultList = [];
    try {
      resultList = await MultiImagePicker.pickImages(
          maxImages: 3,
          materialOptions: MaterialOptions(
            actionBarTitle: "选择图片",
            allViewTitle: "选择图片",
            useDetailsView: true,
            startInAllView: true,
            selectionLimitReachedText: "不能选择更多了~",
          ),
          cupertinoOptions: CupertinoOptions(
            selectionFillColor: "#ff11ab",
            selectionTextColor: "#ffffff",
            selectionCharacter: "✓",
          ));
    } on Exception catch (e) {
      e.toString();
    }
    if (resultList == null || resultList.isEmpty) return;

    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => SimpleDialog(
              children: <Widget>[PostAction(_textFieldValue, resultList)],
            )).then((value) {
      ToastUtil.show("提交成功");
      refresh();
    }).catchError((e) {});
  }

  _postFeedBackpostFeedBack(String content, {int typeId = 0}) async {
    typeId == null ? typeId = 0 : typeId = typeId;
    await api.postFeedback(typeId, content,
        extra: await Application.getDeviceInfo());
  }
}

class PostAction extends StatefulWidget {
  final String content;
  final List<Asset> imageList;

  const PostAction(this.content, this.imageList);

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

class PostActionState extends State<PostAction> with InjectApi {
  final Map<Asset, String> upload = {};
  ValueNotifier<String> _msg;

  @override
  void initState() {
    super.initState();
    _msg = ValueNotifier<String>("请稍候...");
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      post();
    });
  }

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

  void post() async {
    List<Asset> imageList = widget.imageList;
    if (imageList != null && imageList.isNotEmpty) {
      Directory tempDir = await getTemporaryDirectory();
      Directory directory = new Directory('${tempDir.path}/upload');
      if (!directory.existsSync()) {
        directory.createSync();
        print('文档初始化成功，文件保存路径为 ${directory.path}');
      }

      for (var i = 0; i < imageList.length; i++) {
        Asset asset = imageList[i];
        if (upload.containsKey(asset)) continue;
        ByteData byteData = await asset.getByteData(quality: 85);
        File file = File(
            '${directory.path}/${DateTime.now().millisecondsSinceEpoch}_$i.jpg');
        List<int> bytes = byteData.buffer.asUint8List().toList();
        print('临时文件 ${file.path} ${bytes.length}');
        file.writeAsBytesSync(bytes);
        _msg.value = "上传图片(${i + 1}/${imageList.length})...";
        var resp = await api.mediaUp4Feedback(file);
        var image = resp.data;
        file.delete();
        upload[asset] = image;
        // await Future.delayed(Duration(seconds: 3));
      }
    }

    _msg.value = "发布中...";
    // await Future.delayed(Duration(seconds: 3));
    var data = await api.postFeedback(0, '图片',
        images: json.encode(upload.values.toList()),
        extra: await Application.getDeviceInfo());
    print(data);
    if (data.code == 0) {
      Navigator.of(context).pop(true);
    } else {
      Navigator.of(context).pop(false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Column(
        children: <Widget>[
          CircularProgressIndicator(),
          Padding(
            padding: const EdgeInsets.only(top: 15),
            child: ValueListenableBuilder(
                valueListenable: _msg,
                builder: (BuildContext context, String value, Widget child) =>
                    Text(value)),
          )
        ],
      ),
    );
  }
}

//class _BubblePainter extends CustomPainter {
//  final circular = Radius.circular(10);
//  final Paint _paint = Paint()..color = Colors.white;
//  final double _bubbleWidth = 10;
//
//  @override
//  void paint(Canvas canvas, Size size) {
////    Path path = Path()..moveTo(size.width,  size.height / 2)..quadraticBezierTo(size.width / 3*2, size.height / 2 + 50, 0, size.height / 2)
////    ..quadraticBezierTo(size.width / 3, size.height,size.width,size.height)..close();
//    Path path = Path()
//      ..moveTo(_bubbleWidth + 1, _bubbleWidth)
//      ..quadraticBezierTo(_bubbleWidth / 3 * 2, _bubbleWidth + 4, 0, _bubbleWidth)
//      ..quadraticBezierTo(_bubbleWidth / 3, _bubbleWidth + _bubbleWidth / 2, _bubbleWidth + 1, _bubbleWidth * 2)
//      ..close();
//    canvas.drawPath(path, _paint);
//    canvas.drawRRect(RRect.fromLTRBR(_bubbleWidth, 0, size.width, size.height, circular), _paint);
//  }
//
//  @override
//  bool shouldRepaint(CustomPainter oldDelegate) {
//    return oldDelegate != this;
//  }
//}
//
//class _BubblePainterRight extends CustomPainter {
//  final circular = Radius.circular(10);
//  final Paint _paint = Paint()..color = Color(0xffFFC400);
//  final double _bubbleWidth = 10;
//
//  @override
//  void paint(Canvas canvas, Size size) {
////    Path path = Path()..moveTo(size.width,  size.height / 2)..quadraticBezierTo(size.width / 3*2, size.height / 2 + 50, 0, size.height / 2)
////    ..quadraticBezierTo(size.width / 3, size.height,size.width,size.height)..close();
//    double left = size.width - _bubbleWidth;
//    Path path = Path()
//      ..moveTo(left, _bubbleWidth)
//      ..quadraticBezierTo(left + _bubbleWidth / 3 * 2, _bubbleWidth + 4, size.width, _bubbleWidth)
//      ..quadraticBezierTo(left + _bubbleWidth / 3, _bubbleWidth + _bubbleWidth / 2, left, _bubbleWidth * 2)
//      ..close();
//    canvas.drawPath(path, _paint);
//    canvas.drawRRect(RRect.fromLTRBR(0, 0, size.width - _bubbleWidth, size.height, circular), _paint);
//  }
//
//  @override
//  bool shouldRepaint(CustomPainter oldDelegate) {
//    return oldDelegate != this;
//  }
//}

class BubblePainter extends CustomPainter {
  final circular = Radius.circular(10);
  final Paint _paint = Paint()
    ..color = Colors.white
  ..strokeJoin = StrokeJoin.round
  ;
  final double _bubbleWidth = 6;

  @override
  void paint(Canvas canvas, Size size) {
//    Path path = Path()..moveTo(size.width,  size.height / 2)..quadraticBezierTo(size.width / 3*2, size.height / 2 + 50, 0, size.height / 2)
//    ..quadraticBezierTo(size.width / 3, size.height,size.width,size.height)..close();
    Path path = Path()
      ..moveTo(_bubbleWidth + 1, 10)
      ..lineTo(0, 15)
      ..lineTo(0, 16)
      ..lineTo(_bubbleWidth + 1, 21)
      ..close();
    canvas.drawPath(path, _paint);
    canvas.drawRRect(
        RRect.fromLTRBR(_bubbleWidth, 0, size.width, size.height, circular),
        _paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return oldDelegate != this;
  }
}

class BubblePainterRight extends CustomPainter {
  final circular = Radius.circular(10);
  final Paint _paint = Paint()..color = Color(0xffffe400).withOpacity(0.7)
    ..strokeJoin = StrokeJoin.round;
  final double _bubbleWidth = 6;

  @override
  void paint(Canvas canvas, Size size) {
//    Path path = Path()..moveTo(size.width,  size.height / 2)..quadraticBezierTo(size.width / 3*2, size.height / 2 + 50, 0, size.height / 2)
//    ..quadraticBezierTo(size.width / 3, size.height,size.width,size.height)..close();
    double left = size.width - _bubbleWidth - 1;
    Path path = Path()
      ..moveTo(left, 10)
      ..lineTo(size.width, 15)
      ..lineTo(size.width, 16)
      ..lineTo(left, 21)
      ..close();
    canvas.drawPath(path, _paint);
    canvas.drawRRect(
        RRect.fromLTRBR(0, 0, size.width - _bubbleWidth, size.height, circular),
        _paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return oldDelegate != this;
  }
}
