import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/list_msg_model.dart';
import 'package:chat/r.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:url_launcher/url_launcher.dart';

class QuestionModel {
  final String question;
  final int index;

  QuestionModel({this.question, this.index});

  QuestionModel.fromJson(Map<String, dynamic> json)
      : question = json['Question'],
        index = json['Number'];
}

class ServiceMsgModel {
  final bool isMe;
  final List<String> msg;

  ServiceMsgModel({this.isMe, this.msg});
}

class   ServiceCenterPage extends StatefulWidget {
  final int questionIndex;
  ServiceCenterPage({this.questionIndex = -1});

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

class _ServiceCenterPageState extends State<ServiceCenterPage> {
  final TextEditingController _textCtrl = new TextEditingController();

  List<QuestionModel> questions = [];
  ScrollController _scrollCtrl = new ScrollController();

  ListModel<ServiceMsgModel> _list;
  GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();

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

    _list = ListModel<ServiceMsgModel>(
      listKey: _listKey,
      initialItems: [],
    );

    getAllQuestions();
  }

  @override
  void dispose() {
    _listKey = null;
    _scrollCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.NewAppbarBgColor,
        leading: CustomUI.buildCustomLeading(context),
        title: Text(
          I18n.of(context).help,
          textScaleFactor: 1.0,
          style: TextStyle(color: AppColors.NewAppbarTextColor),
        ),
        centerTitle: true,
      ),
      body: SafeArea(
          child: Column(
        children: <Widget>[
          Expanded(
              child: GestureDetector(
                  onTap: () {
                    print('隐藏FocusNode');
                    FocusScope.of(context).requestFocus(FocusNode());
                    setState(() {});
                  },
                  child: _buildMessageList())),
          _buildTextComposer(),
        ],
      )),
    );
  }

  getAllQuestions() async {
    Map data = {
      "language": UserData().language,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('message/staff/question', data: data);
    var resData = res.data;
    if (resData['code'] == 0) {
      questions = resData['data']
          .map<QuestionModel>((v) => QuestionModel.fromJson(v))
          .toList();

      String userName;
      if (UserData().isMan()) {
        userName = I18n.of(context).man_vi;
      } else {
        userName = I18n.of(context).women_vi;
      }
      var allTexts = ['$userName,${I18n.of(context).kf_tips}'];
      for (var i = 0; i < questions.length; i++) {
        allTexts.add(questions[i].question);
      }

      _list.add(ServiceMsgModel(isMe: false, msg: allTexts));

      ///自动发送提问
      if (widget.questionIndex != -1) {
        _textCtrl.text = widget.questionIndex.toString();
        sendMessage();
      }
    }
  }

  buildQuestions(msg) {
    if (questions == null) {
      return Container();
    }
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        ClipRRect(
          child: Image.asset(R.assetsImagesServiceIcon),
          borderRadius: BorderRadius.circular(8),
        ),
        SizedBox(width: 8),
        Container(
            width: Screen.width - 120,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(10)),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: msg
                    .map<Widget>((text) => Container(
                          child: Text(text,
                              textScaleFactor: 1.0,
                              style: TextStyle(fontSize: 13)),
                        ))
                    .toList()))
      ],
    );
  }

  getAnswerWith(int index) async {
    Map data = {"language": UserData().language, "number": index};
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('message/staff/answer', data: data);
    var resData = res.data;
    if (resData['code'] == 0) {
      _list.add(ServiceMsgModel(isMe: false, msg: [resData['data']]));
    } else {
      print(resData['msg']);
    }
  }

  buildAnswer(msg) {
    String answer = msg[0];
    print('anser a$answer');
    String sign = '';
    bool isHttp = answer.trim().startsWith('http');

    if (isHttp) {
      answer = I18n.of(context).service_withdraw_tips;
      Map data = {
        "userId": UserData().basicInfo.userId,
        "language": UserData().language,
      };
      sign = TokenMgr().getSign(data);
      print(
          '@@@@@@ sign $sign   ${UserData().basicInfo.userId}   ${UserData().language}');
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        ClipRRect(
          child: Image.asset(R.assetsImagesServiceIcon),
          borderRadius: BorderRadius.circular(8),
        ),
        SizedBox(width: 8),
        Container(
            width: Screen.width - 120,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(10)),
            child: isHttp
                ? Container(
                    child: Column(
                      children: <Widget>[
                        Text(answer,
                            textScaleFactor: 1.0,
                            style: TextStyle(fontSize: 13)),
                        SizedBox(
                          height: 6,
                        ),
                        GestureDetector(
                          child: Text(I18n.of(context).withdraw_tips,
                              textScaleFactor: 1.0,
                              style:
                                  TextStyle(fontSize: 13, color: Colors.blue)),
                          onTap: () async {
                            String url = msg[0] +
                                '/Bank/Getlanguage?userId=${UserData().basicInfo.userId}&language=${UserData().language}&sign=$sign';
                            print('url :$url');
                            await launch(url);
                          },
                        ),
                      ],
                    ),
                  )
                : Container(
                    child: Text(msg[0],
                        textScaleFactor: 1.0, style: TextStyle(fontSize: 13)),
                  ))
      ],
    );
  }

  _buildMessageList() {
    return AnimatedList(
      key: _listKey,
      initialItemCount: _list.length,
      controller: _scrollCtrl,
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 10),
      itemBuilder: _buildItem,
    );
  }

  Widget _buildItem(
      BuildContext context, int index, Animation<double> animation) {
    ServiceMsgModel msg = _list[index];

    Widget item;
    if (index == 0) {
      item = buildQuestions(msg.msg);
    } else {
      if (msg.isMe) {
        item = buildSendMsg(msg.msg.first);
      } else {
        item = buildAnswer(msg.msg);
      }
    }

    return SizeTransition(
        sizeFactor:
            CurvedAnimation(parent: animation, curve: Curves.decelerate),
        axisAlignment: -2,
        child: Padding(padding: EdgeInsets.only(bottom: 10), child: item));
  }

  Future<Null> _textMessageSubmitted(String text) async {
    sendMessage();
  }

  buildSendMsg(msg) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          constraints: BoxConstraints(maxWidth: Screen.width - 120),
          child: Text(msg,
              textScaleFactor: 1.0, style: TextStyle(color: Colors.white)),
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
          decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                    color: Colors.blue[200],
                    offset: Offset(0, 2),
                    blurRadius: 3.0),
              ],
              color: Color(0xFF377dfe),
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(15),
                topLeft: Radius.circular(15),
                bottomRight: Radius.circular(15),
              )),
        ),
        SizedBox(width: 5),
        Container(
            width: 40,
            height: 40,
            child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: CachedNetworkImage(
                  imageUrl: UserData().basicInfo.headimgurl,
                  placeholder: (context, url) =>
                      Image.asset(R.assetsImagesDefaultNorAvatar),
                ))),
      ],
    );
  }

  sendMessage() {
    var text = _textCtrl.text;
    if (text.length > 0) {
      int index = int.parse(text);

      if (index > 0 && index <= questions.length) {
        _list.add(ServiceMsgModel(isMe: true, msg: [text]));

        getAnswerWith(index);

        _textCtrl.clear();
      } else {
        showToast(I18n.of(context).reinput);
      }
    }
  }

  _buildTextComposer() {
    return Container(
      alignment: Alignment.center,
      width: Screen.width,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              child: TextField(
                keyboardAppearance: Brightness.light,
                onSubmitted: _textMessageSubmitted,
                controller: _textCtrl,
                keyboardType: TextInputType.number,
                cursorColor: Color.fromARGB(255, 0, 189, 96),
                style: TextStyle(
                    fontSize: fixedFontSize(15),
                    textBaseline: TextBaseline.alphabetic),
              ),
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(10),
              ),
            ),
          ),
          SizedBox(width: 5),
          SizedBox(
              child: OutlineButton(
            child: Text(I18n.of(context).send, textScaleFactor: 1.0),
            onPressed: sendMessage,
          ))
        ],
      ),
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(8), topRight: Radius.circular(8)),
      ),
    );
  }
}
