import 'package:flutter/material.dart';
import 'package:liftmanager/res/gaps.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/selected_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'dart:io';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:convert';
import 'package:liftmanager/utils/url.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/internal/bbs/model/question_detail.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'dart:math';
import 'package:liftmanager/widgets/preview_images.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/common/common.dart';

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

  final String id;

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

class QuestionDetailState extends State<QuestionDetail> {
  @override
  void initState() {
    super.initState();
    getQuestionDetail();

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

  bool _hasData = false;
  QuestionDetailModel detailObj;
  List<String> listPreview = [];
  Future getQuestionDetail() async {
    await NewApiService().getQuestionDetail(int.parse(widget.id),
        onSuccess: (res) {
          // print(jsonEncode(res));
          // print(123456);
      if (res != null) {
        _hasData = true;
        detailObj = res;
        setState(() {
          
        });
        listPreview = [];
                                                        
                                                        detailObj.imgs.split(",").forEach((element) {
                                                          listPreview.add(Utils.getImagePath(element,isWater: true));
                                                        });
                                                        
        // print(123456);
        // print(jsonEncode(res));
        // print(jsonEncode(detailObj.title));
        // print(1234563333);
        
      }
    }, 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;

    return Scaffold(
      resizeToAvoidBottomPadding: false, //不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "问题详情",
      ),
      body: _hasData?Stack(
              children: <Widget>[
                Container(
                    child: ListView(children: <Widget>[
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        width: width,
                        padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                            top: ScreenUtil().setWidth(10),
                            bottom: ScreenUtil().setWidth(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: ScreenUtil().setSp(16)),
                                textAlign: TextAlign.start,
                                maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text(
                                    detailObj.brandName??"",
                                    style: TextStyle(
                                        color: Color(0xff666666),
                                        fontSize: ScreenUtil().setSp(14)),
                                    textAlign: TextAlign.start,
                                  ),
                                  Row(
                                      children: <Widget>[
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(
                                              "${detailObj.likeNum??"0"}",
                                              style: TextStyle(
                                                  color: Color(0xff999999),
                                                  fontSize: ScreenUtil().setSp(14)),
                                              textAlign: TextAlign.start,
                                            ),
                                            SizedBox(
                                              width:3
                                            ),
                                            Icon(
                                              IconData(0xe7cd,
                                                  fontFamily: "myfont"),
                                              size: 14.0,
                                              color: Color(0xff999999),
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          width:15
                                        ),
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(
                                              "${detailObj.browseNum??"0"}",
                                              style: TextStyle(
                                                  color: Color(0xff999999),
                                                  fontSize: ScreenUtil().setSp(14)),
                                              textAlign: TextAlign.start,
                                            ),
                                            SizedBox(
                                              width:3
                                            ),
                                            Icon(
                                              IconData(0xe610,
                                                  fontFamily: "myfont"),
                                              size: 14.0,
                                              color: Color(0xff999999),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                ],
                              )
                            ]),
                      ),
                      Container(
                        padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(15),
                            top: ScreenUtil().setWidth(30),
                            bottom: ScreenUtil().setWidth(30)),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(width: 0.5, color: Colours.line),
                          ),
                        ),
                        child: Row(
                          children: <Widget>[
                            Container(
                                child: ClipRRect(
                              borderRadius: BorderRadius.circular(
                                  ScreenUtil().setWidth(18)),
                              child: LoadNetworkImage(
                                detailObj.avatarUrl,
                                // fit: BoxFit.cover,
                                width: ScreenUtil().setWidth(36),
                                height: ScreenUtil().setWidth(36),
                                
                              ),
                            )),
                            Container(
                              padding: EdgeInsets.only(left: 5),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(
                                    detailObj.userName??"",
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(14),
                                        ),
                                  ),
                                  Text(
                                    DateUtils.instance.getFormartData(
                                        timeSamp: detailObj.createTime,
                                        format: "yyyy-MM-dd"),
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(12),
                                        color: Color(0xffaaaaaa)),
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                top: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setWidth(5)),
                            child: Text(
                              "问题描述",
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(16),
                              ),
                              textAlign: TextAlign.left,
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                top: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setWidth(50)),
                            child: Text(
                              detailObj.expression??"",
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(14),
                              ),
                              textAlign: TextAlign.left,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 6,
                        child: Container(color: ThemeUtils.getDialogTextFieldColor(context)),
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                top: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setWidth(5)),
                            child: Text(
                              "解决方法",
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(16),
                              ),
                              textAlign: TextAlign.left,
                            ),
                          ),
                          detailObj.isTip==1?Container(
                            padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15),
                                right: ScreenUtil().setWidth(15),
                                top: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setWidth(50)),
                            child: Text(
                              detailObj.solution??"",
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(14),
                              ),
                              textAlign: TextAlign.left,
                            ),
                          ):Container(
                            padding: EdgeInsets.only(left: ScreenUtil().setWidth(15),bottom: ScreenUtil().setWidth(20)),
                            child:Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                ClipRRect(
                                borderRadius: BorderRadius.circular(20),
                                child: Container(
                                  padding: EdgeInsets.only(left:10,right:10,top:2,bottom:5),
                                  color: Color(0xffffae01),
                                  child: Text(
                                  "打赏后可查看全部",
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(14),
                                    color: Colors.white
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                                  
                                )
                                
                              )
                              ],
                            )
                            
                          ),
                        ],
                      ),
                      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>[]
                        )):Container(child:null),
                      SizedBox(
                        height: 70,
                      ),
                    ],
                  ),
                ])),
                Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                        width: width,
                        child: Row(children: <Widget>[
                          Container(
                              height: ScreenUtil().setWidth(70),
                              width: width / 2,
                              color: Colors.white,
                              padding: EdgeInsets.only(
                                  // left: ScreenUtil().setWidth(10),
                                  // right: ScreenUtil().setWidth(10),
                                  top: ScreenUtil().setWidth(10)),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.center,
                                children: <Widget>[
                                  Container(
                                    width: 1/4*width,
                                    
                                    child: GestureDetector(
                                      onTap: () {
                                      if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
                                        showAlertEvent();
                                      }else {
                                        if (detailObj.isLike == 1) {
                                          // cancelLike(2);
                                          cancelLike();
                                        } else {
                                          // changeLike(2);
                                          changeLike();
                                        }
                                      }
                                      
                                    },
                                      child: Row(
                                        children: <Widget>[
                                          Column(children: <Widget>[
                                    Icon(
                                      IconData(
                                          detailObj.isLike == 1
                                              ? 0xe63c
                                              : 0xe608,
                                          fontFamily: "myfont"),
                                      size: 26.0,
                                      color: Color(detailObj.isLike == 1
                                          ? 0xff0388FD
                                          : 0xff333333),
                                    ),
                                    Text(
                                      detailObj.isLike == 1 ? "已点赞" : "点赞",
                                      style: TextStyle(
                                          color: Color(detailObj.isLike == 1
                                              ? 0xff0388FD
                                              : 0xff000000),
                                          fontSize: ScreenUtil().setSp(14)),
                                      textAlign: TextAlign.start,
                                    ),
                                  ])
                                        ],
                                      )
                                  ),
                                  ),
                                  
                                  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(children: <Widget>[
                                    Icon(
                                        IconData(
                                            detailObj.isFavorite == 1
                                                ? 0xe654
                                                : 0xe604,
                                            fontFamily: "myfont"),
                                        size: 26.0,
                                        color: Color(detailObj.isFavorite == 1
                                            ? 0xff0388FD
                                            : 0xff333333),
                                      ),
                                      Text(
                                        detailObj.isFavorite == 1
                                            ? "已收藏"
                                            : "收藏",
                                        style: TextStyle(
                                            color: Color(
                                                detailObj.isFavorite == 1
                                                    ? 0xff0388FD
                                                    : 0xff000000),
                                            fontSize: ScreenUtil().setSp(14)),
                                        textAlign: TextAlign.start,
                                      ),
                                  ])),
                                  ),
                                ],
                              )),
                          Container(
                            height: ScreenUtil().setWidth(70),
                            width: width / 2,
                            color: Color(0xff0388FD),
                            child: FlatButton(
                              // padding: EdgeInsets.all(15.0),
                              child: Text(
                                "打赏",
                                style:
                                    TextStyle(fontSize: ScreenUtil().setSp(16)),
                              ),
                              textColor: Colors.white,
                              onPressed: () {
                                if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
                                        showAlertEvent();
                                      }else {
                                        NavigatorUtils.push(
                                    context, "${BbsRouter.questionPay}?id=${detailObj.id}&type=question&name=${Uri.encodeComponent(detailObj.userName)}");
                                      }
                                
                              },
                            ),
                          ),
                        ])))
              ],
            )
          : 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,
          ),
        );
}