import 'dart:convert';
import 'dart:io';
import 'package:chat/home/fans_page.dart';
import 'package:chat/home/goddess_hot.dart';
import 'package:chat/home/rich_title.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/models/voucher_change.dart';
import 'package:chat/utils/ChargeMoney.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/blacklist_mgr.dart';
import 'package:chat/utils/conversation_table.dart';
import 'package:chat/utils/file_cache_mgr.dart';
import 'package:chat/utils/friend_list_mgr.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:chat/utils/screen.dart';
import 'package:chat/utils/sp_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:chat/data/WebData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/InformUser.dart';
import 'package:chat/home/MoneyPage.dart';
import 'package:chat/home/Myprogram.dart';
import 'package:chat/home/VideoPage.dart';
import 'package:chat/home/VipPage.dart';
import 'package:chat/models/UserInfo.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/LoadingDialog.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/TutorialOverlay.dart';
import 'package:chat/utils/UserCard.dart';
import 'package:chat/utils/UserChips.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';
import 'package:image_cropper/image_cropper.dart';

import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:share/share.dart';
import '../utils/FullWithButton.dart';
import '../home/EditData.dart';
import '../home/SystemEditPage.dart';
import '../data/UserData.dart';
import '../utils/TokenMgr.dart';
import 'package:dio/dio.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'VerificationCenter.dart';
import 'WhiteAndBlackList.dart';
import "package:chat/utils/PicSwiper.dart";

import 'add_friend.dart';
import 'apply_content_view.dart';
import 'daily_bonus_page.dart';
import 'money_picture_view.dart';

var cardWidth;

var greyColor = const Color(0xFFB2B2B2);

class ProfilePage extends StatefulWidget {
  @required
  final userId;
  final int fromWhere;
  final int addMode;
  final int applyId; //好友申请id

  ProfilePage(
      {Key key,
      this.userId,
      this.fromWhere,
      this.addMode = 0,
      this.applyId = 0})
      : super(key: key);

  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage>
    with TickerProviderStateMixin {
  static const Separate_Size = 10.0;
  GlobalKey<ScaffoldState> registKey = new GlobalKey();
  UserInfo userInfo = new UserInfo();

  TextEditingController nickNameController = new TextEditingController();

  // AnimationController animationController;
  // Animation movement;

  bool isMyself = false;

  List imgList = [];

  bool isCanWatch = false;

  bool isMan = true;
  bool isAttestation = false;

  bool isBuyPicture = false;

  bool isVip = false;

  bool isSvip = false;

  bool isApplying = false; //是否申请中

  //约会节目
  String dateItem = '';

//期待对象
  String lovePeople = '';

//约会范围
  String dateRange = '';

//生日
  String birthday = '';

//身高数据
  String heightStr = '';

//体重数据
  String weightStr = '';

  //个人介绍
  String myMsg = '';

  Map wealthData = {
    'CoinValue': 0,
    'IsMember': 0,
  };

  int myselfImg = 0;

  String endTime = '';

  bool isLoadingFish = false;

  String firstDyImg = ''; //第一条动态的图片

  int programId = 0; //是否有一条活跃的节目

  bool isblack = false;

  bool isAuthority = false; //是否有聊天和查看用户资料的权限

  getUserInfo({mymsg = ''}) async {
    if (mymsg != '' && mymsg != null) {
      UserData().basicInfo.ownMsg = mymsg;
    }
    HttpUtil().getUserInfo(
        widget.userId,
        (data) async {
          print('getUserInfo $data');
          if (isMyself) {
            saveLocalData(data);
          }
          userInfo = UserInfo.fromJson(data);
          initValues();
          isLoadingFish = true;
          showMyMsgDialog();
          if (mounted) {
            setState(() {});
          }
        },
        _buildJoinVip,
        () {
          if (!isMyself) {
            Future.delayed(Duration(milliseconds: 500), () {
              Navigator.of(context).pop();
            });
          }
        });
    getImg();
    if (isMyself) {
      HttpUtil().getWealth(context, (data) {
        wealthData = data;
        endTime = data['MemberEnd'];
        if (mounted) {
          Provider.of<MoneyChangeProvider>(context)
              .initMoney(data['CoinValue']);
          Provider.of<VoucherChangeProvider>(context)
              .initVoucher(data['Voucher']);
        }
      });
    } else {
      // getFirstDy();
      // getFirstProgram();
    }
  }

  saveLocalData(data) {
    UserData().basicInfo = UserInfo.fromJson(data);
    SPUtils.saveString(
        Constants.LocalUsrInfo, jsonEncode(UserData().toJson()).toString());
  }

  initLocalData() async {
    if (isMyself && await SPUtils.get(Constants.LocalUsrInfo) != null) {
      isLoadingFish = true;
      userInfo = UserData().basicInfo;
      initValues();
      showMyMsgDialog();
    }
  }

  showMyMsgDialog() {
    if (!UserData().isFirstTip &&
        (UserData().basicInfo.ownMsg == '' ||
            UserData().basicInfo.ownMsg == null) &&
        UserData().homemainIndex == 4) {
      UserData().isFirstTip = true;

      CustomUI.buildOneConfirm(
          context, I18n.of(context).personal, I18n.of(context).white_now, () {
        Navigator.pop(context);
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return EditPage(
                isEditPage: true,
              );
            },
          ),
        );
      });
    }
  }

  initValues() {
    isMan = userInfo.sex == 1;
    isAttestation = userInfo.isAttestation == null || userInfo.isAttestation;
    isVip = userInfo.isMember > 0;
    isSvip = userInfo.isMember == 2;
    isCanWatch = userInfo.infoAut == 0 || userInfo.applyStatus == 1;
    isApplying = userInfo.applyStatus == 0;
    isblack = userInfo.isBlackList;
    isBuyPicture =
        (isMyself || userInfo.photoAut == 0 || userInfo.payStatus == 1);

    dateItem =
        userInfo.program == null ? "" : WebData().getProgram(userInfo.program);

    lovePeople = userInfo.hopeObject == null
        ? ""
        : WebData().getLovePeople(userInfo.hopeObject);

    dateRange = WebData().getDateRange(userInfo.meetPlace);

    birthday = userInfo.birthday == null ? '' : userInfo.birthday;
    isAuthority = userInfo.isAuthority ||
        (!UserData().isMan() && UserData().basicInfo.isAttestation) ||
        userInfo.distince < 200;
    myMsg = userInfo.ownMsg;
  }

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

    print('ProfilePage initState');

    isMyself = widget.userId == UserData().basicInfo.userId;
    messageOn();
    initLocalData();
    getUserInfo();
  }

  void initMyController() {}

  void _buildJoinVip() {
    isLoadingFish = true;
    CustomUI.buildOneConfirm(
        context, I18n.of(context).only_see, I18n.of(context).joinvip, () {
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return VipPage();
          },
        ),
      );
    }, failcallbak: () {
      Navigator.of(context).pop();
    });
  }

  msgBuyVip(data) {
    HttpUtil().getWealth(context, (data) {
      wealthData = data;
      endTime = data['MemberEnd'];
      if (mounted) {
        Provider.of<MoneyChangeProvider>(context).initMoney(data['CoinValue']);
      }
    });
  }

  msgRefreshPhoto(data) {
    getImg();
  }

  msgUpdateData(data) {
    print('msgUpdateData $data');
    getUserInfo(mymsg: data);
  }

  msgInformSucess(data) {
    if (!isMyself)
      CustomUI.buildOneConfirm(
          context, I18n.of(context).waiting_results, I18n.of(context).ok, () {
        Navigator.of(context).pop();
      });
  }

  msgListDelete(data) {
    if (userInfo.dynamicNum > 0) {
      if (mounted) {
        setState(() {
          userInfo.dynamicNum--;
        });
      }
    }
  }

  void messageOn() {
    MessageMgr().on('inform_sucess', msgInformSucess);
    MessageMgr().on('refresh_money', msgBuyVip);
    MessageMgr().on('refresh_photo', msgRefreshPhoto);
    MessageMgr().on('update_data', msgUpdateData);
    MessageMgr().on('delete_program', msgListDelete);
    MessageMgr().on('post_add_friend', msgAddFriend);
    MessageMgr().on('refresh_love_list', msgRefreshLoveList);
    MessageMgr().on('refresh_fans_num', msgRefreshFansNum);
  }

  void messageOff() {
    MessageMgr().off('inform_sucess', msgInformSucess);
    MessageMgr().off('refresh_money', msgBuyVip);
    MessageMgr().off('refresh_photo', msgRefreshPhoto);
    MessageMgr().off('update_data', msgUpdateData);
    MessageMgr().off('delete_program', msgListDelete);
    MessageMgr().off('post_add_friend', msgAddFriend);
    MessageMgr().off('refresh_love_list', msgRefreshLoveList);
    MessageMgr().off('refresh_fans_num', msgRefreshFansNum);
  }

  msgRefreshFansNum(data) {
    setState(() {
      if (data['UserId'] == userInfo.userId && userInfo.fans < data['nums']) {
        userInfo.fans = data['nums'];
      }
    });
  }

  msgRefreshLoveList(data) {
    setState(() {
      if (data['flag'] == 0) {
        isMyself ? userInfo.followNum++ : userInfo.fans++;
      } else {
        isMyself ? userInfo.followNum-- : userInfo.fans--;
      }
    });
  }

  msgAddFriend(data) {
    setState(() {
      userInfo.isAddFriends = 0;
    });
  }

  @override
  void dispose() {
    messageOff();
    registKey = null;
    //animationController?.dispose();
    nickNameController.dispose();
    super.dispose();
  }

  void getImg() async {
    var data = {
      "visitUserId": UserData().basicInfo.userId,
      "userId": widget.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('user/personal/album', data: data);
    if (res == null) {
      return;
    }
    Map resData = res.data;
    if (resData['code'] == 0) {
      imgList = resData['data'] == null ? [] : resData['data'];
      if (isMyself) {
        UserData().picNum = 0;
        for (int i = 0; i < imgList.length; i++) {
          if (imgList[i]['Status'] == 1) {
            UserData().picNum++;
          }
          if (imgList[i]['Status'] == 0 || imgList[i]['Status'] == 2) {
            UserData().haveReview = true;
          }
        }
      }
      if (mounted) {
        setState(() {});
      }
    }
  }

//上传相册
  void _uploadPhoto() async {
    // if (await CustomUI.showPhotoPermissionSetting(context)) {
    //   var tempFile = await ImagePicker.pickImage(source: ImageSource.gallery);
    //   if (tempFile != null) {
    //     //选择焚烧
    //     Navigator.of(context).push(
    //       new MaterialPageRoute(
    //         builder: (context) {
    //           return UploadPicture(
    //             img: tempFile,
    //           );
    //         },
    //       ),
    //     );
    //   }
    // }


    List<Asset> resultList = List<Asset>();

    resultList = await MultiImagePicker.pickImages(
      maxImages: 9,
      enableCamera: false,
      selectedAssets: [],
      cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
      materialOptions: MaterialOptions(
        actionBarColor: "#50A7F9",
        actionBarTitle: "Hibok",
        allViewTitle: "",
        useDetailsView: false,
        selectCircleStrokeColor: "#000000",
      ),
    );

    if (resultList != null && resultList.length > 0) {
      List<File> fileList = [];
      for (var i = 0; i < resultList.length; i++) {
        Asset photoEntity = resultList[i];
        print('名字:${photoEntity.name}');
        ByteData byteData = await photoEntity.getByteData();
        File file =  await FileCacheMgr().writeFile('temp-photo-${DateTime.now().millisecondsSinceEpoch}-${photoEntity.name}', byteData.buffer.asInt8List(0));

        fileList.add(file);
      }
      print('文件列表${fileList.length}');
      Map data = {"type": 2, "userId": UserData().basicInfo.userId};
      data['sign'] = TokenMgr().getSign(data);
      data['sex'] = UserData().basicInfo.sex;
      data['isBurn'] = 0;
      Response res = await HttpUtil().uploadFiles(
          fileList, data, 'upload/post/postfiles', 'image',
          isShowLoading: true);
      var resData = res.data;
      if (resData['code'] == 0) {
        if (resData['data']['msg'] != '' && resData['data']['msg'] != null) {
          showToast(resData['data']['msg']);
        }
        if(resData['msg'].split('|').length !=fileList.length){
          showToast(I18n.of(context).hava_error_photo);
        }
        MessageMgr().emit('refresh_photo');
      }
    }

//    var photos = await PhotoPicker.pickAsset(
//        context: context,
//        themeColor: Color(0xFFF0F0F0),
//        textColor: Color(0xFF3F3F3F),
//        pickType: PickType.onlyImage);

//    if (photos != null && photos.length > 0) {
//      List<File> fileList = [];
//      for (var i = 0; i < photos.length; i++) {
//        AssetEntity photoEntity = photos[i];
//        fileList.add(await photoEntity.file);
//      }
//      Map data = {"type": 2, "userId": UserData().basicInfo.userId};
//      data['sign'] = TokenMgr().getSign(data);
//      data['sex'] = UserData().basicInfo.sex;
//      data['isBurn'] = 0;
//      Response res = await HttpUtil().uploadFiles(
//          fileList, data, 'upload/post/postfiles', 'image',
//          isShowLoading: true);
//      var resData = res.data;
//      if (resData['code'] == 0) {
//        if (resData['data']['msg'] != '' && resData['data']['msg'] != null) {
//          showToast(resData['data']['msg']);
//        }
//        if(resData['msg'].split('|').length !=photos.length){
//          showToast(I18n.of(context).hava_error_photo);
//        }
//        MessageMgr().emit('refresh_photo');
//      }
//    }
  }

  void _sendPicture() async {
    if (await CustomUI.showPhotoPermissionSetting(context)) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return LoadingDialog(
              text: "",
            );
          });
      var tempFile = await ImagePicker.pickImage(source: ImageSource.gallery);
      Navigator.of(context).pop();
      if (tempFile != null) {
        _cropPicture(tempFile);
      }
    }
  }

  void _cropPicture(tempFile) async {
    File croppedFile = await ImageCropper.cropImage(
      sourcePath: tempFile.path,
      aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
    );

    if (croppedFile != null) {
      Map data = {"type": 1, "userId": userInfo.userId};
      data['sign'] = TokenMgr().getSign(data);
      Response res = await HttpUtil()
          .uploadFile(croppedFile, data, 'upload/file/postflie', 'image');
      var resData = res.data;
      if (resData['code'] == 0) {
        userInfo.headimgurl = resData['msg'];

        if (mounted) {
          setState(() {});
        }
      }
    }
  }

  Widget _buildHeadView() {
    cardWidth = MediaQuery.of(context).size.width;

    Color buttonColor = Colors.grey;
    return Container(
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(bottom: Constants.GreyBorderSide)),
        child: Stack(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
              ),
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(top: 20),
              child: Column(
                children: <Widget>[
                  _buildHeadImg(),
                  _buildUserName(),
                  _buildUserChips(),
                  _buildResientCity(),
                  //_buildProgram(),
                  _buildAttestation(),
                  _buildFans(),
                ],
              ),
            ),
            _buildLoveButton(buttonColor),
          ],
        ));
  }

  //认证相关
  Widget _buildAttestation() {
    return Container(
        margin: EdgeInsets.only(top: 7, bottom: 7),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            isAttestation
                ? Icon(Icons.check_circle_outline,
                    size: 12, color: Constants.BlueTextColor)
                : Padding(
                    padding: EdgeInsets.only(bottom: 0.5),
                    child: Icon(IconData(0xe63a, fontFamily: 'iconfont'),
                        size: 16, color: const Color(0xFFA9A9A9))),
            SizedBox(width: 3),
            Text(
                isAttestation
                    ? isMyself
                        ? (isMan
                            ? (userInfo.isVipAttestation
                                ? I18n.of(context).by_paying
                                : I18n.of(context).incode_passed)
                            : I18n.of(context).certified)
                        : (isMan
                            ? (userInfo.isVipAttestation
                                ? I18n.of(context).pay_join
                                : I18n.of(context).passed_review)
                            : I18n.of(context).passed_video)
                    : isMyself
                        ? I18n.of(context).not_certified
                        : (isMan ? '' : I18n.of(context).not_video),
                textScaleFactor: 1.0,
                style: TextStyle(fontSize: 11, color: Constants.GreyTextColor))
          ],
        ));
    // return Stack(
    //   children: <Widget>[
    //     Container(
    //         margin: EdgeInsets.only(top: 3),
    //         alignment: Alignment.center,
    //         child: Row(
    //           mainAxisAlignment: MainAxisAlignment.center,
    //           children: <Widget>[
    //             isAttestation
    //                 ? Icon(Icons.check_circle_outline,
    //                     size: 12, color: Constants.BlueTextColor)
    //                 : Padding(
    //                     padding: EdgeInsets.only(bottom: 0.5),
    //                     child: Icon(IconData(0xe63a, fontFamily: 'iconfont'),
    //                         size: 16, color: const Color(0xFFA9A9A9))),
    //             SizedBox(width: 3),
    //             Text(
    //                 isAttestation
    //                     ? isMyself
    //                         ? (isMan
    //                             ? (userInfo.isVipAttestation
    //                                 ? I18n.of(context).by_paying
    //                                 : I18n.of(context).incode_passed)
    //                             : I18n.of(context).certified)
    //                         : (isMan
    //                             ? (userInfo.isVipAttestation
    //                                 ? I18n.of(context).pay_join
    //                                 : I18n.of(context).passed_review)
    //                             : I18n.of(context).passed_video)
    //                     : isMyself
    //                         ? I18n.of(context).not_certified
    //                         : (isMan ? '' : I18n.of(context).not_video),
    //                 textScaleFactor: 1.0,
    //                 style:
    //                     TextStyle(fontSize: 11, color: Constants.GreyTextColor))
    //           ],
    //         )),
    // !isMan && isAttestation
    //     ? Container(
    //         padding: EdgeInsets.only(top: 17),
    //         alignment: Alignment.centerRight,
    //         child: InkWell(
    //             onTap: () {
    //               Navigator.of(context).push(
    //                 new MaterialPageRoute(
    //                   builder: (context) {
    //                     return VideoPage(
    //                       userId: userInfo.userId,
    //                     );
    //                   },
    //                 ),
    //               );
    //             },
    //             child: Padding(
    //                 padding: EdgeInsets.only(right: 17),
    //                 child: Row(
    //                   mainAxisAlignment: MainAxisAlignment.end,
    //                   children: <Widget>[
    //                     Text('${I18n.of(context).certified_video}',
    //                         textScaleFactor: 1.0,
    //                         style: TextStyle(
    //                             fontSize: 11, color: Colors.grey)),
    //                     Icon(
    //                       IconData(0xe63c, fontFamily: 'iconfont'),
    //                       size: 18.0,
    //                       color: Color(AppColors.TabIconNormal),
    //                     ),
    //                   ],
    //                 ))))
    //     : Container(),
    //   ],
    // );
  }

  Widget _buildFansButton(int nums, String text, callback,
      {bool isShowDot = false}) {
    return InkWell(
      onTap: callback,
      child: Container(
          width: Screen.width / 3,
          child: Column(
            children: <Widget>[
              SizedBox(height: 8),
              Stack(
                children: <Widget>[
                  Padding(
                      padding: EdgeInsets.only(left: 4, right: 4),
                      child: Text(
                        nums < 0 ? "0" : nums.toString(),
                        style: TextStyle(
                            fontSize: 13,
                            //color: isMyself ? Constants.BlackTextColor : greyColor),
                            color: Constants.BlackTextColor),
                      )),
                  isShowDot
                      ? Positioned(
                          top: 2,
                          right: 0,
                          child: CircleAvatar(
                            radius: 2,
                            backgroundColor: const Color(0xFFE50000),
                          ),
                        )
                      : Container(
                          width: 0,
                        )
                ],
              ),
              SizedBox(height: 4),
              Text(
                text,
                style: TextStyle(
                    fontSize: 11,
                    //color: isMyself ? Constants.BlackTextColor : greyColor),
                    color: greyColor),
              ),
              SizedBox(height: 8),
            ],
          )),
    );
  }

  //关注列表
  Widget _buildFans() {
    return Container(
        decoration:
            BoxDecoration(border: Border(top: Constants.GreyBorderSide)),
        child: Row(
          //mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            _buildFansButton(
                userInfo.fans,
                I18n.of(context).fans,
                isMyself
                    ? () {
                        Navigator.of(context).push(
                          new MaterialPageRoute(
                            builder: (context) {
                              return FansPage();
                            },
                          ),
                        );
                      }
                    : null),
            _buildFansButton(
                userInfo.followNum,
                I18n.of(context).attention,
                isMyself
                    ? () {
                        Navigator.of(context).push(
                          new MaterialPageRoute(
                            builder: (context) {
                              return WhiteAndBlackPage(
                                isWhite: true,
                              );
                            },
                          ),
                        );
                      }
                    : null),
            _buildFansButton(userInfo.dynamicNum, I18n.of(context).dynamics,
                () {
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return MyProgramPage(
                      userId: userInfo.userId,
                      isMan: isMan,
                    );
                  },
                ),
              );
            }, isShowDot: userInfo.dynamicNum > 0),
          ],
        ));
  }

  // //约会节目按钮
  // Widget _buildProgram() {
  //   return programId != 0
  //       ? InkWell(
  //           onTap: () {
  //             Navigator.of(context).push(
  //               new MaterialPageRoute(
  //                 builder: (context) {
  //                   return ProgramDetailPage(
  //                     programId: programId,
  //                   );
  //                 },
  //               ),
  //             );
  //           },
  //           child: Container(
  //               decoration: BoxDecoration(
  //                   borderRadius: BorderRadius.all(
  //                       Radius.circular(Constants.LittleButtonRadius)),
  //                   gradient: LinearGradient(colors: <Color>[
  //                     const Color(0xFF6D6AEC),
  //                     const Color(0xFF1795FF),
  //                   ])),
  //               height: 31,
  //               alignment: Alignment.center,
  //               width: Screen.width,
  //               margin:
  //                   EdgeInsets.only(left: 32.5, right: 32.5, top: 5, bottom: 3),
  //               child: Stack(
  //                 alignment: Alignment.center,
  //                 children: <Widget>[
  //                   Container(
  //                       alignment: Alignment.center,
  //                       height: 31,
  //                       child: Text(
  //                         isMan
  //                             ? I18n.of(context).his_appointment
  //                             : I18n.of(context).her_appointment,
  //                         style: TextStyle(color: Colors.white, fontSize: 14),
  //                       )),
  //                   Positioned(
  //                     right: 30,
  //                     child: Container(
  //                         //padding: movement.value,
  //                         child: Image.asset(
  //                       'assets/images/hand.png',
  //                       width: 20,
  //                     )),
  //                   )
  //                 ],
  //               )))
  //       : Container();
  // }

  //常驻城市
  Widget _buildResientCity() {
    return isMyself
        ? Container(
            padding: EdgeInsets.only(top: 5),
            child: Text(
              userInfo.userId == null
                  ? ''
                  : '${I18n.of(context).Resident_city}：${UserData().hasLocationPermission ? WebData().getDateRange(userInfo.meetPlace) : I18n.of(context).unknown}',
              textScaleFactor: 1.0,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 12),
            ))
        : userInfo.userId == null
            ? Container()
            : Padding(
                padding: EdgeInsets.only(top: 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    InfoTile(
                        icon: IconData(0xe630,
                            fontFamily: Constants.IconFontFamily),
                        title: WebData()
                            .getDistanceString(userInfo.distince.toDouble()),
                        titleColor: greyColor,
                        isDivider: true),
                    InfoTile(
                        title: userInfo.onlineStatus == 1
                            ? I18n.of(context).online
                            : WebData()
                                .getLoginTime(context, userInfo.loginDate),
                        titleColor: greyColor,
                        isDivider:
                            userInfo.photoAut == 1 || userInfo.infoAut == 1),
                    userInfo.infoAut == 1
                        ? InfoTile(
                            icon: IconData(0xe645, fontFamily: 'iconfont'),
                            iconHeight: 22,
                            title: I18n.of(context).application_view,
                            titleColor: greyColor,
                            isDivider: false,
                            onTap: () {})
                        : Container(),
                    userInfo.photoAut == 1
                        ? InfoTile(
                            icon: IconData(0xe632,
                                fontFamily: Constants.IconFontFamily),
                            title: I18n.of(context).paid_photo,
                            titleColor: greyColor,
                            isDivider: false,
                            onTap: () {})
                        : Container(),
                  ],
                ));
  }

  //用户chips
  Widget _buildUserChips() {
    var age = 0;
    if (userInfo.birthday != null) {
      age = DateTime.now().year - int.parse(userInfo.birthday.split('-')[0]);
    }
    return Container(
        margin: EdgeInsets.only(top: 10),
        alignment: Alignment.center,
        width: cardWidth,
        child: userInfo.userId == null
            ? Container()
            : UserChips(
                bgColor: const Color(0xFFF2F2F2),
                fontStyle:
                    TextStyle(fontSize: 12, color: const Color(0xFF807B95)),
                isCenter: true,
                city: UserData().hasLocationPermission
                    ? WebData().getCity(userInfo.city)
                    : I18n.of(context).unknown,
                age: age,
                constellation:
                    WebData().getConstellation(context, userInfo.constellation),
                professional: userInfo.occupation == null
                    ? ''
                    : WebData().getProffesionName(userInfo.occupation)));
  }

  //用户姓名
  Widget _buildUserName() {
    return isMyself
        ? InkWell(
            onTap: () {
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return EditPage(isEditPage: true);
                  },
                ),
              );
            },
            child: Container(
                margin: EdgeInsets.only(top: 10),
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                        Provider.of<RefNameProvider>(context)
                            .getRefName(userInfo.userId, userInfo.nickName),
                        textScaleFactor: 1.0,
                        style: TextStyle(
                            color: Constants.BlackTextColor,
                            fontWeight: FontWeight.w500,
                            fontSize: 16)),
                    isAttestation && !isMan
                        ? Container(
                            height: 13,
                            margin: EdgeInsets.only(left: 5),
                            padding: EdgeInsets.only(left: 5, right: 5),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: Constants.PurpleBackgroundColor,
                            ),
                            child: Text(
                              'Real',
                              textScaleFactor: 1.0,
                              style:
                                  TextStyle(fontSize: 9, color: Colors.white),
                            ))
                        : Text(''),
                    isVip && isMan
                        ? Container(
                            margin: EdgeInsets.only(left: 5),
                            child:
                                isSvip ? Constants.svipIcon : Constants.vipIcon)
                        : Text(''),
                    Container(
                      padding: EdgeInsets.only(left: 5),
                      alignment: Alignment.center,
                      child: new InkWell(
                        child: Icon(
                          IconData(0xe6e5, fontFamily: 'iconfont'),
                          color: Colors.grey,
                          size: 16,
                        ),
                        onTap: () {
                          Navigator.of(context).push(
                            new MaterialPageRoute(
                              builder: (context) {
                                return EditPage(isEditPage: true);
                              },
                            ),
                          );
                        },
                      ),
                    )
                  ],
                )))
        : Container();
  }

  //用户头像
  Widget _buildHeadImg() {
    bool needSign = UserData().sign == 1 && isMyself;

    return Container(
      width: MediaQuery.of(context).size.width,
      child: Stack(
        children: <Widget>[
          Center(
            child: InkWell(
                onTap: isMyself
                    ? _sendPicture
                    : () {
                        Navigator.of(context).push(
                          new MaterialPageRoute(
                            builder: (context) {
                              return PicSwiper(
                                id: 0,
                                pics: [
                                  PicSwiperItem(userInfo.headimgurl, id: 0)
                                ],
                              );
                            },
                          ),
                        );
                      },
                child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(2.0),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey[200],
                            offset: Offset(0, 6),
                            blurRadius: 5,
                          )
                        ]),
                    width: 110,
                    height: 110,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: userInfo.headimgurl == null ||
                              userInfo.headimgurl == ''
                          ? Image.asset(Constants.DefaultHeadImgUrl,
                              height: 110, width: 110)
                          : CachedNetworkImage(
                              imageUrl: userInfo.headimgurl,
                              placeholder: (context, url) => Image.asset(
                                Constants.DefaultHeadImgUrl,
                                height: 110,
                                width: 110,
                              ),
                              fit: BoxFit.cover,
                            ),
                    ))),
          ),

          ///签到功能入口
          needSign
              ? Positioned.fill(
                  child: GestureDetector(
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) {
                          return DailyBonusPage();
                        },
                      ));
                    },
                    child: Container(
                      alignment: Alignment.centerRight,
                      child: Container(
                        margin: EdgeInsets.only(right: 23),
                        width: 48,
                        height: 48,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(30)),
                            boxShadow: [
                              BoxShadow(
                                  color: Color(0x739f9f9f),
                                  offset: Offset(0.3, 0.5),
                                  blurRadius: 2.0,
                                  spreadRadius: 1.0),
//                      BoxShadow(
//                          color: Color(0x9900FF00), offset: Offset(1.0, 1.0)),
//                      BoxShadow(color: Color(0xFF0000FF))
                            ]),
                        child: ClipOval(
                          child: Container(
                            color: Colors.white,
                            child: Column(
                              children: <Widget>[
                                SizedBox(
                                  height: 8,
                                ),
                                Icon(
                                  IconData(0xe65c,
                                      fontFamily: Constants.IconFontFamily),
                                  size: 20,
                                  color: Color(0xFF0D68FF),
                                ),
                                SizedBox(
                                  height: 2,
                                ),
                                Text(
                                  I18n.of(context).signin,
                                  style: TextStyle(
                                      color: Color(0xFF0D68FF), fontSize: 10),
                                )
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                )
              : Container()
        ],
      ),
    );
  }

  //收藏按钮
  Widget _buildLoveButton(Color buttonColor) {
    return isMyself || userInfo.sex == UserData().basicInfo.sex
        ? Container()
        : Positioned(
            right: 10,
            top: 20,
            child: InkWell(
                onTap: () async {
                  if (!userInfo.isLike) {
                    HttpUtil().setLove(userInfo.userId, () {
                      MessageMgr().emit('refresh_love_list',
                          {'UserId': userInfo.userId, 'flag': 0});
                      setState(() {
                        userInfo.isLike = true;
                      });
                    });
                  } else {
                    HttpUtil().cancleLove(userInfo.userId, () {
                      MessageMgr().emit('refresh_love_list',
                          {'UserId': userInfo.userId, 'flag': 2});
                      setState(() {
                        userInfo.isLike = false;
                      });
                    });
                  }
                },
                child: Container(
                    child: Row(
                      children: <Widget>[
                        Icon(
                          IconData(userInfo.isLike ? 0xe623 : 0xe625,
                              fontFamily: Constants.IconFontFamily),
                          size: 14,
                          color: userInfo.isLike
                              ? const Color(0xFFFF7777)
                              : buttonColor,
                        ),
                        SizedBox(width: 2),
                        Text(
                          I18n.of(context).like,
                          style: TextStyle(color: buttonColor, fontSize: 11),
                        )
                      ],
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 5),
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey[300]),
                        borderRadius: BorderRadius.circular(5)))));
  }

  Widget _buildMyPicture() {
    var pisc = imgList
        .map((f) => PicSwiperItem(
              f['ImgUrl'],
              id: f['Id'],
              type: f['Type'],
              isWatch: f['IsCheck'] == 1,
              userId: userInfo.userId,
              isBuy: f['PayStatus'] == 1,
            ))
        .toList();
    var list = imgList.map((data) {
      var width = MediaQuery.of(context).size.width / 4 - 15;
      bool isWatch = data['IsCheck'] == 1;
      double raduis = 10;
      return CustomUI.buildImgCover(data['Id'], pisc, data['ImgUrl'], width,
          raduis, isWatch, context, data['Type'],
          isMyself: isMyself,
          payStatus: data['PayStatus'],
          state: isMan ? 1 : data['Status']);
    }).toList();
    if (!isBuyPicture && list.length > 4) {
      list.length = 4;
    }

    TitleItem title;
    if (!isMan) {
      title = UserData().isVip
          ? TitleItem(
              title: I18n.of(context).unlock_user,
              name: Provider.of<RefNameProvider>(context)
                  .getRefName(userInfo.userId, userInfo.nickName),
            )
          : TitleItem(
              title: I18n.of(context).free_unlock,
              name: userInfo.price.toString() + I18n.of(context).mask_coin);
    } else {
      title = TitleItem(
          title: I18n.of(context).pay_unlock, name: userInfo.price.toString());
    }
    //我的相册
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: Separate_Size),
      padding: EdgeInsets.symmetric(horizontal: 10),
      width: isMyself ? Screen.width : cardWidth,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          FullWidthButton(
            title: (isMyself
                ? I18n.of(context).my_album
                : (isMan
                    ? I18n.of(context).his_photo
                    : I18n.of(context).her_photo)),
            //+'(${I18n.of(context).visit_you.replaceFirst('/s1', userInfo.accessNum.toString())})',
            description: isMyself ? I18n.of(context).upload : '',
            descriptionColor: Constants.BlueTextColor,
            showDivider: true,
            showRightIcon: false,
            onPressed: isMyself ? _uploadPhoto : () {},
          ),
          list.length == 0
              ? (isMyself
                  ? InkWell(
                      onTap: _uploadPhoto,
                      child: Container(
                          height: 100,
                          alignment: Alignment.center,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(I18n.of(context).first_photo,
                                  textScaleFactor: 1.0),
                              Text(
                                  isMan
                                      ? I18n.of(context).have_picture
                                      : I18n.of(context).no_photo,
                                  textScaleFactor: 1.0,
                                  style: TextStyle(
                                      fontSize: 12, color: Colors.grey))
                            ],
                          )))
                  : Container(
                      alignment: Alignment.center,
                      height: 120,
                      child: Text(
                        isMan
                            ? I18n.of(context).not_up_man
                            : I18n.of(context).not_up_women,
                        textScaleFactor: 1.0,
                        style: TextStyle(fontSize: 14),
                      ),
                    ))
              : (isBuyPicture
                  ? Container(
                      //alignment: Alignment.center,
                      child: Wrap(
                      crossAxisAlignment: WrapCrossAlignment.start,
                      children: list,
                    ))
                  : Container(
                      alignment: Alignment.center,
                      child: Stack(
                        //alignment: Alignment.center,
                        children: <Widget>[
                          Wrap(
                            crossAxisAlignment: WrapCrossAlignment.start,
                            children: list,
                          ),
                          Opacity(
                            opacity: 0.96,
                            child: Container(
                              decoration: BoxDecoration(color: Colors.white),
                              height: 200,
                            ),
                          ),
                          Container(
                              height: 200,
                              alignment: Alignment.center,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Image.asset(
                                    'assets/images/suo.png',
                                    width: 35,
                                    color: Colors.grey[700],
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 10),
                                    alignment: Alignment.center,
                                    child: Text(
                                      isMan
                                          ? I18n.of(context).set_lock
                                          : I18n.of(context).set_lock2,
                                      textScaleFactor: 1.0,
                                      style: TextStyle(
                                          color: Colors.grey[700],
                                          fontSize: 15),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 8),
                                    alignment: Alignment.center,
                                    child: RichText(
                                      text: TextSpan(
                                          children: RichTitle.getRichText(title,
                                              titleStyle: TextStyle(
                                                  color: Colors.grey[700],
                                                  fontSize: 13),
                                              nameStyle: TextStyle(
                                                  color: Colors.red,
                                                  fontSize: 13))),
                                    ),
                                  ),
                                  InkWell(
                                      onTap: buyPhoto,
                                      child: Container(
                                        margin: EdgeInsets.only(top: 10),
                                        padding:
                                            EdgeInsets.only(top: 6, bottom: 6),
                                        width: 100,
                                        alignment: Alignment.center,
                                        decoration: Constants
                                            .ConfirmBUttonBoxDecoration,
                                        child: Text(
                                          I18n.of(context).unlock,
                                          textScaleFactor: 1.0,
                                          style: TextStyle(color: Colors.white),
                                        ),
                                      )),
                                ],
                              ))
                        ],
                      ))),
          !isMan && isMyself
              ? InkWell(
                  onTap: () {
                    if (!userInfo.isAttestation) {
                      _buildNotTrue();
                      return;
                    }
                    if (imgList.length == 0) {
                      showToast(I18n.of(context).no_photos);
                      return;
                    }
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (context) {
                      return MoneyPicture(
                        imageList: imgList,
                      );
                    }));
                  },
                  child: Container(
                    alignment: Alignment.centerRight,
                    // decoration: BoxDecoration(
                    //     border:
                    //     Border(top: BorderSide(color: Colors.grey[50]))),
                    margin: EdgeInsets.only(top: 10, right: 10, bottom: 10),
                    padding: EdgeInsets.only(top: 10),
                    child: Text(
                      I18n.of(context).set_photo,
                      textScaleFactor: 1.0,
                      style: TextStyle(color: Colors.red),
                    ),
                  ))
              : Container(),
          _buildRset(),
        ],
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
    );
  }

  void _buildNotTrue() {
    CustomUI.buildOneConfirm(context, I18n.of(context).moneyPageTip,
        I18n.of(context).authenticate_now, () {
      Navigator.pop(context);
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return VerificationCenterPage();
          },
        ),
      );
    });
  }

  void _buildConfirmBlack() {
    Navigator.of(context).pop();
    CustomUI.buildOneConfirm(
        context, I18n.of(context).blacklist_choose, I18n.of(context).determine,
        () async {
      Navigator.pop(context);
      HttpUtil().blackUser(userInfo.userId, () {
        isblack = true;
      });
    });
  }

  void _sendMySelfPicture() async {
    if (await CustomUI.showPhotoPermissionSetting(context)) {
      var tempFile = await ImagePicker.pickImage(source: ImageSource.gallery);
      if (tempFile != null) {
        Map data = {"type": 6, "userId": UserData().basicInfo.userId};
        data['sign'] = TokenMgr().getSign(data);
        data['isBurn'] = 1;

        Response res = await HttpUtil().uploadFile(
            tempFile, data, 'upload/file/postflie', 'image',
            isShowLoading: true);
        var resData = res.data;
        if (resData['code'] == 0) {
          showToast(I18n.of(context).successfully_submit);
          myselfImg = resData['data']['photoId'];
          Navigator.of(context).pop();
          _postApply();
        }
      }
    }
  }

  void _postApply() async {
    Map data = {
      "userId": userInfo.userId,
      "imgUrl": myselfImg,
      "applyUserId": UserData().basicInfo.userId
    };

    data['sign'] = TokenMgr().getSign(data);
    Response res = await HttpUtil()
        .post('user/apply/checkcords', data: data, isShowLoading: true);
    Map resData = res.data;
    if (resData['code'] == 0) {
      isApplying = true;
      setState(() {});
    }
  }

  Widget _buildBody() {
    Widget hidden = Container(
      alignment: Alignment.center,
      width: Screen.width,
      height: Screen.height - 372,
      color: Colors.white,
      margin: EdgeInsets.only(top: 10),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: 10),
            child: Image.asset('assets/images/login/lock.png',
                height: 45, width: 45),
          ),
          Text(
            isMan ? I18n.of(context).view_user : I18n.of(context).view_user2,
            textScaleFactor: 1.0,
            textAlign: TextAlign.center,
            style: TextStyle(color: Constants.GreyTextColor, fontSize: 13.5),
          ),
          InkWell(
              onTap: isApplying
                  ? null
                  : () async {
                      CustomUI.buildOneConfirm(
                          context,
                          I18n.of(context).need_photo,
                          I18n.of(context).choose_photo,
                          _sendMySelfPicture);
                    },
              child: Container(
                margin: EdgeInsets.only(top: 10, left: 100, right: 100),
                padding: EdgeInsets.only(top: 10, bottom: 10),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Constants.ConfrimButtonColor,
                    borderRadius: BorderRadius.all(
                        Radius.circular(Constants.LittleButtonRadius))),
                child: Text(
                  isApplying
                      ? I18n.of(context).already_applied
                      : I18n.of(context).apply_now,
                  textScaleFactor: 1.0,
                  style: TextStyle(color: Colors.white),
                ),
              )),
        ],
      ),
    );
    List<Widget> child = [];
    if (isMyself) {
      child.addAll([
        _buildHeadView(),
        _buildGoldnessHot(),
        _buildMoneyBox(),
        _buildMyPicture(),
        _buildTips(),
        _buildHistory(),
        //_buildApplyCode(),
        _buildShare(),
      ]);
    } else if (isCanWatch) {
      child.addAll([
        _buildHeadView(),
        _buildMyPicture(),
        _buildBasicInfo(),
        _buildBottomTips(),
      ]);
    } else if (userInfo.userId != null) {
      child.addAll([
        _buildHeadView(),
        hidden,
      ]);
    } else {
      child.addAll([
        _buildHeadView(),
      ]);
    }
    return Column(
      children: child,
    );
  }

  _inviteFdBtn() {
    return Container(
      width: Screen.width,
      child: FlatButton(
          child: fixedText(I18n.of(context).add_friends,
              fontSize: 16,
              color: Colors.blueAccent,
              fontWeight: FontWeight.w500),
          onPressed: () async {
            //已经是好友
            if (FriendListMgr().isMyFriend(userInfo.userId)) {
              showToast(I18n.of(context).added);
              return;
            }
            //已申请
            if (userInfo.isAddFriends == 0) {
              showToast(I18n.of(context).add_friends_tips);
              return;
            }

            if (widget.addMode != 3 &&
                UserData().addFdDistanceSwitch > 0 &&
                userInfo.distince > 200) {
              showToast(I18n.of(context).distance_long);
              return;
            }
            Navigator.of(context).push(
              new MaterialPageRoute(
                builder: (context) {
                  return AddFriendPage(
                    userId: userInfo.userId,
                    pageType: SendMessagePageType.AddFriends,
                    originalName: I18n.of(context)
                        .i_am
                        .replaceFirst('/s1', UserData().basicInfo.nickName),
                  );
                },
              ),
            );
          }),
    );
  }

  void doFriendApply(state, callback) async {
    Map data = {
      "id": widget.applyId,
      "userId": UserData().basicInfo.userId,
      "status": state,
    };
    data['sign'] = TokenMgr().getSign(data);
    Response res =
        await HttpUtil().post('friendship/handler/apply', data: data);
    if (res == null) {
      return;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      callback(resData['msg']);
    } else {}
  }

  _dealInvite() {
    return Container(
        width: Screen.width,
        child: Row(
          children: <Widget>[
            Expanded(
                child: InkWell(
              onTap: () {
                doFriendApply(1, (msg) {
                  showToast(msg);
                  Navigator.of(context).pop();
                  var friendModel = FriendModel.fromServerJson({
                    'UserId': userInfo.userId,
                    'ImgUrl': userInfo.headimgurl,
                    'UserName': userInfo.nickName
                  });
                  FriendListMgr().addFriend(friendModel);
                  MessageMgr().emit('do_friend_apply',
                      {'userId': userInfo.userId, 'state': 1});
                  MessageMgr().emit('Add friend');
                });
              },
              child: Container(
                color: const Color(0xFF3875E9),
                alignment: Alignment.center,
                child: Text(
                  I18n.of(context).agree,
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),
            )),
            InkWell(
                onTap: () {
                  doFriendApply(2, (msg) {
                    showToast(msg);
                    Navigator.of(context).pop();
                    MessageMgr().emit('do_friend_apply',
                        {'userId': userInfo.userId, 'state': 2});
                  });
                },
                child: Container(
                  alignment: Alignment.center,
                  color: const Color(0xFFA8D3FF),
                  width: Screen.width * 0.33,
                  child: Text(
                    I18n.of(context).refuse,
                    style:
                        TextStyle(fontSize: 18, color: const Color(0xFF007EFF)),
                  ),
                ))
          ],
        ));
  }

  //自定义item
  Widget _bottomBorderBox(
      String textLeft, String textRight, bool showBorder, callback,
      {showIcon: false}) {
    Widget left = new Container(
        margin: EdgeInsets.only(right: 20),
        width: 90,
        child: new Text(
          textLeft,
          textScaleFactor: 1.0,
          style: TextStyle(fontSize: 14),
        ));

    Widget right = new Expanded(
      child: Text(
        textRight,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 13, color: Constants.GreyTextColor),
      ),
    );
    return InkWell(
        highlightColor: Colors.transparent,
        radius: 0.0,
        onTap: callback,
        child: Container(
          decoration: showBorder
              ? BoxDecoration(border: Border(bottom: Constants.GreyBorderSide))
              : null,
          alignment: Alignment.center,
          padding: EdgeInsets.only(top: 17,bottom: 17,),
          margin: EdgeInsets.only(left: 20, bottom: 0, right: 10),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              left,
              right,
              showIcon
                  ? Padding(
                      padding: EdgeInsets.only(right: 10),
                      child: Icon(
                        IconData(0xe63c, fontFamily: 'iconfont'),
                        size: 22.0,
                        color: Color(AppColors.TabIconNormal),
                      ))
                  : Container()
            ],
          ),
        ));
  }


  testChatPermission(callback) {
    becomeVip() {
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return VipPage();
          },
        ),
      );
    }

    payCallback() {
      if (Provider.of<MoneyChangeProvider>(context).money <
          UserData().accountPrice) {
        Navigator.of(context).pop();
        CustomUI.buildOneConfirm(context, I18n.of(context).balance_insufficien,
            I18n.of(context).recharge, () {
          Navigator.of(context).pop();
          ChargeMoney.showChargeSheet(context, () {
            setState(() {});
          });
        });
        return;
      }
      Navigator.of(context).pop();
      HttpUtil().buyChatAccount(
          UserData().accountPrice, userInfo.userId, context, () {
        setState(() {
          isAuthority = true;
        });
      });
    }

    freeTime() {
      HttpUtil().userFreeTime(context, userInfo.userId, 2, () {
        UserData().basicInfo.usedNum++;
        Navigator.of(context).pop();
        setState(() {
          isAuthority = true;
        });
      });
    }

    // //对方是女性用户，且未认证提示未认证
    // if (userInfo.sex == 2 && !userInfo.isAttestation) {
    //   showToast(I18n.of(context).not_video);
    //   return;
    // }

    //自己是女性，且未认证,提示去认证(好友除外)
    if (!UserData().isMan() && !UserData().basicInfo.isAttestation && !FriendListMgr().isMyFriend(userInfo.userId)){
      CustomUI.buildNotTrue(context);
      return;
    }

    print('isAuthority $isAuthority');
    var tipStr = '';

    //没有解锁账号，并且对方禁止陌生人聊天
    if (!isAuthority && !userInfo.isCanStrangerNews) {
      tipStr = I18n.of(context).stranger_close;
    } else {
      tipStr = I18n.of(context).unlock_information;
      if (userInfo.sex == 2 && !userInfo.isAttestation) {
        tipStr += '(${I18n.of(context).not_true_woman})';
      }
    }
    if (isAuthority) {
      if (callback != null) callback();
    } else {
      //如果自己是男性，vip提示免费次数，次数用完或者非vip提示购买
      if (UserData().isMan()) {
        if (UserData().isVip) {
          UserData().basicInfo.freeNum < UserData().basicInfo.usedNum
              ? CustomUI.buildOneConfirm(
                  context,
                  tipStr,
                  I18n.of(context)
                      .pay_unlock
                      .replaceFirst('/s1', UserData().accountPrice.toString()),
                  payCallback)
              : CustomUI.buildOneConfirm(
                  context,
                  tipStr,
                  I18n.of(context).unlock_choose,
                  freeTime,
                );
        } else {
          CustomUI.buildTowConfirm(
              context,
              tipStr,
              I18n.of(context).become_member,
              becomeVip,
              I18n.of(context)
                  .pay_unlock
                  .replaceFirst('/s1', UserData().accountPrice.toString()),
              payCallback);
        }
      }
    }
  }

  buyChatAccount() {
    if (widget.fromWhere != null && widget.fromWhere == 0) {
      ///如果是聊天界面跳转过来的，直接返回
      Navigator.of(context).pop();
    } else {
      testChatPermission(() {
        int fdId = userInfo.userId;
        int sessionId = UserData().getSessionId(fdId);

        MsgHandler.updateActiveSesstion(sessionId);

        AppNavigator.pushChatPage(context, fdId);
      });
    }
  }

  buyPhoto() {
    //女性用户付费，男性用户会员的话免费解锁，非会员付费解锁
    becomeVip() {
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return VipPage();
          },
        ),
      );
    }

    payCallback() {
      if (Provider.of<MoneyChangeProvider>(context).money < userInfo.price) {
        Navigator.of(context).pop();
        CustomUI.buildOneConfirm(context, I18n.of(context).balance_insufficien,
            I18n.of(context).recharge, () {
          Navigator.of(context).pop();
          ChargeMoney.showChargeSheet(context, () {
            setState(() {});
          });
        });
        return;
      }
      Navigator.of(context).pop();
      HttpUtil().buyPictures(userInfo.price, userInfo.userId, context, () {
        setState(() {
          isBuyPicture = true;
        });
      });
    }

    freeTime() {
      HttpUtil().userFreeTime(context, userInfo.userId, 1, () {
        UserData().basicInfo.usedNum++;
        Navigator.of(context).pop();
        setState(() {
          isBuyPicture = true;
        });
      });
    }

    String title = I18n.of(context).unlock_user.replaceFirst(
          '/s1',
          Provider.of<RefNameProvider>(context)
              .getRefName(userInfo.userId, userInfo.nickName),
        );

    if (!UserData().isMan()) {
      CustomUI.buildOneConfirm(
          context,
          title,
          I18n.of(context)
              .pay_unlock
              .replaceFirst('/s1', userInfo.price.toString()),
          payCallback);
    } else if (UserData().isVip) {
      if (UserData().basicInfo.freeNum < UserData().basicInfo.usedNum) {
        CustomUI.buildOneConfirm(
            context,
            title,
            I18n.of(context)
                .pay_unlock
                .replaceFirst('/s1', userInfo.price.toString()),
            payCallback);
      } else {
        CustomUI.buildOneConfirm(
            context, title, I18n.of(context).unlock_choose, freeTime);
      }
    } else {
      CustomUI.buildTowConfirm(
          context,
          title,
          I18n.of(context).become_member,
          becomeVip,
          I18n.of(context)
              .pay_unlock
              .replaceFirst('/s1', userInfo.price.toString()),
          payCallback);
    }
  }

  Widget _buildBasicInfo() {
    String wechat = '';
    String facebook = '';
    bool isHidden = userInfo.accountStatus == 1;
    //隐藏社交账号
    if (isHidden) {
      wechat = I18n.of(context).ask_me;
      facebook = I18n.of(context).ask_me;
    } else {
      wechat = isAuthority ? userInfo.wechat : I18n.of(context).filled_in;
      facebook = isAuthority ? userInfo.facebook : I18n.of(context).filled_in;
    }

    heightStr = (userInfo.height == 0.0 || userInfo.height == null)
        ? I18n.of(context).not_show
        : '${userInfo.height.toInt()}CM';
    weightStr = (userInfo.weight == 0.0 || userInfo.weight == null)
        ? I18n.of(context).not_show
        : '${userInfo.weight.toInt()}KG';

    List<Widget> basicList = [
      userInfo.height != null && userInfo.height != 0
          ? _bottomBorderBox(I18n.of(context).height, heightStr, true, () {})
          : Container(),
      userInfo.weight != null && userInfo.weight != 0
          ? _bottomBorderBox(I18n.of(context).weight, weightStr, true, () {})
          : Container(),
      _bottomBorderBox(I18n.of(context).Resident_city, dateRange, true, () {}),
      //_bottomBorderBox(I18n.of(context).program, dateItem, true, () {}),
      _bottomBorderBox(I18n.of(context).expect_lover, lovePeople, true, () {}),
      (userInfo.wechat != null && userInfo.wechat != '')
          ? _bottomBorderBox(
              I18n.of(context).wechat_number, wechat, true, buyChatAccount,
              showIcon: !isAuthority)
          : Container(),
      (userInfo.facebook != null && userInfo.facebook != '')
          ? _bottomBorderBox(
              I18n.of(context).facebook, facebook, true, buyChatAccount,
              showIcon: !isAuthority)
          : Container(),
      userInfo.ownMsg != null && userInfo.ownMsg != ''
          ? _bottomBorderBox(
              I18n.of(context).self_introduction, myMsg, false, () {})
          : Container(),
    ];

    return Container(
        width: cardWidth,
        margin: EdgeInsets.only(top: Separate_Size),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                top: Constants.GreyBorderSide,
                bottom: Constants.GreyBorderSide)),
        child: new Column(
          children: basicList,
        ));
  }

  Widget _buildTips() {
    return Container(
        margin: EdgeInsets.only(top: 10, bottom: 10, left: 20, right: 20),
        child: Text(I18n.of(context).dont,
            textScaleFactor: 1.0,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey,
            )));
  }

  Widget _buildBottomTips() {
    return Container(
      margin: EdgeInsets.only(bottom: 10, left: 10, right: 10, top: 10),
      width: cardWidth,
      alignment: Alignment.center,
      child: Text(I18n.of(context).not_illage,
          textScaleFactor: 1.0,
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 12, color: Colors.grey)),
    );
  }

  Widget _buildGoldnessHot() {
    //女神热度
    return isMan
        ? Container()
        : Container(
            margin: EdgeInsets.only(top: Separate_Size),
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: FullWidthButton(
              title: I18n.of(context).Goddess_heat,
              showDivider: false,
              showRightIcon: true,
              onPressed: () {
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return GoddessHotPage(
                        userId: userInfo.userId,
                      );
                    },
                  ),
                );
              },
            ),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                    top: Constants.GreyBorderSide,
                    bottom: Constants.GreyBorderSide)),
          );
  }

  Widget _buildMoneyBox() {
    //认证、钱包、隐私连麦设置
    return Container(
      margin: EdgeInsets.only(top: Separate_Size),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
      padding: EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          isMan
              ? FullWidthButton(
                  title: I18n.of(context).member,
                  description: UserData().isVip
                      ? I18n.of(context)
                          .expires
                          .replaceFirst('/s1', endTime.split(' ')[0])
                      : I18n.of(context).enjoy_privileges,
                  showDivider: true,
                  onPressed: () {
                    Navigator.of(context).push(
                      new MaterialPageRoute(
                        builder: (context) {
                          return VipPage();
                        },
                      ),
                    );
                  },
                )
              : FullWidthButton(
                  title: isAttestation
                      ? I18n.of(context).certified_video
                      : I18n.of(context).authenticate,
                  showDivider: true,
                  onPressed: () {
                    Navigator.of(context).push(
                      new MaterialPageRoute(
                        builder: (context) {
                          return isAttestation
                              ? VideoPage(
                                  userId: userInfo.userId,
                                )
                              : VerificationCenterPage();
                        },
                      ),
                    );
                  },
                ),
          FullWidthButton(
            title: I18n.of(context).wallet,
            description:
                '${Provider.of<MoneyChangeProvider>(context).money}${I18n.of(context).mask_coin}',
            showDivider: false,
            onPressed: () {
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return MoneyPage();
                  },
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildHistory() {
    //历史访客
    return Container(
      margin: EdgeInsets.only(top: Separate_Size),
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: FullWidthButton(
        title: I18n.of(context).historical_visitor,
        description: I18n.of(context)
            .visit_you
            .replaceFirst('/s1', userInfo.accessNum.toString()),
        showDivider: false,
        showRightIcon: false,
        onPressed: () {},
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
    );
  }

  //恢复焚阅照片
  Widget _buildRset() {
    //历史访客
    return isMyself
        ? Container(
            margin: EdgeInsets.only(top: Separate_Size),
            //padding: EdgeInsets.symmetric(horizontal: 10),
            child: FullWidthButton(
              title: I18n.of(context)
                  .visit_photo
                  .replaceFirst('/s1', userInfo.burnNum.toString()),
              description: I18n.of(context).recovery_photo,
              showDivider: false,
              showRightIcon: false,
              onPressed: () async {
                CustomUI.buildOneConfirm(
                    context,
                    I18n.of(context).confrim_recovery,
                    I18n.of(context).determine, () async {
                  HttpUtil().resetPhoto(() {
                    Navigator.of(context).pop();
                    userInfo.burnNum = 0;
                    setState(() {});
                  });
                });
              },
            ),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(top: Constants.GreyBorderSide)),
          )
        : Container();
  }

  Widget _buildShare() {
    //分享
    return Container(
      margin: EdgeInsets.only(top: Separate_Size, bottom: Separate_Size),
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: FullWidthButton(
        showRightIcon: false,
        title: I18n.of(context).share_app,
        showDivider: false,
        onPressed: () {
          Share.share('https://henho.jphgames.com/');
        },
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: Constants.GreyBorderSide, bottom: Constants.GreyBorderSide)),
    );
  }

  Widget _buildIcon(code, str, isCanHit, callback, {iconSize = 28.0}) {
    var color = isCanHit ? Constants.BlueTextColor : Constants.GreyTextColor;
    return InkWell(
        onTap: isCanHit
            ? callback
            : () {
                showToast(isMan
                    ? I18n.of(context).view_user
                    : I18n.of(context).view_user2);
              },
        child: Row(
          children: <Widget>[
            Icon(
              IconData(
                code,
                fontFamily: 'iconfont',
              ),
              color: color,
              size: iconSize,
            ),
            Padding(
                child: Text(
                  str,
                  textScaleFactor: 1.0,
                  style: TextStyle(color: color, fontSize: 12),
                ),
                padding: EdgeInsets.only(left: 5))
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    cardWidth = screenSize.width;
    Widget appBar = AppBar(
      leading: isMyself ? Container() : CustomUI.buildCustomLeading(context),
      titleSpacing: isMyself ? -40 : NavigationToolbar.kMiddleSpacing,
      title: isMyself
          ? Text(
              I18n.of(context).me,
              textScaleFactor: 1.0,
              style: Constants.MainTitleStyle,
            )
          : Container(
              alignment: Alignment.center,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                      WebData().subUserName(
                          Provider.of<RefNameProvider>(context)
                              .getRefName(userInfo.userId, userInfo.nickName)),
                      textScaleFactor: 1.0,
                      style: TextStyle(color: Constants.BlackTextColor)),
                  isAttestation && !isMan
                      ? Container(
                          height: 13,
                          margin: EdgeInsets.only(left: 5),
                          padding: EdgeInsets.only(left: 5, right: 5),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Constants.PurpleBackgroundColor,
                          ),
                          child: Text(
                            'Real',
                            textScaleFactor: 1.0,
                            style: TextStyle(fontSize: 10, color: Colors.white),
                          ))
                      : Text(''),
                  isVip && isMan
                      ? Container(
                          margin: EdgeInsets.only(left: 5),
                          child:
                              isSvip ? Constants.svipIcon : Constants.vipIcon)
                      : Text(''),
                ],
              )),
      centerTitle: !isMyself,
      elevation: 1,
      actions: <Widget>[
        isMyself
            ? Container(
                padding: EdgeInsets.only(right: 15),
                alignment: Alignment.center,
                child: new InkWell(
                  child: CircleAvatar(
                      backgroundColor: Constants.GreyBackgroundColor,
                      radius: 15.75,
                      child: Icon(
                        IconData(0xe658, fontFamily: 'iconfont'),
                        color: Constants.BlackTextColor,
                        size: 20,
                      )),
                  onTap: () {
                    AppNavigator.pushQrPage(context);
                  },
                ),
              )
            : Container(),
        isMyself
            ? Container(
                padding: EdgeInsets.only(right: 15),
                alignment: Alignment.center,
                child: new InkWell(
                  child: CircleAvatar(
                      backgroundColor: Constants.GreyBackgroundColor,
                      radius: 15.75,
                      child: Icon(
                        Icons.settings,
                        //IconData(0xe6e5, fontFamily: 'iconfont'),
                        color: Constants.BlackTextColor,
                        size: 22,
                      )),
                  onTap: () {
                    Navigator.of(context).push(
                      new MaterialPageRoute(
                        builder: (context) {
                          return SystemEditPage();
                        },
                      ),
                    );
                  },
                ),
              )
            : Container(),
        isMyself
            ? Container(
                // padding: EdgeInsets.only(right: 10),
                // alignment: Alignment.center,
                // child: new InkWell(
                //   child: CircleAvatar(
                //       backgroundColor: Constants.GreyBackgroundColor,
                //       radius: 15.75,
                //       child: Icon(
                //         IconData(0xe6e5, fontFamily: 'iconfont'),
                //         color: Constants.BlackTextColor,
                //         size: 25,
                //       )),
                //   onTap: () {
                //     Navigator.of(context).push(
                //       new MaterialPageRoute(
                //         builder: (context) {
                //           return EditPage(isEditPage: true);
                //         },
                //       ),
                //     );
                //   },
                // ),
                )
            : Container(
                alignment: Alignment.center,
                child: new InkWell(
                  child: new Padding(
                    padding: EdgeInsets.only(
                        right: 15, left: 15, top: 10, bottom: 10),
                    child: Icon(
                      IconData(
                        0xe621,
                        fontFamily: 'iconfont',
                      ),
                      color: Constants.BlackTextColor,
                      size: 20,
                    ),
                  ),
                  onTap: () {
                    showModalBottomSheet(
                      context: registKey.currentContext,
                      builder: (BuildContext context) {
                        return SafeArea(
                          child: Container(
                            height: 137,
                            child: Column(
                              children: <Widget>[
                                InkWell(
                                    onTap: () async {
                                      Navigator.of(context).pop();
                                      Navigator.of(context).push(
                                        new MaterialPageRoute(
                                          builder: (context) {
                                            return AddFriendPage(
                                                userId: userInfo.userId,
                                                pageType:
                                                SendMessagePageType.Remark,
                                                originalName: Provider.of<
                                                    RefNameProvider>(
                                                    context)
                                                    .getRefName(userInfo.userId,
                                                    userInfo.nickName));
                                          },
                                        ),
                                      );
                                    },
                                    child: Container(
                                        alignment: Alignment.center,
                                        height: 45,
                                        child: Text(I18n.of(context).Remark,
                                            textScaleFactor: 1.0,
                                            style: TextStyle(
                                                fontSize: 18,
                                                color: Constants
                                                    .BlackTextColor)))),
                                Divider(height: 1),
                                InkWell(
                                  child: Container(
                                    height: 45,
                                    alignment: Alignment.center,
                                    child: Text(
                                      isblack
                                          ? I18n.of(context).remove_blacklist
                                          : I18n.of(context).blacklist,
                                      textScaleFactor: 1.0,
                                      style: TextStyle(
                                          fontSize: 18,
                                          color: Constants.BlackTextColor),
                                    ),
                                  ),
                                  onTap: isblack
                                      ? () async {
                                          HttpUtil().cancleBlackUser(
                                              userInfo.userId, () {
                                            Navigator.of(context).pop();
                                            isblack = false;
                                          });
                                        }
                                      : _buildConfirmBlack,
                                ),
                                Divider(height: 1),
                                InkWell(
                                    onTap: () async {
                                      Navigator.of(context).pop();
                                      Navigator.of(context).push(
                                        new MaterialPageRoute(
                                          builder: (context) {
                                            return InformUserPage(
                                              isMan: isMan,
                                              userId: userInfo.userId,
                                            );
                                          },
                                        ),
                                      );
                                    },
                                    child: Container(
                                        alignment: Alignment.center,
                                        height: 45,
                                        child: Text(
                                            I18n.of(context).anonymous_report,
                                            textScaleFactor: 1.0,
                                            style: TextStyle(
                                                fontSize: 18,
                                                color: Constants
                                                    .BlackTextColor)))),


                              ],
                            ),
                          ),
                        );
                      },
                    ).then((val) {});
                  },
                ),
              ),
      ],
    );
    var bottomWidget = Container(
      height: 55,
      decoration: BoxDecoration(
        border: Border(top: BorderSide(color: Color(0xffeaeaea))),
        color: Constants.LightGreyBackgroundColor,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: widget.addMode == 1 || widget.addMode == 3
            ? <Widget>[_inviteFdBtn()]
            : (widget.addMode == 2
                ? [_dealInvite()]
                : <Widget>[
                    _buildIcon(0xe633, I18n.of(context).evaluate, true,
                        () async {
                      Map data = {
                        "userid": userInfo.userId,
                        'evaluateuserid': UserData().basicInfo.userId,
                      };
                      data['sign'] = TokenMgr().getSign(data);

                      Response res = await HttpUtil().post('evaluate/user/info',
                          data: data, isShowLoading: true);

                      Map resData = res.data;
                      print(resData);
                      if (resData['code'] == 0) {
                        Navigator.of(context).push(TutorialOverlay(
                            child: ApplyContent(
                                userId: userInfo.userId,
                                isMan: isMan,
                                userInfo: resData['data'])));
                      } else {
                        showToast(resData['msg']);
                      }
                    }),
                    _buildIcon(0xe637, I18n.of(context).private_chat,
                        isCanWatch, isCanWatch ? buyChatAccount : null,
                        iconSize: 24.0),
                    _buildIcon(
                        0xe62f, I18n.of(context).chat, isCanWatch, onAudio)
                  ]),
      ),
    );
    Widget content = Container(
      color: Colors.white,
      child: SafeArea(
          child: Scaffold(
              bottomNavigationBar: !isMyself ? bottomWidget : null,
              appBar: appBar,
              key: registKey,
              body: SafeArea(
                  child: Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                color: AppColors.BackgroundColor,
                child: SingleChildScrollView(
                  child: _buildBody(),
                ),
              )))),
    );
    return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  //连麦
  onAudio() async {
    testChatPermission(() async {
      if (userInfo.chatStatus == 0) {
        showToast(I18n.of(context).cantt_voice);
        return;
      }
      if (BlacklistMgr.isBlack(userInfo.userId)) {
        return;
      }
      //对方关闭陌生人消息，则提示
      if (!userInfo.isCanStrangerNews) {
        showToast(I18n.of(context).stranger_close_tips);
        return;
      }

      if (await CustomUI.showPermissionSetting(context,
          PermissionGroup.microphone, I18n.of(context).video_permission)) {
        AppNavigator.pushAudioChatPage(context, userInfo);
      } else {
        showToast(I18n.of(context).need_record);
      }
    });
  }
}
