import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/InformUser.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/MessageBox.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/PicSwiper.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import '../utils/HttpUtil.dart';
import 'package:dio/dio.dart';
import "../data/UserData.dart";
import '../utils/TokenMgr.dart';

class ProgramDetailPage extends StatefulWidget {
  @required
  final int programId;
  ProgramDetailPage({Key key, this.programId}) : super(key: key);

  @override
  _ProgramDetailPageState createState() => new _ProgramDetailPageState();
}

class _ProgramDetailPageState extends State<ProgramDetailPage> {
  GlobalKey<ScaffoldState> registKey = new GlobalKey();

  List fabulousList = [];
  bool isMyself = false;

  List evaluateList = [];

  List enrollList = [];

  bool showAllContent = false;

  bool isMan = false;

  bool isProgram = false;

  Map programInfo = {};

  bool isLoadingFish = false;

  bool isNonContent = false;

  bool isJoin = false;

  msgRefresh(data) {
    getData();
  }

  msgUpdateDy(data) {
    setState(() {
      isNonContent = data;
    });
  }

  @override
  void initState() {
    super.initState();
    MessageMgr().on('delete_program', msgDeleteProgram);
    MessageMgr().on('update_dy', msgUpdateDy);
    MessageMgr().on('refresh_list', msgRefreshList);
    getData();
  }

  msgRefreshList(data) {
    getData();
  }

  msgDeleteProgram(data) {
    Navigator.of(context).pop();
  }

  Future getData() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "id": widget.programId,
    };
    data['sign'] = TokenMgr().getSign(data);
    Response res = await HttpUtil().post('station/evaluate/detail',
        data: data, failback: () => Navigator.of(context).pop());
    var resData = res.data;
    print(resData);
    if (resData['code'] == 0) {
      if (resData['data']['FabulousList'] != null)
        fabulousList = resData['data']['FabulousList'];
      if (resData['data']['EvaluateList'] != null) {
        evaluateList = resData['data']['EvaluateList'];
      }
      enrollList = resData['data']['EnrollList'];
      isMyself = resData['data']['UserId'] == UserData().basicInfo.userId;
      isMan = resData['data']['Sex'] == 1;
      isProgram = resData['data']['Type'] == 0;
      programInfo = resData['data'];
      programInfo['Id'] = widget.programId;
      isNonContent = resData['data']['EvaluateStatus'] == 1;
      isJoin = resData['data']['IsEnroll'] == 1;
      isLoadingFish = true;
      setState(() {});
    } else {
      showToast(resData['msg']);
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      //backgroundColor: AppColors.NewAppbarBgColor,
      title: new Text(
        isProgram
            ? I18n.of(context).program_details
            : I18n.of(context).dynamic_details,
        textScaleFactor: 1.0,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
          elevation: 1,
      leading: CustomUI.buildCustomLeading(context),
      centerTitle: true,
    );
    var content = new Scaffold(
        key: registKey,
        appBar: appBar,
        //backgroundColor: Colors.white,
        body: SafeArea(
          child: Center(
            child: Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: _buildBody(),
            ),
          ),
        ));

    return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  Widget _buildBottomSheetItem(str, height, callback) {
    return InkWell(
      child: Container(
        height: height,
        decoration:
            BoxDecoration(border: Border(bottom: Constants.GreyBorderSide)),
        alignment: Alignment.center,
        child: Text(
          str,
          textScaleFactor: 1.0,
          style: TextStyle(fontSize: 18, color: Constants.BlackTextColor),
        ),
      ),
      onTap: callback,
    );
  }

  Widget _buildReply(data) {
    const TextColor = Constants.BlackTextColor;
    const BlueColor = Constants.GreyTextColor;
    bool isWriter =
        programInfo['UserId'] == UserData().basicInfo.userId; //是否发布者
    bool isReplyer = data['UserId'] == UserData().basicInfo.userId; //是否评论者
    replay() {
      Navigator.of(context).pop();
      CustomUI.showContentDialog(
          registKey.currentContext, programInfo['Id'], data['Pid'], 1, (data) {
        programInfo['EvaluateNum']++;
        evaluateList.add(data);
        setState(() {});
      },
          replyUserId: data['UserId'],
          replyUserName: Provider.of<RefNameProvider>(context)
              .getRefName(data['UserId'], data['NickName']),
          isMyself: isMyself);
    }

    inform() async {
      var resdata = {
        "reportuserId": UserData().basicInfo.userId,
        "userid": data['UserId'],
      };
      resdata['sign'] = TokenMgr().getSign(resdata);
      resdata['type'] = 4;
      resdata['objectId'] = data['Pid'];
      resdata['reason'] = 0;

      resdata["imgurl"] = '';
      resdata["explain"] = '';
      Response res = await HttpUtil().post('report/user/insert', data: resdata);
      Map resData = res.data;
      showToast(resData['msg']);
      if (resData['code'] == 0) {
        Navigator.of(context).pop();
      }
    }

    delete() async {
      var resdata = {
        "userId": UserData().basicInfo.userId,
        "pId": data['Pid'],
      };
      resdata['sign'] = TokenMgr().getSign(resdata);

      Response res = await HttpUtil()
          .post('station/delete/evaluate', data: resdata, isShowLoading: true);
      Map resData = res.data;
      if (resData['code'] == 0) {
        Navigator.of(context).pop();
        programInfo['EvaluateNum']--;
        getData();
      }
    }

    double fontSize = 14;

    //1.不是发布者
    //1.1是评论者则没有选项
    //1.2不是评论者则有回复和举报
    //2.是发布者
    //2.1是评论者则有删除
    //2.2不是评论者则有删除，回复和举报
    return InkWell(
        onTap: !isWriter && isReplyer
            ? null
            : () {
                double height = 50.0;
                List<Widget> list = [];
                if (!isWriter && !isReplyer)
                  list = [
                    _buildBottomSheetItem(
                        I18n.of(context).reply, height, replay),
                    _buildBottomSheetItem(
                        I18n.of(context).report, height, inform),
                  ];
                if (isWriter && isReplyer)
                  list = [
                    _buildBottomSheetItem(
                        I18n.of(context).delete, height, delete),
                  ];
                if (isWriter && !isReplyer)
                  list = [
                    _buildBottomSheetItem(
                        I18n.of(context).delete, height, delete),
                    _buildBottomSheetItem(
                        I18n.of(context).reply, height, replay),
                    _buildBottomSheetItem(
                        I18n.of(context).report, height, inform),
                  ];

                //回复不能回复自己 ，只有发布者才能删除评论
                showModalBottomSheet(
                  context: registKey.currentContext,
                  builder: (BuildContext context) {
                    return new Container(
                      height: height * list.length,
                      child: Column(
                        children: list,
                      ),
                    );
                  },
                ).then((val) {});
              },
        child: Container(
          padding: EdgeInsets.only(bottom: 3),
          child: RichText(
            text: TextSpan(
                children: data['ReplyUserId'] == 0
                    ? [
                        TextSpan(
                          text: Provider.of<RefNameProvider>(context)
                              .getRefName(data['UserId'], data['NickName']),
                          style: TextStyle(
                              fontSize: fontSize,
                              textBaseline: TextBaseline.alphabetic,
                              color: BlueColor,
                              fontWeight: FontWeight.w500),
                        ),
                        TextSpan(
                          text: '： ${data['Content']}',
                          style: TextStyle(
                              color: TextColor,
                              textBaseline: TextBaseline.alphabetic,
                              fontSize: fontSize),
                        )
                      ]
                    : [
                        TextSpan(
                          text: Provider.of<RefNameProvider>(context)
                              .getRefName(data['UserId'], data['NickName']),
                          style: TextStyle(
                              fontSize: fontSize,
                              textBaseline: TextBaseline.alphabetic,
                              color: BlueColor,
                              fontWeight: FontWeight.w500),
                        ),
                        TextSpan(
                          text: ' ${I18n.of(context).reply} ',
                          style: TextStyle(
                              fontSize: fontSize,
                              textBaseline: TextBaseline.alphabetic,
                              color: TextColor,
                              fontWeight: FontWeight.w500),
                        ),
                        TextSpan(
                          text: data['ReplyNickName'],
                          style: TextStyle(
                              fontSize: fontSize,
                              textBaseline: TextBaseline.alphabetic,
                              color: BlueColor,
                              fontWeight: FontWeight.w500),
                        ),
                        TextSpan(
                          text: '： ${data['Content']}',
                          style: TextStyle(
                              color: TextColor,
                              textBaseline: TextBaseline.alphabetic,
                              fontSize: fontSize),
                        )
                      ]),
          ),
        ));
  }

  Widget _buildJoinItem(data) {
    Widget basicInfo = Row(children: <Widget>[
      Padding(
          padding: EdgeInsets.only(left: 10, right: 5),
          child: Stack(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(right: 10),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(6.0),
                  child: CachedNetworkImage(
                    height: 45,
                    width: 45,
                    imageUrl:
                        data['Headimgurl'] == null ? "" : data['Headimgurl'],
                    placeholder: CustomUI.buildImgLoding,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Positioned(
                  right: 5,
                  bottom: 0,
                  child: Container(
                    padding: EdgeInsets.only(bottom: 1.3, left: 0.5),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(20))),
                    child: Icon(
                      IconData(
                        !isMan ? 0xe639 : 0xe638,
                        fontFamily: 'iconfont',
                      ),
                      color: !isMan
                          ? const Color(0xff0072ff)
                          : const Color(0xffff0486),
                      size: 12,
                    ),
                  ))
            ],
          )),
      Expanded(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            child: RichText(
                text: TextSpan(children: [
              TextSpan(
                  text: Provider.of<RefNameProvider>(context)
                      .getRefName(data['UserId'], data['NickName']),
                  style:
                      TextStyle(fontSize: 14, color: Constants.BlackTextColor)),
              TextSpan(
                  text: I18n.of(context).signed_up.replaceFirst('/s1', ''),
                  style:
                      TextStyle(fontSize: 13, color: Constants.GreyTextColor)),
            ])),
          ),
          Text(
            '${data['CreateTime']}',
            textScaleFactor: 1.0,
            style: TextStyle(color: Constants.LightGreyTextColor, fontSize: 12),
          ),
        ],
      )),
      InkWell(
          onTap: () {
            Navigator.of(context).push(
              new MaterialPageRoute(
                builder: (context) {
                  return InformUserPage(
                    isMan: !isMan,
                    userId: data['UserId'],
                  );
                },
              ),
            );
          },
          child: Container(
              padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
              alignment: Alignment.topRight,
              child: Text(
                I18n.of(context).report,
                textScaleFactor: 1.0,
                style: TextStyle(color: Constants.BlackTextColor),
              )))
    ]);

    Widget img = Container(
      child: Row(
        children: <Widget>[
          InkWell(
              onTap: () {
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return PicSwiper(
                          id: 0, pics: [PicSwiperItem(data['ImgUrl'], id: 0)]);
                    },
                  ),
                );
              },
              child: Container(
                  margin: EdgeInsets.only(top: 10, left: 60),
                  height: 80,
                  width: 100,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(2.0)),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: CachedNetworkImage(
                      imageUrl: data['ImgUrl'] == null ? "" : data['ImgUrl'],
                      placeholder: CustomUI.buildImgLoding,
                      fit: BoxFit.cover,
                    ),
                  ))),
          Expanded(
            child: Container(
              height: 90,
              alignment: Alignment.bottomRight,
              child: InkWell(
                child: Container(
                  margin: EdgeInsets.only(right: 10),
                  decoration: BoxDecoration(
                      color: const Color(0xFF547CFF),
                      borderRadius: BorderRadius.all(Radius.circular(5))),
                  padding:
                      EdgeInsets.only(left: 15, right: 15, top: 5, bottom: 5),
                  child: Text(
                    !isMan
                        ? I18n.of(context).talk_him
                        : I18n.of(context).contact_her,
                    textScaleFactor: 1.0,
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  ),
                ),
                onTap: () {
                  int fdId = data['UserId'];
                  int sessionId = UserData().getSessionId(fdId);

                  MsgHandler.updateActiveSesstion(sessionId);
                  AppNavigator.pushChatPage(context, fdId);
                },
              ),
            ),
          )
        ],
      ),
    );

    return Container(
        padding: EdgeInsets.only(top: 10, bottom: 10),
        decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.all(Radius.circular(10))),
        margin: EdgeInsets.only(top: 10),
        width: MediaQuery.of(context).size.width * 0.95,
        child: Column(
          children: <Widget>[basicInfo, img],
        ));
  }

  Widget _buildJoinList() {
    if (enrollList == null || enrollList.length == 0) {
      return Container();
    }
    return isMyself
        ? Container(
            child: Column(
              children: enrollList.map((data) {
                return _buildJoinItem(data);
              }).toList(),
            ),
          )
        : Container();
  }

  Widget _buildContent() {
    if (evaluateList == null || evaluateList.length == 0) {
      return Container();
    }
    const maxNum = 2;

    Widget button = InkWell(
      highlightColor: Colors.transparent,
      radius: 0,
      onTap: () {
        setState(() {
          showAllContent = !showAllContent;
        });
      },
      child: Padding(
        padding: EdgeInsets.only(top: 5, bottom: 5),
        child: Row(
          children: <Widget>[
            Text(
              !showAllContent
                  ? I18n.of(context).expand
                  : I18n.of(context).collapse,
              textScaleFactor: 1.0,
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            Icon(
              !showAllContent
                  ? Icons.keyboard_arrow_down
                  : Icons.keyboard_arrow_up,
              size: 18,
              color: Colors.grey,
            )
          ],
        ),
      ),
    );
    List<Widget> list = [];

    int showNum = evaluateList.length;
    if (evaluateList.length >= maxNum && !showAllContent) {
      showNum = maxNum;
    }

    for (int i = 0; i < showNum; i++) {
      var data = evaluateList[i];
      list.add(_buildReply(data));
    }
    if (evaluateList.length > maxNum) {
      list.add(button);
    }
    return Container(
        margin: EdgeInsets.only(left: 23, top: 10, right: 8, bottom: 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: list,
        ));
  }

  Widget _buildBody() {
    return new ListView(
      children: isLoadingFish
          ? <Widget>[
              MessageBox(isDetail: true, programInfo: programInfo),
              // _buildBigImg(programInfo),
              // _buildImgList(),
              _buildContent(),
              _buildJoinList(),
            ]
          : [],
    );
  }

  @override
  void dispose() {
    registKey = null;
    MessageMgr().off('update_dy', msgUpdateDy);
    MessageMgr().off('delete_program', msgDeleteProgram);
    MessageMgr().off('refresh_list', msgRefreshList);
    super.dispose();
  }
}
