import 'package:chat/data/UserData.dart';
import 'package:chat/data/chat_data_mgr.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/last_chat_item.dart';
import 'package:chat/models/last_message_model.dart';
import 'package:chat/r.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/net_state_widget.dart';
import 'package:chat/utils/screen.dart';
import 'package:chat/utils/sql_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

class LastChatPage extends StatefulWidget {
  final bool needRobot;
  final int enterType; // 0默认  1图片 2转发消息
  final dynamic enterContent;
  LastChatPage({this.needRobot = true, this.enterType = 0, this.enterContent});

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

class _LastChatPageState extends State<LastChatPage> {
  @override
  void initState() {
    super.initState();

    MessageMgr().on(MessageMgr.REFRESH_PUSH_PERMISSION, requestPushPermission);
    MessageMgr().on('Update LastMsg', updateList);
  }

  @override
  void dispose() {
    MessageMgr().off(MessageMgr.REFRESH_PUSH_PERMISSION, requestPushPermission);
    MessageMgr().off('Update LastMsg', updateList);
    super.dispose();
  }

  requestPushPermission(args) async {
    print('请求推送权限');
    final PermissionStatus status = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.notification);
    print('请求推送权限--status:$status');
    if (status == PermissionStatus.denied) {
      setState(() {
        UserData().needRequestPushPermission = UserData().privatyMsgPushSwitch;
      });
    }
    if (status == PermissionStatus.granted) {
      UserData().needRequestPushPermission = false;
      if (mounted) {
        setState(() {});
      }
    }
  }

  updateList(args) {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    List<LastMessageModel> lastMsgList = ChatDataMgr().lastMsgProvider.lastMsgList;

    print('lastMsgList ${lastMsgList.length}');

    return Column(
      children: <Widget>[
        UserData().needRequestPushPermission
            ? InkWell(
                onTap: () {
                  CustomUI.buildOneConfirm(
                      context,
                      I18n.of(context).notice_open,
                      I18n.of(context).determine, () async {
                    Navigator.of(context).pop();
                    PermissionHandler().openAppSettings();
                  }, title: I18n.of(context).open_notice);
                },
                child: Container(
                  height: 25,
                  alignment: Alignment.center,
                  width: double.infinity,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        I18n.of(context).not_open,
                        textScaleFactor: 1,
                        style: TextStyle(
                            fontSize: 12.5, color: const Color(0xffab8f60)),
                      ),
                      Icon(
                        Icons.chevron_right,
                        size: 18,
                        color: const Color(0xffab8f60),
                      )
                    ],
                  ),
                  color: const Color(0xfffaefcf),
                ))
            : Container(),
        NetStateWidget(),
        widget.needRobot ? _translateRobot() : Container(),
        //_CompanyServer(),
        lastMsgList.length == 0
            ? _emptyContent()
            : _chatRecordsList(lastMsgList)
      ],
    );
  }

  Widget _translateRobot() {
    return InkWell(
        onTap: () {
          AppNavigator.pushTranslateRobotPage(context);
        },
        child: Container(
          padding: const EdgeInsets.all(10.0),
          height: 68,
          child: Row(
            children: <Widget>[
              ClipRRect(
                child: Image.asset(R.assetsImagesRobot),
                borderRadius: BorderRadius.circular(5),
              ),
              SizedBox(width: 10),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  fixedText(I18n.of(context).translate_robot,
                      fontSize: 15, fontWeight: FontWeight.w500),
                  SizedBox(height: 5),
                  Text(
                    I18n.of(context).robot_hello,
                    textScaleFactor: 1.0,
                    style: AppStyles.DescStyle,
                  ),
                ],
              )
            ],
          ),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Color(AppColors.ConversationItemBgColor),
              border: Border(bottom: Constants.GreyBorderSide)),
        ));
  }

   Widget _CompanyServer() {
    return InkWell(
        onTap: () {
          AppNavigator.pushCompanyServerPage(context);
        },
        child: Container(
          padding: const EdgeInsets.all(10.0),
          height: 68,
          child: Row(
            children: <Widget>[
              ClipRRect(
                child: Image.asset(R.assetsImagesServerIcon),
                borderRadius: BorderRadius.circular(5),
              ),
              SizedBox(width: 10),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  fixedText(I18n.of(context).feedback_assistant,
                      fontSize: 15, fontWeight: FontWeight.w500),
                  SizedBox(height: 5),
                  Text(
                    I18n.of(context).feedback_tips,
                    textScaleFactor: 1.0,
                    style: AppStyles.DescStyle,
                  ),
                ],
              )
            ],
          ),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Color(AppColors.ConversationItemBgColor),
              border: Border(bottom: Constants.GreyBorderSide)),
        ));
  }

  Widget _emptyContent() {
    return Expanded(
      child: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(bottom: 9.5, right: 11),
              child: Icon(
                IconData(
                  0xe640,
                  fontFamily: 'iconfont',
                ),
                color: Constants.LightBlueIconColor,
                size: 60,
              )),
          fixedText(I18n.of(context).no_new,
              color: Constants.OpacityBlueTextColor, fontSize: 14),
        ],
      )),
    );
  }

  Widget _chatRecordsList(lastMsgList) {
    return Expanded(
        child: Container(
            alignment: Alignment.topCenter,
            child: ListView.builder(
              shrinkWrap: true,
              itemBuilder: (BuildContext context, int index) {
                LastMessageModel msg = lastMsgList[index];
                if (msg.sessionId == 10000) {
                  return Container();
                }
                return Dismissible(
                    key: Key(msg.sessionId.toString()),
                    child: LastChatItem(
                      Key(msg.sessionId.toString()),
                      msg,
                      enterType: widget.enterType,
                      enterContent: widget.enterContent,
                    ),
                    direction: DismissDirection.endToStart,
                    background: Container(
                      color: Colors.red,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          fixedText(I18n.of(context).delete,
                              color: Colors.white),
                          Icon(
                            Icons.delete,
                            color: Colors.white,
                          )
                        ],
                      ),
                    ),
                    confirmDismiss: (direction) async {
                      var _confirmContent = I18n.of(context).confirm_delete;
                      bool isDismiss = await CustomUI.showIosDialog(
                          context, _confirmContent, () {
                        lastMsgList.removeAt(index);
                        SqlUtil.userInfoTable.deleteUser(msg.friendId);
                        ChatDataMgr().deleteMsg(msg.sessionId, false);
                        setState(() {});
                        Navigator.of(context).pop(true);
                      }, () {
                        Navigator.of(context).pop(false);
                      });

                      return isDismiss;
                    });
              },
              itemCount: lastMsgList.length,
            )));
  }
}
