import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/community/photo_view_gallery_screen.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/comunity_comment.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/border_text.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/icon_text.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class CommunityList extends StatefulWidget {
  final List<ComunityComment> comments;
  final String userId;
  final int commentType;
  final bool isList;
  final Function exitFull;
  final Function removalDynamic;

  CommunityList(this.comments, this.userId, this.commentType,
      {this.isList = false, this.exitFull, this.removalDynamic});

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

class _CommunityList extends State<CommunityList> {
  ApiService apiService;

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

    SharedPreferences.getInstance().then((value) => {
          apiService = ApiService(Dio(),
              context: context, token: value.getString("token")),
        });
  }

  ///关注/取关会员
  _vipFollow(followId, isFollow) async {
    BaseData baseData = await apiService.follow(followId);
    if (baseData != null && baseData.isSuccess) {
      widget.exitFull();
      SmartDialog.showToast(isFollow ? "关注成功" : "取关成功",
          alignment: Alignment.center);
      setState(() {});
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  ///删除动态
  _deleteDynamic(id) async {
    BaseData baseData = await apiService.deleteTrend(id);
    if (baseData != null && baseData.isSuccess) {
      widget.exitFull();
      SmartDialog.showToast("删除成功", alignment: Alignment.center);
      setState(() {});
    } else {
      // SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        (widget.comments == null || widget.comments.length == 0)
            ? NoDataView(
                src: widget.commentType == 1
                    ? "assets/image/dong_tai.webp"
                    : "assets/image/guan_zhu.webp",
                isShowBtn: false,
                text: widget.commentType == 1
                    ? "目前暂无发布动态,要把开心的事讲出来哦~"
                    : "目前暂无添加关注,可在推荐中关注自己喜欢的人哦~",
                fontSize: 16.sp,
                margin: EdgeInsets.only(top: 120.h, left: 60.w, right: 60.w),
              )
            : ListView.builder(
                padding: EdgeInsets.zero,
                itemCount: widget.comments.length,
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (context, position) {
                  return GestureDetector(
                    onTap: () {
                      Navigator.of(context).pushNamed(
                          '/router/new_community_details',
                          arguments: {
                            "commentsId": widget.comments[position].id,
                            "userId": widget.userId,
                            // exitFull: () {
                            //   setState(() {});
                            // },
                          }).then((value) {
                        widget.exitFull();
                        setState(() {});
                      });
                      setState(() {});
                    },
                    child: communityItem(widget.comments[position], position),
                  );
                },
              ),
      ],
    ));
  }

  ///动态内容
  Widget buildMedia(SubjectInfo subjectInfo, position) {
    if (subjectInfo == null) {
      return Container();
    }
    Widget itemWidget = Container();
    if (subjectInfo.type == "image" && subjectInfo.images.length > 0) {
      if (subjectInfo.images.length == 1) {
        itemWidget = Container(
          child: InkWell(
              onTap: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => PhotoViewGalleryScreen(
                              images: subjectInfo.images, //传入图片list
                              index: 0, //传入当前点击的图片的index
                            )));
              },
              child: MImage(
                subjectInfo.images[0],
                fit: BoxFit.contain,
                radius: BorderRadius.circular(2),
                width: MediaQuery.of(context).size.width / 1.5,
                height: MediaQuery.of(context).size.width / 1.5,
                errorSrc: "assets/image/default_2_1.webp",
                fadeSrc: "assets/image/default_2_1.webp",
              )),
        );
      } else {
        itemWidget = GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: (subjectInfo.images.length == 2 ||
                    subjectInfo.images.length == 4)
                ? 2
                : 3,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.w,
            childAspectRatio: 1,
          ),
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, position) {
            return Container(
              child: InkWell(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => PhotoViewGalleryScreen(
                                images: subjectInfo.images, //传入图片list
                                index: position, //传入当前点击的图片的index
                              )));
                },
                child: MImage(
                  subjectInfo.images[position],
                  fit: BoxFit.cover,
                  aspectRatio: 1,
                  radius: BorderRadius.circular(1),
                  errorSrc: "assets/image/default_2_1.webp",
                  fadeSrc: "assets/image/default_2_1.webp",
                ),
              ),
            );
          },
          itemCount: subjectInfo.images.length,
        );
      }
    } else if (subjectInfo.type == "video" && subjectInfo.video.isNotEmpty) {
      itemWidget = Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.width / 7 * 5,
        color: Colors.black,
        child: Stack(
          children: [
            Container(
              width: double.infinity,
              height: double.infinity,
              child: MImage(
                subjectInfo.video.replaceAll(".mp4", "_poster.jpg"),
                fit: BoxFit.cover,
                radius: BorderRadius.circular(2),
                errorSrc: "assets/image/default_2_1.webp",
                fadeSrc: "assets/image/default_2_1.webp",
              ),
            ),
            Center(
              child: Icon(
                Icons.play_circle_outline,
                color: Colors.white,
                size: 60,
              ),
            ),
          ],
        ),
      );
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 16.h,
        ),
        itemWidget,
      ],
    );
  }

  Widget communityItem(ComunityComment comments, position) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16),
      margin: EdgeInsets.only(bottom: 12),
      color: Colors.white,
      child: Column(
        children: [
          Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      height: 44,
                      child: Row(
                        children: [
                          GestureDetector(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) =>
                                        PhotoViewGalleryScreen(
                                      images: [
                                        (comments?.memberInfo?.avatar ?? "")
                                                .isEmpty
                                            ? "https://lmg.jj20.com/up/allimg/tx30/09041130358711081.jpg"
                                            : comments?.memberInfo?.avatar
                                      ], //传入图片list
                                      index: 0, //传入当前点击的图片的index
                                    ),
                                  ));
                            },
                            child: MImage(
                              (comments?.memberInfo?.avatar ??
                                  "https://lmg.jj20.com/up/allimg/tx30/09041130358711081.jpg"),
                              width: 44,
                              height: 44,
                              isCircle: true,
                              fit: BoxFit.cover,
                              errorSrc: "assets/image/default_1.webp",
                              fadeSrc: "assets/image/default_1.webp",
                            ),
                          ),
                          SizedBox(
                            width: 8,
                          ),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                comments?.memberInfo?.nickname ?? "",
                                style: TextStyle(
                                  fontSize: 15.sp,
                                  fontWeight: MyFontWeight.semi_bold,
                                  color: Color(0xFF1A1A1A),
                                ),
                              ),
                              Text(
                                comments?.createTime ?? "",
                                style: TextStyle(
                                  fontSize: 13.sp,
                                  fontWeight: MyFontWeight.regular,
                                  color: Color(0xFF808080),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    if ((comments?.memberInfo?.mid ?? "") != (widget.userId))
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            if (widget.commentType == 0) {
                              comments.selfFollow =
                                  !(comments.selfFollow ?? false);
                              _vipFollow(comments?.memberInfo?.mid,
                                  comments?.selfFollow ?? false);
                            } else {
                              showDeleteDialog(position);
                            }
                          });
                        },
                        child: (widget.commentType == 0)
                            ? Container(
                                width: 56.w,
                                height: 25.h,
                                alignment: Alignment.center,
                                child: RoundButton(
                                  height: 25.h,
                                  backgroup: (comments?.selfFollow ?? false)
                                      ? Color(0xFFE6E6E6)
                                      : Color(0xFF32A060),
                                  textColor: (comments?.selfFollow ?? false)
                                      ? Color(0xFF808080)
                                      : Colors.white,
                                  text: (comments?.selfFollow ?? false)
                                      ? S.of(context).yiguanzhu
                                      : S.of(context).guanzhu,
                                  radius: 20,
                                  icons: Icon(
                                    (comments?.selfFollow ?? false)
                                        ? Icons.check
                                        : Icons.add,
                                    color: (comments?.selfFollow ?? false)
                                        ? Color(0xFF808080)
                                        : Colors.white,
                                    size: 15,
                                  ),
                                ))
                            : Padding(
                                padding: EdgeInsets.all(20),
                                child: Icon(
                                  Icons.close,
                                  color: Colors.black,
                                  size: 16,
                                ),
                              ),
                      ),
                  ],
                ),
                SizedBox(
                  height: 12.h,
                ),
                Text(
                  comments.subject ?? "",
                  maxLines: 10,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Color(0xFF1A1A1A),
                    fontWeight: MyFontWeight.regular,
                    fontSize: 15.sp,
                  ),
                ),
                buildMedia(comments?.subjectInfo, position),
                // if (!widget.isDetails)
                SizedBox(
                  height: 12.h,
                ),
                // if (!comments.isDetails)
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    IconText(
                      "${comments?.viewers ?? ""}",
                      space: 4.w,
                      leftImage: "assets/svg/liulanliang.svg",
                      iconSize: 16,
                      textStyle: TextStyle(
                        fontSize: 14.sp,
                      ),
                    ),
                    IconText(
                      "${comments.comments ?? 0}",
                      space: 4.w,
                      leftImage: "assets/svg/pinglun.svg",
                      iconSize: 16,
                      textStyle: TextStyle(
                        fontSize: 14.sp,
                      ),
                    ),
                    GestureDetector(
                      onTap: () {},
                      child: IconText(
                        "${comments.likes ?? 0}",
                        space: 4.w,
                        leftImage: "assets/svg/xihuan.svg",
                        iconSize: 16,
                        textStyle: TextStyle(
                          fontSize: 14.sp,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///删除动态弹窗
  showDeleteDialog(index) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Container(
            width: MediaQuery.of(context).size.width - 84,
            height: 130.h,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  S.of(context).quedingyaoshanchudongtai,
                  style: TextStyle(
                    fontSize: 17.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                SizedBox(
                  height: 30.h,
                ),
                Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        child: BorderText(
                          text: S.of(context).quxiao,
                          textColor: Color(0xFF32A060),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                          borderColor: Color(0xFF32A060),
                          radius: 4,
                          padding: EdgeInsets.all(12),
                          borderWidth: 1,
                        ),
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      flex: 1,
                    ),
                    SizedBox(
                      width: 16.w,
                    ),
                    Expanded(
                      child: InkWell(
                        child: RoundButton(
                          text: S.of(context).queding,
                          textColor: Colors.white,
                          radius: 4,
                          padding: EdgeInsets.all(12),
                          backgroup: Color(0xFF32A060),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                        onTap: () {
                          _deleteDynamic(widget.comments[index].id);
                          Navigator.of(context).pop();
                        },
                      ),
                      flex: 1,
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }
}