import 'dart:convert';
import 'dart:io';

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/community_view/community_dynamic.dart';
import 'package:huixiang/community/photo_view_gallery_screen.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/article.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/comunity_comment.dart';
import 'package:huixiang/retrofit/data/member_Infor.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/data/upload_result.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_footer.dart';
import 'package:huixiang/view_widget/no_data_view.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PersonalPage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  PersonalPage({this.arguments});

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

class _PersonalPage extends State<PersonalPage> with WidgetsBindingObserver {
  ApiService apiService;
  final RefreshController refreshController = RefreshController();
  final ScrollController scrollController = ScrollController();
  var isShrink = false;
  int pageNum = 1;
  String userId;
  List<Article> articles = [];
  MemberInfor memberInfor;
  String filePath;
  bool isLoadMore = false;
  bool isRefresh = true;
  bool isLoadingData = false;
  String memberId;
  Map<String, dynamic> modifyInfo = {"background": ""};

  @override
  void initState() {
    super.initState();
    memberId = widget.arguments["memberId"];
    WidgetsBinding.instance.addObserver(this);
    SharedPreferences.getInstance().then((value) => {
          apiService = ApiService(Dio(),
              context: context,
              token: value.getString('token'),
              showLoading: true),
          _onRefresh(),
        });
  }

  _onRefresh() async {
    queryCommunity(null);
    queryMember(memberId);
  }

  ///查询会员信息
  queryMember(id) async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<MemberInfor> baseData =
        await apiService.memberDetail(id).catchError((error) {
      refreshController.refreshFailed();
    });
    if (baseData != null && baseData.isSuccess) {
      setState(() {
        memberInfor = baseData.data;
      });
      refreshController.refreshCompleted();
    } else {
      refreshController.refreshFailed();
    }
  }

  ///动态列表
  queryCommunity(String searchKey) async {
    if(!isRefresh){
      isRefresh = true;
      return;
    }
    if(isLoadingData){
      return;
    }
    isLoadingData = true;
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      userId = value.getString('userId');
      apiService = ApiService(
          Dio(),
          context: context,
          token: value.getString("token"),
          showLoading: false
      );
    }
    if(isLoadMore){
      pageNum += 1;
      isLoadMore = false;
    }
    else if(searchKey == null)pageNum = 1;
    BaseData<PageInfo<ComunityComment>> baseData = await apiService.trendList({
      "mid": memberId == "0" ? userId : memberId,
      "onlyFollow": false,
      "onlyMe": true,
      "pageNum": searchKey == null?pageNum:1,
      "pageSize": 10,
      "searchKey": searchKey??""
    }).catchError((error) {
      if(searchKey == null) {
        refreshController.refreshFailed();
        refreshController.loadFailed();
      }
    });
    if(searchKey == null){
    refreshController.refreshCompleted();
    refreshController.loadComplete();
    }
    if (baseData.isSuccess) {
      if(searchKey != null){
        if(baseData?.data?.list != null && baseData.data.list.isNotEmpty)
          articles.forEach((element) {
            if(element.id == searchKey){
              element.content = jsonEncode(baseData.data.list[0].subjectInfo);
              element.mainTitle =baseData.data.list[0].subject;
              element.followed = baseData.data.list[0].selfFollow;
              element.authorHeadImg = baseData.data.list[0].memberInfo?.avatar;
              element.authorName = baseData.data.list[0].memberInfo?.nickname;
              element.location = baseData.data.list[0].location;
              element.createTime = baseData.data.list[0].createTime;
              element.author = baseData.data.list[0].memberInfo?.mid;
              element.viewers = baseData.data.list[0]?.viewers;
              element.likes = baseData.data.list[0]?.likes;
              element.comments = baseData.data.list[0]?.comments;
              this.isRefresh = false;
              setState(() {
              });
            }
          });
      }
      else{
        if (pageNum == 1) {
          articles.clear();
        }
        baseData.data.list.forEach((element) {
          var article = Article();
          article.id = element.id;
          article.content = jsonEncode(element.subjectInfo);
          article.mainTitle =element.subject;
          article.followed = element.selfFollow;
          article.authorHeadImg = element.memberInfo?.avatar;
          article.authorName = element.memberInfo?.nickname;
          article.location = element.location;
          article.createTime = element.createTime;
          article.author = element.memberInfo?.mid;
          article.viewers = element?.viewers;
          article.likes = element?.likes;
          article.comments = element?.comments;
          articles.add(article);
        });
        setState(() {
        });
        // comments.sort((a,b)=>b.createTime.compareTo(a.createTime));
        // print("comments: ${comments.length}");
        if (int.tryParse(baseData.data.total) < (pageNum * 10)) {
          refreshController.loadNoData();
        }
      }
    }

    isLoadingData = false;
  }

  ///去编辑个人资料
  _toUserInfo() async {
    SharedPreferences shared = await SharedPreferences.getInstance();
    if (shared.getString("token") == null || shared.getString("token") == "") {
      Navigator.of(context)
          .pushNamed('/router/new_login_page', arguments: {"login": "login"});
      return;
    }
    await Navigator.of(context)
        .pushNamed('/router/user_info_page')
        .then((value) {
      _onRefresh();
      setState(() {});
    });
    setState(() {});
  }

  ///显示图片选择方式
  showImagePicker() {
    showCupertinoModalPopup(
        context: context,
        builder: (contetx) {
          return CupertinoActionSheet(
            title: Text(S.of(context).genghuantouxiang),
            actions: [
              CupertinoActionSheetAction(
                child: Text(S.of(context).paizhao),
                onPressed: () {
                  openCamera();
                  Navigator.of(context).pop();
                },
                isDefaultAction: true,
                isDestructiveAction: false,
              ),
              CupertinoActionSheetAction(
                child: Text(S.of(context).xiangce),
                onPressed: () {
                  openStorage();
                  Navigator.of(context).pop();
                },
                isDefaultAction: true,
                isDestructiveAction: false,
              ),
            ],
            cancelButton: CupertinoActionSheetAction(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text(S.of(context).quxiao),
              isDestructiveAction: true,
            ),
          );
        });
  }

  ///拍照
  openCamera() async {
    if (await Permission.camera.isGranted) {
      Media medias = await ImagePickers.openCamera(
        cameraMimeType: CameraMimeType.photo,
        cropConfig: CropConfig(
          enableCrop: true,
          width: 200,
          height: 200,
        ),
        compressSize: 500,
      );
      if (medias == null) return;
      filePath = medias.path;
      fileUpload();
    } else {
      await Permission.camera.request();
      openCamera();
    }
  }

  ///打开相册
  openStorage() async {
    if (await Permission.storage.isGranted) {
      List<Media> medias = await ImagePickers.pickerPaths(
        galleryMode: GalleryMode.image,
        selectCount: 1,
        showGif: true,
        showCamera: false,
        compressSize: 500,
        uiConfig: UIConfig(
          uiThemeColor: Color(0xFFFFFFFF),
        ),
        cropConfig: CropConfig(
          enableCrop: true,
          width: 200,
          height: 200,
        ),
      );
      if (medias == null || medias.length == 0) return;
      filePath = medias[0].path;
      setState(() {});
      fileUpload();
    } else {
      await Permission.storage.request();
      openStorage();
    }
  }

  ///调用修改用户信息接口
  modifyInfos() async {
    var info = await apiService.editInfo(modifyInfo).catchError((onError) {});
    if (info.isSuccess) {
      setState(() {
        SmartDialog.showToast("用户信息修改成功", alignment: Alignment.center);
      });
      _onRefresh();
    }
  }

  ///文件上传
  fileUpload() async {
    if (filePath != null && filePath != "" && await File(filePath).exists()) {
      BaseData<UploadResult> baseData = await apiService
          .upload(File(filePath), 123123123, false)
          .catchError((onError) {});
      if (baseData != null && baseData.isSuccess) {
        UploadResult uploadResult = baseData.data;
        modifyInfo["background"] = uploadResult.url;
        modifyInfos();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: MyHeader(),
      footer: CustomFooter(
        builder: (context, mode) {
          return MyFooter(mode);
        },
      ),
      onRefresh: _onRefresh,
      onLoading: () {
        isLoadMore = true;
        setState(() {
          _onRefresh();
        });
      },
      physics: BouncingScrollPhysics(),
      scrollController: scrollController,
      child: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 248,
                color: Color(0xFFFFFFFF),
                // color: Colors.red,
                child: Stack(
                  // alignment: Alignment.bottomLeft,
                  children: [
                    Positioned(
                      top: 0,
                      left: 0,
                      bottom: 36,
                      right: 0,
                      child: Stack(
                        alignment: Alignment.bottomRight,
                        children: [
                          Container(
                              color: Colors.black,
                              child: Opacity(
                                  opacity: 0.9,
                                  child: MImage(
                                    memberInfor?.background ?? "",
                                    width: double.infinity,
                                    height: 260.h,
                                    fit: BoxFit.cover,
                                    errorSrc: "assets/image/default_1.webp",
                                    fadeSrc: "assets/image/default_1.webp",
                                  ))),
                          Container(
                            margin: EdgeInsets.only(
                                top: 50.h, left: 16.w, right: 16.w),
                            alignment: Alignment.topLeft,
                            decoration: BoxDecoration(
                              color: Colors.transparent,
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                GestureDetector(
                                  child: Image.asset(
                                    "assets/image/integral_return.webp",
                                    width: 24,
                                    height: 24,
                                  ),
                                  onTap: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            ),
                          ),
                          if (memberId == "0")
                            Positioned(
                              bottom: 9,
                              right: 16.w,
                              child: GestureDetector(
                                onTap: () {
                                  showImagePicker();
                                },
                                child: Container(
                                  padding: EdgeInsets.only(left: 2, right: 2),
                                  width: 59.w,
                                  height: 23.h,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(2),
                                    color: Color(0x80000000),
                                  ),
                                  child: Text(
                                    S.of(context).genghuanbeijing,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      fontWeight: MyFontWeight.regular,
                                      color: Color(0xFFFFFFFF),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                    homeInfo(),
                  ],
                ),
              ),
              Container(
                color: Color(0xFFFFFFFF),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                        margin: EdgeInsets.only(left: 86, top: 12, right: 16),
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              isShrink = !isShrink;
                            });
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Expanded(
                                  flex: 1,
                                  child: Text(
                                    memberId == "0"
                                        ? ((memberInfor?.signature == "")
                                            ? "还未编辑个性签名~"
                                            : memberInfor?.signature ?? "")
                                        : "个性签名: ${(memberInfor?.signature == "") ? "还未编辑个性签名~" : memberInfor?.signature ?? ""}",
                                    overflow: isShrink
                                        ? TextOverflow.visible
                                        : TextOverflow.ellipsis,
                                    maxLines: isShrink ? 10 : 2,
                                    style: TextStyle(
                                        fontSize: 12.sp,
                                        color: Color(0xFF868686),
                                        fontWeight: MyFontWeight.regular,
                                        height: 1.5),
                                  )),
                              Icon(
                                (isShrink != null && !isShrink)
                                    ? Icons.chevron_right
                                    : Icons.keyboard_arrow_up,
                                color: Colors.black,
                                size: 18,
                              ),
                            ],
                          ),
                        )),
                    Container(
                      margin: EdgeInsets.only(left: 16, right: 16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {},
                              child: Container(
                                  color: Colors.transparent,
                                  padding: EdgeInsets.all(16),
                                  child: Column(
                                    children: [
                                      Text(
                                        memberInfor != null
                                            ? memberInfor.follow.toString()
                                            : "0",
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 16.sp,
                                          fontWeight: MyFontWeight.semi_bold,
                                        ),
                                      ),
                                      SizedBox(
                                        height: 4,
                                      ),
                                      Text(
                                        S.of(context).guanzhu,
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 12.sp,
                                          fontWeight: MyFontWeight.regular,
                                        ),
                                      ),
                                    ],
                                  )),
                            ),
                          ),
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {},
                              child: Container(
                                  color: Colors.transparent,
                                  padding: EdgeInsets.all(16),
                                  child: Column(
                                    children: [
                                      Text(
                                        memberInfor != null
                                            ? memberInfor.fans.toString()
                                            : "0",
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 16.sp,
                                          fontWeight: MyFontWeight.semi_bold,
                                        ),
                                      ),
                                      SizedBox(
                                        height: 4,
                                      ),
                                      Text(
                                        S.of(context).fensi,
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 12.sp,
                                          fontWeight: MyFontWeight.regular,
                                        ),
                                      ),
                                    ],
                                  )),
                            ),
                          ),
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {},
                              child: Container(
                                  color: Colors.transparent,
                                  padding: EdgeInsets.all(16),
                                  child: Column(
                                    children: [
                                      Text(
                                        (memberInfor?.trendTotal ?? 0)
                                            .toString(),
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 16.sp,
                                          fontWeight: MyFontWeight.semi_bold,
                                        ),
                                      ),
                                      SizedBox(
                                        height: 4,
                                      ),
                                      Text(
                                        S.of(context).dongtai,
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 12.sp,
                                          fontWeight: MyFontWeight.regular,
                                        ),
                                      ),
                                    ],
                                  )),
                            ),
                          ),
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {},
                              child: Container(
                                  color: Colors.transparent,
                                  padding: EdgeInsets.all(16),
                                  child: Column(
                                    children: [
                                      Text(
                                        (memberInfor?.gainLikeTotal ?? 0)
                                            .toString(),
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 16.sp,
                                          fontWeight: MyFontWeight.semi_bold,
                                        ),
                                      ),
                                      SizedBox(
                                        height: 4,
                                      ),
                                      Text(
                                        "获赞",
                                        style: TextStyle(
                                          color: Color(0xFF353535),
                                          fontSize: 12.sp,
                                          fontWeight: MyFontWeight.regular,
                                        ),
                                      ),
                                    ],
                                  )),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.all(16),
                      height: 1.h,
                      color: Color(0xFFF7F7F7),
                    ),
                    Padding(
                        padding: EdgeInsets.only(left: 16),
                        child: Text(
                          memberId != "0" ? "TA的动态" : "我的动态",
                          style: TextStyle(
                            color: Color(0xFF353535),
                            fontSize: 15.sp,
                            fontWeight: MyFontWeight.semi_bold,
                          ),
                        )),
                    dynamicList()
                  ],
                ),
              ),
            ],
          )),
    );
  }

  Widget homeInfo() {
    return Positioned(
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        child: Container(
          padding: EdgeInsets.only(
            left: 16,
            right: 16,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => PhotoViewGalleryScreen(
                          images: [
                            (memberInfor?.headimg ?? "").isEmpty
                                ? "https://lmg.jj20.com/up/allimg/tx30/09041130358711081.jpg"
                                : memberInfor?.headimg
                          ], //传入图片list
                          index: 0, //传入当前点击的图片的index
                        ),
                      ));
                },
                child: MImage(
                  memberInfor?.headimg ?? "",
                  isCircle: true,
                  width: 66,
                  height: 66,
                  fit: BoxFit.cover,
                  errorSrc: "assets/image/default_user.webp",
                  fadeSrc: "assets/image/default_user.webp",
                ),
              ),
              SizedBox(width: 10.w),
              Text(
                memberInfor?.nickname ?? "",
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: MyFontWeight.medium,
                  color: Color(0xFF353535),
                ),
              ),
              SizedBox(width: 4.w),
              Image.asset(
                "assets/image/vip_yk.webp",
                width: 20,
                height: 20,
              ),
              Spacer(),
              if (memberId == "0")
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _toUserInfo();
                    });
                  },
                  child: Container(
                    height: 23,
                    padding:
                        EdgeInsets.only(left: 6, right: 6, bottom: 2, top: 2),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(100),
                      border: Border.all(
                        width: 1,
                        color: Color(0xFF353535),
                        style: BorderStyle.solid,
                      ),
                    ),
                    child: Text(
                      S.of(context).bianjigerenziliao,
                      style: TextStyle(
                        fontSize: 12.sp,
                        fontWeight: MyFontWeight.regular,
                        color: Color(0xFF353535),
                      ),
                    ),
                  ),
                )
            ],
          ),
        ));
  }

  Widget dynamicList() {
    return Container(
      child: (articles == null || articles.length == 0)
          ? NoDataView(
              src: "assets/image/dong_tai.webp",
              isShowBtn: false,
              text: "目前暂无发布动态,要把开心的事讲出来哦~",
              fontSize: 16.sp,
              margin: EdgeInsets.only(left: 60.w, right: 60.w),
            )
          : ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemBuilder: (context, position) {
                return InkWell(
                  child: CommunityDynamic(
                    articles[position],
                    memberId == "0" ? 1 : 0,
                    exitFull: () {
                      // setState(() {
                      //   _onRefresh();
                      // });
                    },
                    removalDynamic: () {
                      setState(() {
                        _onRefresh();
                      });
                    },
                  ),
                  onTap: () {
                    Navigator.of(context).pushNamed(
                      '/router/community_details',
                      arguments: {
                        "businessId": articles[position].id,
                        "userId": userId,
                      },
                    ).then((value) {
                      queryCommunity(articles[position].id);
                    });
                  },
                );
              },
              itemCount: articles.length,
            ),
    );
  }
}