import 'dart:math';

import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/bbs/model/question_detail.dart';
import 'package:liftmanager/internal/bbs/page/tab/question/question_pay.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/iconfont.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/preview_images.dart';

class QuestionDetail extends StatefulWidget {
  QuestionDetail(this.id);

  final String id;

  @override
  State<StatefulWidget> createState() {
    return QuestionDetailState();
  }
}

class QuestionDetailState extends State<QuestionDetail> {
  bool _hasData = false;
  QuestionDetailModel detailObj;
  List<String> listPreview = [];
  double vipPrice;

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

    FastNotification.addListener("initIsPay", (initThisUserMoney) {
      if (mounted) {
        getQuestionDetail();
        setState(() {});
      }
    });
  }

  Future getQuestionDetail() async {
    await NewApiService().getQuestionDetail(int.parse(widget.id),
        onSuccess: (res) {
      if (res != null) {
        _hasData = true;
        detailObj = res;

        listPreview = [];
        setState(() {});
        detailObj.imgs?.split(",")?.forEach((element) {
          listPreview.add(Utils.getImagePath(element, isWater: true));
        });
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  void getVipPrice() {
    NewApiService().getVipFeeList('1', onSuccess: (res) {
      setState(() {
        vipPrice = res.records[0].price;
      });
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  showAlertEvent() {
    showAlert(
      context,
      "提示",
      "确定登录？",
      "确定",
      () {
        NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
      },
      txt2: "取消",
      onPre2: () {
        NavigatorUtils.goBack(context);
      },
    );
  }

  Future changeLike() async {
    await NewApiService().questionLike(detailObj.id, 1, onSuccess: (res) {
      toasts("点赞成功");
      getQuestionDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future changeFav() async {
    await NewApiService().questionFav(detailObj.id, 1, onSuccess: (res) {
      toasts("收藏成功");
      initCollect();
      getQuestionDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future cancelLike() async {
    await NewApiService().questionLikeCancel(detailObj.id, 1, onSuccess: (res) {
      toasts("取消点赞成功");
      getQuestionDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future cancelFav() async {
    await NewApiService().questionFavCancel(detailObj.id, 1, onSuccess: (res) {
      toasts("取消收藏成功");
      initCollect();
      getQuestionDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  initCollect() {
    String collectInit = randomInt(1111, 9999).toString() +
        DateTime.now().millisecondsSinceEpoch.toString();
    FastNotification.push("collectAction", collectInit);
  }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    _clipText({title, bgcolor, textcolor}) {
      return ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(3)),
        child: Container(
          padding: EdgeInsets.only(left: 5, right: 5, top: 2, bottom: 2),
          color: bgcolor,
          alignment: Alignment.center,
          // color: Color(0xFD5D61),
          child: Text(
            title,
            style: TextStyle(fontSize: 11, color: textcolor),
          ),
        ),
      );
    }

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "案例详情",
      ),
      body: _hasData
          ? Stack(
              children: <Widget>[
                Container(
                    child: ListView(
                        physics: detailObj.isTip != 1
                            ? const NeverScrollableScrollPhysics()
                            : null,
                        children: <Widget>[
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            width: width,
                            padding: EdgeInsets.symmetric(
                                horizontal: 10, vertical: 10),
                            decoration: BoxDecoration(
                              border: Border(
                                bottom:
                                    BorderSide(width: 0.5, color: Colours.line),
                              ),
                            ),
                            child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    detailObj.title ?? "",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      color: Color(0xff333333),
                                    ),
                                    textAlign: TextAlign.start,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Row(
                                    children: [
                                      _clipText(
                                          title: detailObj.brandName ?? "",
                                          bgcolor:
                                              Color.fromRGBO(67, 141, 250, .16),
                                          textcolor: Color(0xFF5887FF)),
                                      Expanded(child: Container()),
                                      Text(
                                        "${detailObj.browseNum ?? "0"}浏览·${detailObj.likeNum ?? "0"}赞",
                                        textAlign: TextAlign.right,
                                        style: TextStyle(
                                          color: Color(0xFFCCCCCC),
                                          fontSize: 11,
                                        ),
                                      )
                                    ],
                                  ),
                                ]),
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 10, vertical: 10),
                            child: Row(
                              children: <Widget>[
                                Container(
                                    child: ClipRRect(
                                  borderRadius: BorderRadius.circular(16),
                                  child: LoadNetworkImage(
                                    detailObj.avatarUrl,
                                    // fit: BoxFit.cover,
                                    width: 32,
                                    height: 32,
                                  ),
                                )),
                                Container(
                                  padding: EdgeInsets.only(left: 5),
                                  child: Row(
                                    // crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        detailObj.userName ?? "",
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xff555A64),
                                        ),
                                      ),
                                      SizedBox(
                                        width: 5,
                                      ),
                                      _clipText(
                                          title: 'lv1',
                                          bgcolor:
                                              Color.fromRGBO(253, 93, 97, 1),
                                          textcolor: Colors.white),
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 10),
                            child: Text(
                              '${DateUtils().getFormartData(timeSamp: detailObj.createTime, format: 'yyyy-MM-dd HH:mm:ss')} 发布',
                              style: TextStyle(
                                  fontSize: 12, color: Color(0xff989898)),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Divider(
                            thickness: 0.5,
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: [
                                  Container(
                                    width: ScreenUtil().setWidth(2),
                                    height: ScreenUtil().setHeight(13),
                                    color: Color(0xFF568AFF),
                                  ),
                                  Container(
                                    padding: EdgeInsets.only(
                                        left: ScreenUtil().setWidth(10),
                                        top: ScreenUtil().setHeight(6),
                                        bottom: ScreenUtil().setWidth(5)),
                                    child: Text(
                                      "问题描述",
                                      style: TextStyle(
                                        fontSize: 15,
                                        color: Color(0xff333333),
                                      ),
                                      textAlign: TextAlign.left,
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 10),
                                child: Text(
                                  detailObj.expression ?? "",
                                  style: TextStyle(
                                    fontSize: 13,
                                    color: Color(0xff333333),
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 6,
                            child: Container(
                                color: ThemeUtils.getDialogTextFieldColor(
                                    context)),
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: [
                                  Container(
                                    // margin: EdgeInsets.only(
                                    // top: ScreenUtil().setHeight(10)),
                                    width: ScreenUtil().setWidth(2),
                                    height: ScreenUtil().setHeight(13),
                                    color: Color(0xFF568AFF),
                                  ),
                                  Container(
                                    padding: EdgeInsets.only(
                                        left: ScreenUtil().setWidth(10),
                                        top: ScreenUtil().setHeight(6),
                                        bottom: ScreenUtil().setWidth(5)),
                                    child: Text(
                                      "解决方法",
                                      style: TextStyle(
                                        fontSize: 15,
                                        color: Color(0xff333333),
                                      ),
                                      textAlign: TextAlign.left,
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 10),
                                child: Text(
                                  detailObj.solution ?? "",
                                  style: TextStyle(
                                    fontSize: 13,
                                    color: Color(detailObj.isTip != 1
                                        ? 0x0c333333
                                        : 0xff333333),
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                              )
                            ],
                          ),
                          if (detailObj.isTip == 1)
                            Container(
                                padding: EdgeInsets.only(
                                    top: ScreenUtil().setWidth(5),
                                    left: ScreenUtil().setWidth(15),
                                    right: ScreenUtil().setWidth(15)),
                                child: Wrap(
                                    spacing: 6,
                                    alignment: WrapAlignment.spaceBetween,
                                    crossAxisAlignment:
                                        WrapCrossAlignment.center,
                                    children: detailObj.imgs != null &&
                                            detailObj.imgs.isNotEmpty
                                        ? List<Widget>.from(detailObj.imgs
                                            .split(",")
                                            .asMap()
                                            .keys
                                            .map((subindex) {
                                            // print(item);
                                            return Container(
                                              padding: subindex <
                                                      detailObj.imgs
                                                              .split(",")
                                                              .length -
                                                          1
                                                  ? EdgeInsets.only(right: 6)
                                                  : EdgeInsets.only(right: 0),
                                              // color:Colors.red,
                                              // decoration: BoxDecoration(
                                              //   borderRadius: BorderRadius.circular(20.0),
                                              // ),
                                              child: GestureDetector(
                                                onTap: () {
                                                  Navigator.of(context).push(
                                                    new FadeRoute(
                                                      page:
                                                          PhotoViewGalleryScreen(
                                                        images:
                                                            listPreview, //传入图片list
                                                        index:
                                                            subindex, //传入当前点击的图片的index
                                                        // heroTag: img,//传入当前点击的图片的hero tag （可选）
                                                      ),
                                                    ),
                                                  );
                                                },
                                                child: ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(10),
                                                  child: LoadNetworkImage(
                                                    detailObj.imgs
                                                        .split(",")[subindex],
                                                    // height: width/375*75,
                                                    height: ScreenUtil()
                                                        .setWidth(80),
                                                    width: ScreenUtil()
                                                        .setWidth(80),
                                                    isWater: true,
                                                  ),
                                                ),
                                              ),
                                            );
                                          }).toList())
                                        : <Widget>[])),
                          SizedBox(
                            height: 70,
                          ),
                        ],
                      ),
                    ])),
                if (detailObj.isTip != 1)
                  Positioned(
                    bottom: ScreenUtil().setHeight(50),
                    left: 0,
                    height: ScreenUtil().setHeight(260),
                    width: width,
                    child: InkWell(
                      child: Container(
                          // color: Colors.red,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                                colors: [
                                  Color(0x66FFFFFF),
                                  Color(0xFFFFFFFF),
                                ],
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Stack(
                                overflow: Overflow.visible,
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      NavigatorUtils.push(
                                          context, '${WodeRouter.vip}?id=');
                                    },
                                    child: Container(
                                      width: 50,
                                      height: 50,
                                      decoration: BoxDecoration(
                                        gradient: LinearGradient(colors: [
                                          Color(0xffE6C8A0),
                                          Color(0xffDCB885)
                                        ]),
                                        borderRadius: BorderRadius.circular(25),
                                      ),
                                      child: Icon(
                                        Iconfont.huiyuan101,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                  Positioned(
                                    top: 0,
                                    left: 30,
                                    child: Container(
                                      padding: EdgeInsets.all(2),
                                      color: Color(0xffF95046),
                                      child: Text(
                                        '最低仅需${vipPrice}元/月',
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 9),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              Text(
                                '立即成为会员，查看更多内容',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Color(0xff333333),
                                ),
                              )
                            ],
                          )),
                    ),
                  ),
                Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                        height: ScreenUtil().setHeight(50),
                        color: Colors.white,
                        width: width,
                        child: Row(children: <Widget>[
                          Container(
                            width: 60,
                            child: GestureDetector(
                                onTap: () {
                                  if (FlutterStars.SpUtil.getString(
                                          Constant.userId) ==
                                      "-1") {
                                    showAlertEvent();
                                  } else {
                                    if (detailObj.isLike == 1) {
                                      // cancelLike(2);
                                      cancelLike();
                                    } else {
                                      // changeLike(2);
                                      changeLike();
                                    }
                                  }
                                },
                                child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      Icon(
                                        // &#xe610;
                                        // : 0xe608,
                                        // &#xe6f8;
                                        detailObj.isLike == 1
                                            ? const IconData(0xe610,
                                                fontFamily: "Iconfont")
                                            : const IconData(0xe6f8,
                                                fontFamily: "Iconfont"),
                                        size: 20,
                                        color: Color(detailObj.isLike == 1
                                            ? 0xff5589FF
                                            : 0xff555A64),
                                      ),
                                      Text(
                                        detailObj.isLike == 1 ? "已点赞" : "点赞",
                                        style: TextStyle(
                                            color: Color(detailObj.isLike == 1
                                                ? 0xff5589FF
                                                : 0xff555A64),
                                            fontSize: 12),
                                        textAlign: TextAlign.start,
                                      ),
                                    ])),
                          ),
                          Container(
                            width: 60,
                            child: GestureDetector(
                              onTap: () {
                                if (FlutterStars.SpUtil.getString(
                                        Constant.userId) ==
                                    "-1") {
                                  showAlertEvent();
                                } else {
                                  if (detailObj.isFavorite == 1) {
                                    // cancelLike(3);
                                    cancelFav();
                                  } else {
                                    // changeLike(3);
                                    changeFav();
                                  }
                                }
                              },
                              child: Container(
                                  child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: <Widget>[
                                    Icon(
                                      // : 0xe604,
                                      detailObj.isFavorite == 1
                                          ? const IconData(0xe62a,
                                              fontFamily: "Iconfont")
                                          : const IconData(0xe6b7,
                                              fontFamily: "Iconfont"),
                                      size: 20,
                                      color: Color(detailObj.isFavorite == 1
                                          ? 0xff5589FF
                                          : 0xff555a64),
                                    ),
                                    Text(
                                      detailObj.isFavorite == 1 ? "已收藏" : "收藏",
                                      style: TextStyle(
                                        color: Color(detailObj.isFavorite == 1
                                            ? 0xff5589FF
                                            : 0xff555A64),
                                        fontSize: 12,
                                      ),
                                      textAlign: TextAlign.start,
                                    ),
                                  ])),
                            ),
                          ),
                          Expanded(
                              child: ClipRRect(
                            borderRadius: BorderRadius.circular(22),
                            child: Container(
                              height: 44,
                              // width: width / 2,
                              color: Color(0xff5589FF),
                              child: FlatButton(
                                // padding: EdgeInsets.all(15.0),
                                child: RichText(
                                  text: TextSpan(
                                      text: '打赏',
                                      style: TextStyle(
                                          fontSize: 16.0,
                                          fontWeight: FontWeight.w500),
                                      children: <TextSpan>[
                                        TextSpan(
                                            text: '（可查看全部内容）',
                                            style: TextStyle(
                                              fontSize: 11.0,
                                            )),
                                      ]),
                                ),
                                textColor: Colors.white,
                                onPressed: () {
                                  if (FlutterStars.SpUtil.getString(
                                          Constant.userId) ==
                                      "-1") {
                                    showAlertEvent();
                                  } else {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => QuestionPay(
                                                  detailObj.id.toString(),
                                                  "question",
                                                  detailObj.userName,
                                                  detailObj.avatarUrl,
                                                  expert: detailObj.expert
                                                      .toString(),
                                                )));

                                    // NavigatorUtils.push(context,
                                    //     "${BbsRouter.questionPay}?id=${detailObj.id}&userModel=${[detailObj.avatarUrl]}&type=question&name=${Uri.encodeComponent(detailObj.userName)}");
                                  }
                                },
                              ),
                            ),
                          )),
                          SizedBox(
                            width: 10,
                          )
                        ])))
              ],
            )
          : Center(
              child: Text("正在加载..."),
            ),
    );
  }
}

class FadeRoute extends PageRouteBuilder {
  final Widget page;

  FadeRoute({this.page})
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              page,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
}
