import 'package:chat/data/UserData.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/ProfilePage.dart';
import 'package:chat/home/ProgramDetail.dart';
import 'package:chat/home/VipPage.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/PicSwiper.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:chat/utils/PopUpMenu.dart' as myPopUp;
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

const BlackIconColor = const Color(0xFF4D4D4F);

class MessageBox extends StatefulWidget {
  final programInfo;
  final bool isDetail;
  MessageBox({
    Key key,
    @required this.programInfo,
    this.isDetail: false,
  }) : super(key: key);

  _MessageBoxState createState() => _MessageBoxState();
}

class _MessageBoxState extends State<MessageBox> {
  bool isMyself = false;
  bool isProgram = false;
  bool isCloseContent = false;
  bool isShowAll = false;

  //List fabulousList = [];

  @override
  Widget build(BuildContext context) {
    initValue();
    return _buildMessageBox(widget.programInfo);
  }

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

  void initValue() {
    isMyself = widget.programInfo['UserId'] == UserData().basicInfo.userId;
    isProgram = widget.programInfo['Type'] == 0;
    isCloseContent = widget.programInfo['EvaluateStatus'] == 1;
    widget.programInfo['EvaluateList'] =
        widget.programInfo['EvaluateList'] == null
            ? []
            : widget.programInfo['EvaluateList'];
    widget.programInfo['FabulousList'] =
        widget.programInfo['FabulousList'] == null
            ? []
            : widget.programInfo['FabulousList'];
  }

  void _selectValue(str, userId, isProgram) async {
    if (str == 'inform') {
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return InformUserPage(
              isMan: widget.programInfo['Sex'] == 1,
              programId: widget.programInfo['Id'],
              isProgram: isProgram,
              userId: userId,
            );
          },
        ),
      );
    } else if (str == 'black') {
      HttpUtil().blackUser(userId, () {});
    } else if (str == 'noContent') {
      var data = {
        "userId": UserData().basicInfo.userId,
        "type": 1,
        "id": userId,
      };
      data['sign'] = TokenMgr().getSign(data);

      Response res =
          await HttpUtil().post('station/settings/program', data: data);
      var resData = res.data;
      if (resData['code'] == 0) {
        showToast(resData['msg']);
        widget.programInfo['EvaluateStatus'] = 1;
        MessageMgr().emit('update_dy', true);
        setState(() {});
      }
    } else if (str == 'delete') {
      var data = {
        "userId": UserData().basicInfo.userId,
        "type": 2,
        "id": userId,
      };
      data['sign'] = TokenMgr().getSign(data);

      Response res =
          await HttpUtil().post('station/settings/program', data: data);
      var resData = res.data;
      if (resData['code'] == 0) {
        showToast(resData['msg']);
        if (isProgram) {
          UserData().isCanProgram = true;
        }
        MessageMgr().emit('delete_program', userId);
      }
    } else if (str == 'openContent') {
      var data = {
        "userId": UserData().basicInfo.userId,
        "type": 3,
        "id": userId,
      };
      data['sign'] = TokenMgr().getSign(data);

      Response res =
          await HttpUtil().post('station/settings/program', data: data);
      var resData = res.data;
      if (resData['code'] == 0) {
        showToast(resData['msg']);
        widget.programInfo['EvaluateStatus'] = 0;
        MessageMgr().emit('update_dy', false);
        setState(() {});
      }
    }
  }

  Widget _iconButton(code, iconColor, text, callback,
      {textColor = BlackIconColor, double iconSize = 18}) {
    return InkWell(
        onTap: callback,
        child: Container(
            alignment: Alignment.center,
            width: Screen.width / 4,
            margin: EdgeInsets.only(bottom: 5),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Container(
                    child: Icon(
                  IconData(
                    code,
                    fontFamily: 'iconfont',
                  ),
                  color: iconColor,
                  size: iconSize,
                )),
                Container(
                    constraints: BoxConstraints(minHeight: 15),

                    ///防止中文数字高度不一样，界面发生变化
                    padding: EdgeInsets.only(top: 2, left: 1.5),
                    child: fixedText(text,
                        color: textColor,
                        fontSize: 9.67,
                        fontWeight: FontWeight.normal))
              ],
            )));
  }

  Widget _iconRow(code, str, size) {
    return Container(
      margin: EdgeInsets.only(top: 3),
      constraints: BoxConstraints(minHeight: 20),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
              margin: EdgeInsets.only(right: 5),
              child: Icon(
                IconData(
                  code,
                  fontFamily: 'iconfont',
                ),
                color: BlackIconColor,
                size: size,
              )),
          Expanded(
              child: Container(
                  child: extendedText(
            str,
            selectionEnabled: false,
            color: Constants.BlackTextColor,
            emojisize: 17.0,
            fontSize: ScreenUtil().setSp(14),
            //fontWeight: FontWeight.w500,
          ))),
        ],
      ),
    );
  }

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

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

  Widget _buildIconButtonList(data) {
    bool isStop = data['Status'] == 1;
    //bool isSameSex = data['Sex'] == UserData().basicInfo.sex;
    //bool isMan = data['Sex'] == 1;
    bool isAd = data['Type'] == 2;
    Widget likeButton = _iconButton(
      0xe65b,
      data['IsFabulous'] > 0 ? Constants.BlueTextColor : BlackIconColor,
      // data['FabulousNum'] > 0
      //     ? data['FabulousNum'].toString()
      //     : I18n.of(context).thumbs_up3,
      I18n.of(context).thumbs_up3,
      isStop
          ? () {
              showToast(I18n.of(context).has_ended);
            }
          : data['IsFabulous'] > 0
              ? () {
                  showToast(I18n.of(context).already_praised);
                }
              : () async {
                  if (isAd) {
                    Map rdata = {
                      "userId": UserData().basicInfo.userId,
                      "adId": data['Id'],
                    };
                    rdata['sign'] = TokenMgr().getSign(rdata);

                    Response res = await HttpUtil().post('adActivity/give/like',
                        data: rdata, isShowLoading: true);
                    var resData = res.data;
                    if (resData['code'] == 0) {
                      setState(() {
                        data['FabulousNum']++;
                        data['IsFabulous']++;

                        widget.programInfo['FabulousList'].add({
                          "UserId": UserData().basicInfo.userId,
                          "Headimgurl": UserData().basicInfo.headimgurl
                        });
                      });
                    }
                  } else {
                    Map rdata = {
                      "userId": UserData().basicInfo.userId,
                      "id": data['Id'],
                    };
                    rdata['sign'] = TokenMgr().getSign(rdata);

                    Response res = await HttpUtil().post('station/give/like',
                        data: rdata, isShowLoading: true);
                    var resData = res.data;
                    if (resData['code'] == 0) {
                      setState(() {
                        data['FabulousNum']++;
                        data['IsFabulous']++;

                        widget.programInfo['FabulousList'].add({
                          "UserId": UserData().basicInfo.userId,
                          "Headimgurl": UserData().basicInfo.headimgurl
                        });
                      });
                    }
                  }
                },
      textColor:
          data['IsFabulous'] > 0 ? Constants.BlueTextColor : BlackIconColor,
    );
    // var str = data['EvaluateNum'] > 0
    //     ? data['EvaluateNum'].toString()
    //     : I18n.of(context).comment;
    Widget contentButton = _iconButton(
        0xe65d,
        isCloseContent && !isMyself
            ? BlackIconColor.withOpacity(0.5)
            : BlackIconColor,
        // !isCloseContent
        //     ? (isMyself ? str : I18n.of(context).comment)
        //     : isMyself ? str : I18n.of(context).comment_closed,
        !isCloseContent
            ? I18n.of(context).comment
            : I18n.of(context).comment_closed,
        isStop
            ? () {
                showToast(I18n.of(context).has_ended);
              }
            : (isCloseContent)
                ? () {
                    showToast(I18n.of(context).comment_closed);
                  }
                :
                // isSameSex && !isMyself
                //     ? () {
                //         showToast(isMan
                //             ? I18n.of(context).men_cant2
                //             : I18n.of(context).ms_cant2);
                //       }
                //     :
                () {
                    CustomUI.showContentDialog(context, data['Id'], 0, 0,
                        (data) {
                      widget.programInfo['EvaluateNum']++;
                      widget.programInfo['EvaluateList'].insert(0, data);

                      data['Id'] = widget.programInfo['Id'];
                      if (!isAd && widget.isDetail)
                        MessageMgr().emit('refresh_list', data);
                      setState(() {});
                    }, isAd: isAd, isMyself: isMyself);
                  },
        textColor: isCloseContent && !isMyself
            ? BlackIconColor.withOpacity(0.5)
            : BlackIconColor);

    Widget stopJoin = _iconButton(
        0xe65e,
        BlackIconColor,
        !isStop
            ? I18n.of(context).end_registration
            : I18n.of(context).has_ended,
        isStop
            ? null
            : () async {
                CustomUI.buildOneConfirm(context, I18n.of(context).end_choose,
                    I18n.of(context).determine, () async {
                  Map rdata = {
                    "userId": UserData().basicInfo.userId,
                    "id": data['Id'],
                  };
                  rdata['sign'] = TokenMgr().getSign(rdata);

                  Response res = await HttpUtil()
                      .post('station/fin/inscriptions', data: rdata);
                  var resData = res.data;
                  if (resData['code'] == 0) {
                    Navigator.of(context).pop();
                    UserData().isCanProgram = true;
                    showToast(resData['msg']);
                    MessageMgr().emit('refresh_list');
                    widget.programInfo['Status'] = 1;
                    setState(() {});
                  }
                });
              },
        iconSize: 18);

    Widget joinButton = _iconButton(
        0xe624,
        data['IsEnroll'] > 0 ? Colors.red : BlackIconColor,
        isMyself
            ? '${I18n.of(context).view_registration}(${data['EnrollNum']})'
            : '${I18n.of(context).sign_up2}(${data['EnrollNum']})',
        isMyself
            ? null
            :
            // isSameSex
            //     ? () {
            //         showToast(isMan
            //             ? I18n.of(context).men_cant
            //             : I18n.of(context).ms_cant);
            //       }
            //     :
            (data['IsEnroll'] > 0
                ? () {
                    showToast(I18n.of(context).alreay_join);
                  }
                : () async {
                    if ((UserData().isMan() && !UserData().isVip)) {
                      CustomUI.buildOneConfirm(
                          context,
                          I18n.of(context).cannot_join,
                          I18n.of(context).joinvip, () {
                        Navigator.of(context).pop();
                        Navigator.of(context).push(
                          new MaterialPageRoute(
                            builder: (context) {
                              return VipPage();
                            },
                          ),
                        );
                      });
                      return;
                    }
                    if ((!UserData().isMan() &&
                        !UserData().basicInfo.isAttestation)) {
                      CustomUI.buildNotTrue(context);
                      return;
                    }

                    CustomUI.buildOneConfirm(
                        context,
                        I18n.of(context).need_photo2,
                        I18n.of(context).choose_photo, () {
                      _sendPicture((url) async {
                        Map rdata = {
                          "userId": UserData().basicInfo.userId,
                          "id": data['Id'],
                        };
                        rdata['sign'] = TokenMgr().getSign(rdata);
                        rdata['imgUrl'] = url;
                        Response res = await HttpUtil()
                            .post('station/program/enroll', data: rdata);
                        var resData = res.data;
                        if (resData['code'] == 0) {
                          showToast(resData['msg']);
                          setState(() {
                            data['EnrollNum']++;
                            data['IsEnroll']++;
                          });
                        }
                      });
                    });
                  }),
        iconSize: 18);
    return Container(
      width: double.infinity,
      alignment: Alignment.center,
      height: 47,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: isProgram
            ? (isMyself
                ? [likeButton, contentButton, joinButton, stopJoin]
                : [likeButton, contentButton, joinButton])
            : [likeButton, contentButton],
      ),
    );
  }

  //动态消息框
  Widget _buildMessageBox(data) {
    bool isAd = data['Type'] == 2;
    return InkWell(
        onTap: () async {
          if (isAd) {
            if (await canLaunch(data['HopeObject'])) {
              await launch(data['HopeObject']);
            } else {
              throw 'Could not launch ${data['HopeObject']}';
            }
            return;
          }
          if (widget.isDetail) return;
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return ProgramDetailPage(
                  programId: data['Id'],
                );
              },
            ),
          );
        },
        child: Container(
          margin: EdgeInsets.only(top: 10),
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                  top: Constants.GreyBorderSide,
                  bottom: Constants.GreyBorderSide)),
          child: Column(
            children: <Widget>[
              _buildUserInfo(data),
              _buildTimebox(data),
              _buildImgSet(data),
              _buildImgList(data),
              widget.isDetail ? Container() : _buildDivder(),
              _buildIconButtonList(data),
              //_buildContent(),
            ],
          ),
        ));
  }

  Widget _buildDivder() {
    return Container(
        height: 1,
        margin: EdgeInsets.symmetric(horizontal: 21),
        decoration:
            BoxDecoration(border: Border(top: Constants.GreyBorderSide)));
  }

  // Widget _buildContent() {
  //   if (widget.programInfo['EvaluateList'].length == 0) {
  //     return Container();
  //   }
  //   List<Widget> list = [];
  //   var size = widget.programInfo['EvaluateList'].length >= 2
  //       ? 2
  //       : widget.programInfo['EvaluateList'].length;
  //   for (int i = 0; i < size; i++) {
  //     var data = widget.programInfo['EvaluateList'][i];
  //     list.add(_buildReply(data));
  //   }
  //   return Container(
  //       decoration: BoxDecoration(
  //           borderRadius: BorderRadius.only(
  //               bottomLeft: Radius.circular(10),
  //               bottomRight: Radius.circular(10))),
  //       child: Column(
  //         children: <Widget>[
  //           Container(
  //             padding: EdgeInsets.zero,
  //             margin:
  //                 EdgeInsets.only(left: 20, right: 20, top: 11.5, bottom: 14),
  //             height: 0.1,
  //             decoration: BoxDecoration(
  //                 border: Border(top: BorderSide(color: Color(0xFFF1F1F1)))),
  //           ),
  //           Container(
  //               margin: EdgeInsets.only(left: 24),
  //               decoration: BoxDecoration(
  //                   borderRadius: BorderRadius.only(
  //                       bottomLeft: Radius.circular(10),
  //                       bottomRight: Radius.circular(10))),
  //               child: Row(
  //                 crossAxisAlignment: CrossAxisAlignment.start,
  //                 children: <Widget>[
  //                   Column(
  //                     crossAxisAlignment: CrossAxisAlignment.start,
  //                     children: list,
  //                   )
  //                 ],
  //               ))
  //         ],
  //       ));
  // }

  // Widget _buildReply(data) {
  //   var content = ": ${data['Content'] == null ? '' : data['Content']} ";
  //   return Container(
  //     padding: EdgeInsets.only(left: 0, bottom: 3),
  //     width: Screen.width - 30,
  //     child: RichText(
  //       text: TextSpan(
  //           children: data['ReplyUserId'] == 0
  //               ? [
  //                   TextSpan(
  //                     text: Provider.of<RefNameProvider>(context)
  //                         .getRefName(data['UserId'], data['NickName']),
  //                     style: TextStyle(
  //                         fontSize: 12.5,
  //                         textBaseline: TextBaseline.alphabetic,
  //                         color: const Color(0xFF739BBC),
  //                         fontWeight: FontWeight.w500),
  //                   ),
  //                   TextSpan(
  //                     text: content,
  //                     style: TextStyle(
  //                         color: Constants.GreyTextColor,
  //                         textBaseline: TextBaseline.alphabetic,
  //                         fontSize: 12.5),
  //                   )
  //                 ]
  //               : [
  //                   TextSpan(
  //                     text: WebData().subUserName(
  //                         Provider.of<RefNameProvider>(context)
  //                             .getRefName(data['UserId'], data['NickName'])),
  //                     style: TextStyle(
  //                         fontSize: 12.5,
  //                         textBaseline: TextBaseline.alphabetic,
  //                         color: const Color(0xFF739BBC),
  //                         fontWeight: FontWeight.w500),
  //                   ),
  //                   TextSpan(
  //                     text: ' ${I18n.of(context).reply} ',
  //                     style: TextStyle(
  //                         fontSize: 12.5,
  //                         textBaseline: TextBaseline.alphabetic,
  //                         color: Constants.GreyTextColor,
  //                         fontWeight: FontWeight.w500),
  //                   ),
  //                   TextSpan(
  //                     text: WebData().subUserName(data['ReplyNickName']),
  //                     style: TextStyle(
  //                         fontSize: 12.5,
  //                         textBaseline: TextBaseline.alphabetic,
  //                         color: const Color(0xFF739BBC),
  //                         fontWeight: FontWeight.w500),
  //                   ),
  //                   TextSpan(
  //                     text: content,
  //                     style: TextStyle(
  //                         color: Constants.GreyTextColor,
  //                         textBaseline: TextBaseline.alphabetic,
  //                         fontSize: 12.5),
  //                   )
  //                 ]),
  //     ),
  //   );
  // }

  Widget _buildTimebox(data) {
    return Container(
      padding: EdgeInsets.only(left: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          isProgram
              ? _iconRow(0xe636,
                  WebData().getProgramName(context, data['ProgramType']), 16.0)
              : Container(),
          isProgram
              ? _iconRow(
                  0xe635,
                  '${data['AboutTime'].split(' ')[0]} ${WebData().getDateString(context, data['timeQuantum'])}',
                  16.0)
              : Container(),
          isProgram
              ? _iconRow(
                  0xe617,
                  '${I18n.of(context).expect_lover}:${WebData().getLovePeople(data['HopeObject'])}',
                  16.0)
              : Container(),
          _buildTextContent(data),
        ],
      ),
    );
  }

  bool isExpansion(String text) {
    double width = Screen.width - 25;
    TextPainter _textPainter = TextPainter(
        maxLines: 2,
        text: TextSpan(
            text: text, style: TextStyle(fontSize: 16.0, color: Colors.black)),
        textDirection: TextDirection.ltr)
      ..layout(maxWidth: width, minWidth: width);
    if (_textPainter.didExceedMaxLines) {
      //这里判断 文本是否截断
      return true;
    } else {
      return false;
    }
  }

  Widget _buildTextContent(data) {
    if (data['Content'] == null || data['Content'] == '') {
      return Container();
    }
    bool showAllContent = isExpansion(data['Content']);
    return Container(
        margin: EdgeInsets.only(right: 10, top: 5),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              extendedText(
                data['Content'],
                selectionEnabled: false,
                color: Constants.BlackTextColor,
                emojisize: 17.0,
                maxLines: isShowAll ? 10 : 2,
                fontSize: ScreenUtil().setSp(14),
                fontWeight: FontWeight.w500,
              ),
              showAllContent
                  ? InkWell(
                      onTap: () {
                        setState(() {
                          isShowAll = !isShowAll;
                        });
                      },
                      child: Container(
                          padding: EdgeInsets.only(top: 5),
                          child: Row(
                            children: <Widget>[
                              Text(
                                !isShowAll
                                    ? I18n.of(context).expand
                                    : I18n.of(context).collapse,
                                textScaleFactor: 1.0,
                                style: TextStyle(
                                    fontSize: 15,
                                    color: Constants.BlueTextColor),
                              ),
                              Icon(
                                  !isShowAll
                                      ? Icons.keyboard_arrow_down
                                      : Icons.keyboard_arrow_up,
                                  size: 24,
                                  color: Constants.BlueTextColor),
                            ],
                          )))
                  : Container(),
            ]));
  }

  Widget _buildBigImg(int id, List imgList, width, height) {
    return InkWell(
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return PicSwiper(
                  id: id,
                  pics: imgList
                      .map<PicSwiperItem>(
                          (f) => PicSwiperItem(f, id: imgList.indexOf(f)))
                      .toList(),
                );
              },
            ),
          );
        },
        child: Container(
          height: height,
          width: width,
          child: CachedNetworkImage(
            imageUrl: imgList[id] == null ? "" : imgList[id],
            placeholder: CustomUI.buildImgLoding,
            fit: BoxFit.cover,
          ),
        ));
  }

  Widget _buildImgSet(data) {
    double height = 254.5;
    List imgList = (data['ImgUrl'] == '' || data['ImgUrl'] == null)
        ? []
        : data['ImgUrl'].split('|');
    Widget result;
    switch (imgList.length) {
      case 1:
        result = _buildBigImg(0, imgList, Screen.width, height);
        break;
      case 2:
        double paddingWidth = 3;
        double imgWidth = (Screen.width - paddingWidth) / 2;
        result = Row(
          children: <Widget>[
            _buildBigImg(0, imgList, imgWidth, height),
            SizedBox(
              width: paddingWidth,
            ),
            _buildBigImg(1, imgList, imgWidth, height)
          ],
        );
        break;
      case 3:
        double paddingWidth = 3;
        double imgWidth = (Screen.width - paddingWidth) / 2;
        double imgHeight = (height - paddingWidth) / 2;
        result = Row(
          children: <Widget>[
            _buildBigImg(0, imgList, imgWidth, height),
            SizedBox(width: paddingWidth),
            Column(
              children: <Widget>[
                _buildBigImg(1, imgList, imgWidth, imgHeight),
                SizedBox(height: paddingWidth),
                _buildBigImg(2, imgList, imgWidth, imgHeight),
              ],
            ),
          ],
        );
        break;
      case 4:
        double paddingWidth = 3;
        double imgWidth = (Screen.width - paddingWidth) / 2;
        double imgHeight = (height - paddingWidth) / 2;
        result = Row(
          children: <Widget>[
            Column(
              children: <Widget>[
                _buildBigImg(0, imgList, imgWidth, imgHeight),
                SizedBox(height: paddingWidth),
                _buildBigImg(1, imgList, imgWidth, imgHeight),
              ],
            ),
            SizedBox(width: paddingWidth),
            Column(
              children: <Widget>[
                _buildBigImg(2, imgList, imgWidth, imgHeight),
                SizedBox(height: paddingWidth),
                _buildBigImg(3, imgList, imgWidth, imgHeight),
              ],
            ),
          ],
        );
        break;
      default:
        result = Container();
    }

    return Padding(padding: EdgeInsets.only(top: 5), child: result);
  }

  Widget _buildImg(data) {
    double width = 25;
    return InkWell(
        onTap: data['UserId'] == UserData().basicInfo.userId
            ? null
            : () {
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return ProfilePage(
                        userId: data['UserId'],
                      );
                    },
                  ),
                );
              },
        child: Container(
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(2.0)),
            width: width,
            height: width,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(30),
              child: CachedNetworkImage(
                imageUrl: data['Headimgurl'] == null ? '' : data['Headimgurl'],
                placeholder: (context, url) => Image.asset(
                  Constants.DefaultHeadImgUrl,
                  width: width,
                  height: width,
                ),
                fit: BoxFit.cover,
              ),
            )));
  }

  Widget _buildImgList(programInfo) {
    int pictureNum = programInfo['FabulousList'].length >= 3
        ? 3
        : programInfo['FabulousList'].length;
    List<Widget> list = [
      Container(height: 30, width: 30, margin: EdgeInsets.only(top: 10))
    ];
    if (pictureNum != 0) {
      list.add(_buildImg(programInfo['FabulousList'][0]));
      for (int i = 1; i < pictureNum; i++) {
        list.add(Positioned(
          left: 15.0 * i,
          child: _buildImg(programInfo['FabulousList'][i]),
        ));
      }
      if (programInfo['FabulousList'].length > 3) {
        list.add(Positioned(
            left: 70,
            child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Colors.grey[400],
                    borderRadius: BorderRadius.circular(20.0)),
                width: 25,
                height: 25,
                child: Text(
                  '+${programInfo['FabulousList'].length - pictureNum}',
                  textScaleFactor: 1.0,
                  style: TextStyle(color: Colors.white, fontSize: 13),
                ))));
      }
    }

    return Container(
        height: 37.5,
        padding: EdgeInsets.only(top: 0, left: 15, right: 23),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: Stack(
                alignment: Alignment.centerLeft,
                children: list,
              ),
            ),
            Container(
              child: Text(
                I18n.of(context)
                    .content_num
                    .replaceFirst('/s1', programInfo['EvaluateNum'].toString()),
                style: TextStyle(fontSize: 12, color: BlackIconColor),
              ),
            ),
          ],
        ));
  }

  Widget _buildUserInfo(data) {
    Color greColor = Color(0xFF5A5A5A);
    Widget otherPop = myPopUp.PopupMenuButton<String>(
      offset: Offset(-10, 40),
      child: Container(
          margin: EdgeInsets.only(right: 10),
          padding: EdgeInsets.only(left: 8, right: 8, top: 0, bottom: 0),
          decoration: BoxDecoration(
              //border: Border.all(color: greColor),
              borderRadius: BorderRadius.all(Radius.circular(8))),
          child: Icon(
            IconData(0xe621, fontFamily: Constants.IconFontFamily),
            color: greColor,
            size: 12,
          )),
      onSelected: (str) {
        _selectValue(str, data['UserId'], isProgram);
      },
      itemBuilder: (BuildContext context) => <myPopUp.PopupMenuEntry<String>>[
        myPopUp.PopupMenuItem<String>(
          value: 'inform',
          child: Container(
              margin: EdgeInsets.only(top: 10, bottom: 10),
              child: fixedText(I18n.of(context).anonymous_report,
                  fontSize: 14, color: Constants.BlackTextColor)),
        )
      ],
    );

    Widget myPop = myPopUp.PopupMenuButton<String>(
      offset: Offset(0, 40),
      padding: EdgeInsets.zero,
      child: Container(
          //margin: EdgeInsets.only(right: 10),
          padding: EdgeInsets.only(left: 18, right: 18, top: 3, bottom: 3),
          decoration: BoxDecoration(

              //border: Border.all(color: greColor),
              borderRadius: BorderRadius.all(Radius.circular(8))),
          child: Icon(
            IconData(0xe621, fontFamily: Constants.IconFontFamily),
            color: greColor,
            size: 12,
          )),
      onSelected: (str) {
        _selectValue(str, data['Id'], isProgram);
      },
      itemBuilder: (BuildContext context) => <myPopUp.PopupMenuEntry<String>>[
        !isCloseContent
            ? myPopUp.PopupMenuItem<String>(
                value: 'noContent',
                child: Container(
                    margin: EdgeInsets.only(top: 10, bottom: 10),
                    child: fixedText(I18n.of(context).prohibit_comments,
                        fontSize: 15, color: Constants.BlackTextColor)))
            : myPopUp.PopupMenuItem<String>(
                value: 'openContent',
                child: Container(
                    margin: EdgeInsets.only(top: 10, bottom: 10),
                    child: fixedText(I18n.of(context).open_comments,
                        fontSize: 15, color: Constants.BlackTextColor))),
        const myPopUp.PopupMenuDivider(
          height: 1,
        ),
        myPopUp.PopupMenuItem<String>(
          value: 'delete',
          child: Container(
              margin: EdgeInsets.only(top: 10, bottom: 10),
              child: fixedText(I18n.of(context).delete,
                  fontSize: 15, color: Constants.BlackTextColor)),
        ),
      ],
    );
    bool isMan = data['Sex'] == 1;
    bool isVip = data['IsMember'] > 0;
    bool isSVIP = data['IsMember'] == 2;
    bool isAd = data['Type'] == 2;
    double imgHeight = 45.6;

    return Container(
      margin: EdgeInsets.only(top: 5, bottom: 10),
      child: Stack(children: <Widget>[
        InkWell(
            onTap: () async {
              if (isAd) {
                if (await canLaunch(data['HopeObject'])) {
                  await launch(data['HopeObject']);
                } else {
                  throw 'Could not launch ${data['HopeObject']}';
                }
                return;
              }
              if (data['UserId'] == UserData().basicInfo.userId) {
                return;
              }
              // if (data['Sex'] == UserData().basicInfo.sex) {
              //   showToast(UserData().isMan()
              //       ? I18n.of(context).cant_see
              //       : I18n.of(context).cant_see2);
              //   return;
              // }
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return ProfilePage(
                      userId: data['UserId'],
                    );
                  },
                ),
              );
            },
            child: Stack(
              children: <Widget>[
                Padding(
                    padding: EdgeInsets.only(
                        top: 8.5, right: 19, left: 15, bottom: 0),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(imgHeight),
                      child:
                          data['HeadimgUrl'] == null || data['HeadimgUrl'] == ''
                              ? Image.asset(
                                  Constants.DefaultHeadImgUrl,
                                  width: imgHeight,
                                  height: imgHeight,
                                )
                              : CachedNetworkImage(
                                  height: imgHeight,
                                  width: imgHeight,
                                  imageUrl: data['HeadimgUrl'],
                                  placeholder: (context, url) => Image.asset(
                                    Constants.DefaultHeadImgUrl,
                                    width: imgHeight,
                                    height: imgHeight,
                                  ),
                                  fit: BoxFit.cover,
                                ),
                    )),
                Positioned(
                    right: 15,
                    bottom: 0,
                    child: Container(
                      padding: EdgeInsets.only(bottom: 1.3, left: 0.5),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(20))),
                      child: Icon(
                        IconData(
                          isMan ? 0xe639 : 0xe638,
                          fontFamily: 'iconfont',
                        ),
                        color: isMan
                            ? const Color(0xff0072ff)
                            : const Color(0xffff0486),
                        size: 13,
                      ),
                    ))
              ],
            )),
        Container(
            margin: EdgeInsets.only(top: 3, left: imgHeight + 31),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(height: 5),
                Row(
                  children: <Widget>[
                    Container(
                        child: Text(
                      data['NickName'] == null || data['NickName'] == ''
                          ? ''
                          : WebData().subUserName(
                              Provider.of<RefNameProvider>(context).getRefName(
                                  data['UserId'], data['NickName'])),
                      textScaleFactor: 1.0,
                      style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                    )),
                    data['IsAttestation'] == 1 && !isMan
                        ? Container(
                            margin: EdgeInsets.only(left: 5),
                            padding: EdgeInsets.only(
                                top: 2, bottom: 2, left: 5, right: 5),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(3),
                              color: Constants.PurpleBackgroundColor,
                            ),
                            child: Text(
                              'Real',
                              textScaleFactor: 1.0,
                              style:
                                  TextStyle(fontSize: 8, color: Colors.white),
                            ))
                        : Text(''),
                    isVip && isMan
                        ? Container(
                            margin: EdgeInsets.only(left: 5),
                            child:
                                isSVIP ? Constants.svipIcon : Constants.vipIcon)
                        : Container(),
                    Expanded(
                      child: Align(
                        alignment: Alignment.centerRight,
                        child: isAd
                            ? Container(
                                margin: EdgeInsets.only(right: 10),
                                padding: EdgeInsets.symmetric(
                                    horizontal: 5.5, vertical: 2.5),
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(3),
                                    border: Border.all(color: Colors.grey)),
                                child: Text(I18n.of(context).ad,
                                    style: TextStyle(
                                        fontSize: 9, color: Colors.grey)),
                              )
                            : Container(),
                      ),
                    ),
                    !isAd
                        ? Container(
                            alignment: Alignment.centerRight,
                            child: isMyself ? myPop : otherPop)
                        : Container(),
                  ],
                ),
                SizedBox(height: 8),
                Row(
                  children: <Widget>[
                    Text(
                      WebData().getLoginTime(context, data['CreateTime']),
                      style: TextStyle(
                          color: const Color(0xFF5C5C5C), fontSize: 12),
                    ),
                    Expanded(
                      child: isMyself
                          ? Align(
                              alignment: Alignment.centerRight,
                              child: Container(
                                margin: EdgeInsets.only(right: 10),
                                padding: EdgeInsets.only(
                                    left: 4, right: 4, top: 3, bottom: 3),
                                decoration: BoxDecoration(
                                  color: Colors.grey[200],
                                  borderRadius: BorderRadius.circular(10.0),
                                ),
                                child: Text(
                                  I18n.of(context).i_posted,
                                  style: TextStyle(
                                    fontSize: 10,
                                    color: Colors.grey[600],
                                  ),
                                ),
                              ))
                          : Container(),
                    )
                  ],
                )
              ],
            )),
      ]),
    );
  }
}
