import 'package:chat/models/ChatMsg.dart';
import 'package:chat/proto/all.pbserver.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:chat/utils/sql_util.dart';
import 'package:chat/utils/upload_util.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:percent_indicator/percent_indicator.dart';

class UploadImgItem extends StatefulWidget {
  final MsgModel msg;
  final Widget child;
  final bool isShowProgress;
  final CancelToken cancelToken;

  UploadImgItem(
      {this.msg, this.child, this.isShowProgress = true, this.cancelToken});

  @override
  _UploadItemState createState() => _UploadItemState();
}

class _UploadItemState extends State<UploadImgItem> {
  double percent = 0;

  @override
  void initState() {
    super.initState();
    MsgModel msg = widget.msg;

    if (msg.localFile != null && msg.state == MsgState.None) {
      //需要上传
      uploadImg();
    }

    MessageMgr().on('ReUpload Msg', reUpload);
  }

  @override
  void dispose() {
    MessageMgr().off('ReUpload Msg', reUpload);

    super.dispose();
  }

  reUpload(args) {
    if (args == widget.msg) {
      print('重新上传');
      uploadImg();
    }
  }

  uploadImg() async {
    if (widget.msg.state == MsgState.Uploading ||
        widget.msg.state == MsgState.Uploaded) {
      return;
    }

    widget.msg.state = MsgState.Uploading;
    await UploadUtil().uploadFile(widget.msg, cancelToken: widget.cancelToken);

    if (mounted) {
      this.setState(() {});
    }

    SqlUtil().updateMsgState(
        widget.msg.sessionId, widget.msg.time, widget.msg.state);
  }

  uploadWidget() {
    if (widget.msg.state == MsgState.Uploading && widget.isShowProgress) {
      return StreamBuilder(
        stream: UploadUtil().getStream(widget.msg.extraFile).stream,
        initialData: UploadUtil().streamLastPercentMap[widget.msg.extraFile],
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data != null) {
            if (snapshot.data >= 1) {
              return SizedBox(width: 0, height: 0);
            }

            return CircularPercentIndicator(
              radius: 30.0,
              lineWidth: 2.0,
              percent: snapshot.data,
              center: Padding(
                  padding: EdgeInsets.all(2),
                  child: fixedText(
                      "${(snapshot.data * 100).toStringAsFixed(0)}%",
                      fontSize: 9,
                      color: Colors.green)),
              progressColor: Colors.green,
            );
          } else {
            return SizedBox(width: 0, height: 0);
          }
        },
      );
    } else if (widget.msg.state == MsgState.UploadFailed) {
      //声音重传按钮叠加比较丑，和发送失败一起处理
      if (widget.msg.msgType == ChatType.ShortVoiceChatType.value) {
        return SizedBox(width: 0, height: 0);
      }
      return InkWell(
        onTap: uploadImg,
        child: Container(
          padding: EdgeInsets.all(5),
          decoration: BoxDecoration(
              color: Colors.grey.withAlpha(150),
              borderRadius: BorderRadius.circular(8)),
          child: Icon(Icons.rotate_right, color: Colors.white70),
        ),
      );
    } else if (widget.msg.msgType == ChatType.ShortVideoChatType.value &&
        widget.msg.state >= MsgState.Uploaded) {
      return Icon(Icons.play_circle_outline, color: Colors.white);
    } else {
      return SizedBox(width: 0, height: 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[widget.child, uploadWidget()],
    );
  }
}
