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

import 'package:chat/chat/gift_select_widget.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/VipPage.dart';
import 'package:chat/map/google_map_location_picker.dart';
import 'package:chat/models/UserInfo.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/proto/all.pbserver.dart';
import 'package:chat/utils/ChargeMoney.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/blacklist_mgr.dart';
import 'package:chat/utils/file_cache_mgr.dart';
import 'package:chat/utils/image_util.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
//import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:file_picker/file_picker.dart';

import '../r.dart';

class UtilKeyboard extends StatefulWidget {
  final double keyboardHeight;
  final Function sendMsg;
  final bool isGroup;
  UtilKeyboard({this.keyboardHeight, this.sendMsg, this.isGroup});

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

class _UtilKeyboardState extends State<UtilKeyboard> {
  bool isAuthority = false;

  @override
  Widget build(BuildContext context) {
    bool isShowRedPacket = UserData().redPacketSW > 0;

    List<Widget> iconList = [];
    iconList.add(
        _buildOtherSelect(R.assetsImagesChatItem1, I18n.of(context).camera, () {
      print('开始选择拍照');
      _sendPicture(context);
    }));

    iconList.add(
        _buildOtherSelect(R.assetsImagesChatItem2, I18n.of(context).video, () {
      print('开始选择视频');
      _sendVideo(context);
    }));

    if (!widget.isGroup) {
      iconList.add(
          _buildOtherSelect(R.assetsImagesChatItem3, I18n.of(context).chat, () {
        _audioChat(context);
      }));
    }

    iconList.add(
        _buildOtherSelect(R.assetsImagesChatItem4, I18n.of(context).locate, () {
      _openMap(context);
    }));

    if (!widget.isGroup) {
      iconList.add(Offstage(
          offstage: !isShowRedPacket,
          child: _buildOtherSelect(
              R.assetsImagesChatItem5, I18n.of(context).red_money, () {
            int friendId = Provider.of<int>(context);
            if (BlacklistMgr.isBlack(friendId)) {
              return;
            }
            AppNavigator.pushCoinBagPage(context);
          })));

      iconList.add(_buildOtherSelect(
          R.assetsImagesChatItem6, I18n.of(context).giving_gift, () {
        _showGiftSheet(context);
      }));
    }

    iconList.add(_buildOtherSelect(
        R.assetsImagesChatItem7, I18n.of(context).file, () async {
      _sendFile(context);
    }));

    return Container(
        width: Screen.width,
        color: Colors.white,
        height: widget.keyboardHeight,
        padding: EdgeInsets.only(top: 20, bottom: 10, left: 20),
        alignment: Alignment.topLeft,
        child: Wrap(spacing: 10.0, runSpacing: 20.0, children: iconList));
  }

  _showGiftSheet(BuildContext context) {
    int friendId = 0;
    if (!widget.isGroup) {
      friendId = Provider.of<int>(context);
    }

    showModalBottomSheet(
        context: context,
        elevation: 2.0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20), topRight: Radius.circular(20))),
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (BuildContext context, setBottomSheetState) {
              return GiftSelectWidget(friendId, widget.sendMsg);
            },
          );
        });
  }

  _openMap(BuildContext context) async {
    if (await CustomUI.showPermissionSetting(
        context, PermissionGroup.location, I18n.of(context).open_location)) {
      var result = await LocationPicker.pickLocation(
          context, 'AIzaSyAb9JNtW0BEZ_qLeDg87ZhvxSmZply-7hU',
          initialCenter: LatLng(UserData().latitude, UserData().longitude));

      if (result == null ||
          result.address == null ||
          result.address.length == 0) {
        return;
      }

      var reslutStr = jsonEncode(result);

      int friendId = 0;
      if (!widget.isGroup) {
        friendId = Provider.of<int>(context);
      }
      var msg = MsgHandler.createSendMsg(
          ChatType.PlaceChatType, utf8.encode(reslutStr),
          friendId: friendId,
          channelType:
              widget.isGroup ? ChatChannelType.Group : ChatChannelType.Session);

      widget.sendMsg(msg);
    }
  }

  _audioChat(BuildContext context) async {
    if (await CustomUI.showPermissionSetting(context,
        PermissionGroup.microphone, I18n.of(context).video_permission)) {
      int friendId = Provider.of<int>(context);
      UserInfo info = await HttpUtil().getFriendInfo(friendId, true);

      if (info == null) {
        print('获取用户信息失败');
        return;
      }

      if (info.chatStatus == 0) {
        showToast(I18n.of(context).cantt_voice);
        return;
      }

      if (BlacklistMgr.isBlack(info.userId)) {
        return;
      }

      //对方关闭陌生人消息，则提示
      if (!info.isCanStrangerNews) {
        showToast(I18n.of(context).stranger_close_tips);
        return;
      }

      if (info.isAuthority ||
          (!UserData().isMan() && UserData().basicInfo.isAttestation) ||
          info.distince < 200) {
        isAuthority = true;
      }
      becomeVip() {
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return VipPage();
            },
          ),
        );
      }

      payCallback() {
        if (Provider.of<MoneyChangeProvider>(context).money <
            UserData().accountPrice) {
          Navigator.of(context).pop();
          CustomUI.buildOneConfirm(
              context,
              I18n.of(context).balance_insufficien,
              I18n.of(context).recharge, () {
            Navigator.of(context).pop();
            ChargeMoney.showChargeSheet(context, () {});
          });
          return;
        }
        Navigator.of(context).pop();
        HttpUtil().buyChatAccount(UserData().accountPrice, info.userId, context,
            () {
          isAuthority = true;
        });
      }

      freeTime() {
        HttpUtil().userFreeTime(context, info.userId, 2, () {
          UserData().basicInfo.usedNum++;
          Navigator.of(context).pop();
          isAuthority = true;
        });
      }

      if (!isAuthority) {
        if (UserData().isVip) {
          UserData().basicInfo.freeNum < UserData().basicInfo.usedNum
              ? CustomUI.buildOneConfirm(
                  context,
                  I18n.of(context).unlock_information,
                  I18n.of(context)
                      .pay_unlock
                      .replaceFirst('/s1', UserData().accountPrice.toString()),
                  payCallback)
              : CustomUI.buildOneConfirm(
                  context,
                  I18n.of(context).unlock_information,
                  I18n.of(context).unlock_choose,
                  freeTime,
                );
        } else {
          CustomUI.buildTowConfirm(
              context,
              I18n.of(context).unlock_information,
              I18n.of(context).become_member,
              becomeVip,
              I18n.of(context)
                  .pay_unlock
                  .replaceFirst('/s1', UserData().accountPrice.toString()),
              payCallback);
        }
        return;
      }
      AppNavigator.pushAudioChatPage(context, info);
    }
  }

  void _sendPicture(BuildContext context) async {
    if (await CustomUI.showPermissionSetting(
        context, PermissionGroup.camera, I18n.of(context).camera_permission)) {
      File imgFile = await ImagePicker.pickImage(source: ImageSource.camera);

      if (imgFile == null) {
        return;
      }
      var imgSize = await imgFile.length();

      print('图片大小:${imgSize / 1024}KB');
      var sendImg;

      bool isNeedUpload = false;
      if (imgSize > ImgSizeLimit) {
        print('图片大于 $ImgSizeLimit,压缩');
        //发送压缩图
        sendImg = await WidgetUtil.getCompressImg(imgFile.absolute.path);
        isNeedUpload = true;
      } else {
        sendImg = imgFile.readAsBytesSync().toList();
      }

      var rect = await WidgetUtil.getImageWH(
          image: Image.memory(Uint8List.fromList(sendImg)));

      int aspectRatio = rect.width * 100 ~/ rect.height;

      int friendId = 0;
      if (!widget.isGroup) {
        friendId = Provider.of<int>(context);
      }
      var msg = MsgHandler.createSendMsg(ChatType.ImageChatType, sendImg,
          extra: aspectRatio,
          friendId: friendId,
          localFile: isNeedUpload ? imgFile.absolute.path : null,
          channelType:
              widget.isGroup ? ChatChannelType.Group : ChatChannelType.Session);

      widget.sendMsg(msg);
    }
  }

  void _sendFile(BuildContext context) async {
    File file = await FilePicker.getFile();
    int fileSize = file.lengthSync();
    print('选择的文件 ${file.path} 大小 $fileSize');

    if (fileSize > 33 * 1024 * 1024) {
      showToast(I18n.of(context).max_file.replaceFirst('/s1', 33.toString()));
      return;
    }
    ///ios存在着文件夹才打得开
   File newFile= await FileCacheMgr().writeFile(file.path.split('/').last, file.readAsBytesSync());




    int friendId = 0;
    if (!widget.isGroup) {
      friendId = Provider.of<int>(context);
    }
    var fileName = file.path.split('/').last;
    print('fileName  $fileName');

    var ext = '';
    var extList = fileName.split('.');
    if (extList.length > 1) {
      ext = extList.last;
    }
    print('ext  $ext');

    var fileMsg = FileChat.create();
    fileMsg.type = ext;
    fileMsg.size = fileSize;
    fileMsg.name = fileName;

    var msg = MsgHandler.createSendMsg(
        ChatType.FileChatType, fileMsg.writeToBuffer(),
        friendId: friendId,
        localFile: newFile.path,
        channelType:
            widget.isGroup ? ChatChannelType.Group : ChatChannelType.Session);

    widget.sendMsg(msg);
  }

  void _sendVideo(BuildContext context) async {
    if (await CustomUI.showPhotoPermissionSetting(context)) {
      File video = await ImagePicker.pickVideo(source: ImageSource.gallery);

      if (video == null) {
        return;
      }
      var videoSize = await video.length();
      print('视频大小:$videoSize');

      if (videoSize > 33 * 1024 * 1024) {
        showToast(I18n.of(Constants.getCurrentContext()).video_more_big);
        return;
      }

      final thumbnail = await getVideoThumbnail(video);

      var rect = await WidgetUtil.getImageWH(
          image: Image.memory(Uint8List.fromList(thumbnail)));

      int aspectRatio = rect.width * 100 ~/ rect.height;

      int friendId = 0;
      if (!widget.isGroup) {
        friendId = Provider.of<int>(context);
      }
      var msg = MsgHandler.createSendMsg(ChatType.ShortVideoChatType, thumbnail,
          extra: aspectRatio,
          friendId: friendId,
          localFile: video.path,
          channelType:
              widget.isGroup ? ChatChannelType.Group : ChatChannelType.Session);

      widget.sendMsg(msg);
    }
  }

  getVideoThumbnail(File video) async {
    List<int> thumbnail = await VideoThumbnail.thumbnailData(
      imageFormat: ImageFormat.JPEG,
      video: video.path,
      quality: 20,
    );

    if (thumbnail.length > ImgSizeLimit) {
      print('图片较大 ${thumbnail.length}');
      File file =await FileCacheMgr().writeFile(DateTime.now().millisecondsSinceEpoch.toString(),thumbnail);

      File compressedFile = await FlutterNativeImage.compressImage(file.path,
          quality: 30, percentage: 40);
      thumbnail =compressedFile.readAsBytesSync().toList();


//      thumbnail =  await FlutterImageCompress.compressWithList(thumbnail, quality: 10);

      print('压缩后 ${thumbnail.length}');
    }

    return thumbnail;
  }
}

Widget _buildOtherSelect(String imgPath, String title, VoidCallback onTap) {
  var imgWidth = Screen.width / 4 - 20;
  return InkWell(
    child: Container(
      width: imgWidth,
      child: Column(
        children: <Widget>[
          SizedBox(
            child: Image.asset(imgPath, fit: BoxFit.contain),
            width: 40,
            height: 40,
          ),
          SizedBox(height: 5),
          Text(title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              textScaleFactor: 1.0,
              style: TextStyle(color: Color(0xFF090909), fontSize: 12))
        ],
      ),
    ),
    onTap: onTap,
  );
}
