import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/chat/emoji_text.dart';
import 'package:chat/chat/input_bar.dart';
import 'package:chat/chat/my_special_text_span_builder.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/MyDialogContent.dart';
import 'package:chat/home/SelectPage.dart';
import 'package:chat/home/VerificationCenter.dart';
import 'package:chat/home/VipPage.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/utils/ChargeMoney.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/file_cache_mgr.dart';
import 'package:chat/utils/keyboard/bottom_area_avoider.dart';
import 'package:chat/utils/keyboard_utils.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:multi_image_picker/multi_image_picker.dart';

import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/ShadowButton.dart';
import '../data/UserData.dart';
import '../utils/TokenMgr.dart';
import '../data/WebData.dart';

class AddProgram extends StatefulWidget {
  @required
  final bool isProgram;

  AddProgram({Key key, this.isProgram = true}) : super(key: key);

  _AddProgramState createState() => _AddProgramState();
}

const double LEFT_WIDTH = 80;

const int Max_Img_Num = 4;

class _AddProgramState extends State<AddProgram> {
  //期待对象
  String lovePeople = "";
  Set<String> lovePeopleId = new Set();

  //约会范围
  String dateRange = "";
  Set<String> dateRangeId = new Set();

  //开始时间
  String beginTime = '';
  String beginTimeId = '';

  //结束时间
  String endTime = '';
  var endTimeId = -1;

  //List<File> imgFileList = [];

  //上传图片地址
  List<String> imgUrlList = [];

  //禁止评论
  bool isCanContent = false;
  bool isHidden = false;

  int programId = -1;

  String programCat = '';

//  String content = '';

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

    print('AddProgram initState');

    _bloc.start();
    getKeyboardHeight();
    focusNode.addListener(_focusNodeListener);
    msgMgr.on('Keyboard Hide', dealWithKeyboardHide);
  }

  @override
  void dispose() {
    focusNode.removeListener(_focusNodeListener);
    _bloc.dispose();
    msgMgr.off('Keyboard Hide', dealWithKeyboardHide);

    super.dispose();
  }

  ///keyboard相关-----------------------------------------------------------------------------------------------
  KeyboardBloc _bloc = KeyboardBloc();
  MessageMgr msgMgr = MessageMgr();
  double keyboardHeight;
  final _keyParent = GlobalKey();
  double _offset = 0;
  Duration _timeToDismiss = Duration(milliseconds: 120);
  OverlayEntry _overlayEntry;
  FocusNode focusNode = new FocusNode();

  bool get _isShowing {
    return _overlayEntry != null;
  }

  bool isShowEmoji = false;
  bool _dismissAnimationNeeded = true;
  double _kBarSize = 45.0;
  bool isActionFromButton = false;

  dealWithKeyboardHide(args) {
    if (!isActionFromButton) {
      closeEmojiAction();
    }
  }

  TextEditingController _textCtrl = TextEditingController();
  final ValueNotifier<bool> _counter = ValueNotifier<bool>(false);

  void _insertOverlay() {
    print('插入界面');
    OverlayState os = Overlay.of(context);
    _overlayEntry = OverlayEntry(builder: (context) {
      // Update and build footer, if any

      final queryData = MediaQuery.of(context);
      return Positioned(
        bottom: queryData.viewInsets.bottom,
        left: 0,
        right: 0,
        child: SafeArea(
          child: Container(
            height: _kBarSize,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Material(
                  color: Colors.grey[200],
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Divider(
                        height: 1,
                        color: Color(0xffb0b0b0),
                      ),
                      InkWell(
                        child: Container(
                          padding: EdgeInsets.only(left: 15),
                          height: 43,
                          color: Colors.white,
                          alignment: Alignment.centerLeft,
                          child: Icon(
                              IconData(isShowEmoji ? 0xe655 : 0xe651,
                                  fontFamily: Constants.IconFontFamily),
                              size: 27,
                              color: Color(0xffb0b0b0)),
                        ),
                        onTap: () {
                          setState(() {
                            isActionFromButton = true;
                            isShowEmoji = !isShowEmoji;
                            _kBarSize = isShowEmoji ? keyboardHeight : 45;

                            if (isShowEmoji) {
                              SystemChannels.textInput
                                  .invokeMethod('TextInput.hide');
                            } else {
                              SystemChannels.textInput
                                  .invokeMethod('TextInput.show');
                            }
                            if (isShowEmoji) {
                              Future.delayed(Duration(milliseconds: 200), () {
                                ///150延迟防止界面越界
                                _counter.value = isShowEmoji;
                              });

                              Future.delayed(Duration(milliseconds: 1000), () {
                                ///缩下键盘的时候-防止表情被关闭
                                isActionFromButton = false;
                              });
                            } else {
                              _counter.value = isShowEmoji;
                              Future.delayed(Duration(milliseconds: 360), () {
                                ///150延迟防止界面越界
                                isActionFromButton = false;
                              });
                            }
                          });
                        },
                      ),
                      ValueListenableBuilder(
                        builder:
                            (BuildContext context, bool value, Widget child) {
                          return value
                              ? Container(
                                  width: MediaQuery.of(context).size.width,
                                  child: buildEmojiGird(),
                                )
                              : SizedBox(
                                  height: 1,
                                );
                        },
                        valueListenable: _counter,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    });
    os.insert(_overlayEntry);
  }

  getKeyboardHeight() async {
    var sp = await SharedPreferences.getInstance();
    keyboardHeight = sp.getDouble(Constants.KeyboardHeight);
    print('keyboardHeight : $keyboardHeight');
  }

  Future<Null> _focusNodeListener() async {
    print('监听');

    if (isShowEmoji) {
      return;
    }
    _focusChanged(focusNode.hasFocus);
  }

  _focusChanged(bool showBar) {
    print('showBar $showBar _isShowing:$_isShowing');
    if (showBar && !_isShowing) {
      _insertOverlay();
    } else if (!showBar && _isShowing) {
      _removeOverlay();
    } else if (showBar && _isShowing) {
      _overlayEntry.markNeedsBuild();
    }
  }

  /// Remove the overlay bar. Call when losing focus or being dismissed.
  void _removeOverlay({bool fromDispose = false}) async {
    if (_dismissAnimationNeeded) {
      if (mounted && !fromDispose) {
        _overlayEntry?.markNeedsBuild();
        await Future.delayed(_timeToDismiss);
      }
    }
    _overlayEntry?.remove();
    _overlayEntry = null;
    if (!fromDispose && _dismissAnimationNeeded) _updateOffset();
    _dismissAnimationNeeded = true;
  }

  void _updateOffset() {
    if (!mounted) {
      return;
    }

    if (!_isShowing) {
      setState(() {
        _offset = 0.0;
      });
      return;
    }

    double newOffset = _kBarSize; // offset for the actions bar
    newOffset += MediaQuery.of(context)
        .viewInsets
        .bottom; // + offset for the system keyboard

    if (newOffset < 0) newOffset = 0;

    // Update state if changed
    if (_offset != newOffset) {
      setState(() {
        _offset = newOffset;
      });
    }
  }

  Widget buildEmojiGird() {
    return Container(
      height: keyboardHeight - 44,
      child: Stack(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(5, 8, 50, 0),
            child: GridView.builder(
              controller: new ScrollController(keepScrollOffset: false),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 7, crossAxisSpacing: 0, mainAxisSpacing: 0),
              itemBuilder: (context, index) {
                return GestureDetector(
                  child: Container(
                    padding: EdgeInsets.all(7),
                    child: Image.asset(EmojiUitl
                        .instance.emojiMap[EmojiText.flag + "${index + 1}]"]),
                  ),
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    if (_textCtrl.value.text.length < 94) {
                      InputBarState.insertText(
                          EmojiText.flag + "${index + 1}]", _textCtrl);
                    }

//                    setState(() {
//                      _isComposingMessage = _textCtrl.text.length > 0;
//                    });
                  },
                );
              },
              itemCount: EmojiUitl.instance.emojiMap.length,
              padding: EdgeInsets.all(5.0),
            ),
          ),
          Positioned.fill(
              child: Container(
            padding: EdgeInsets.fromLTRB(0, 0, 0, 14),
            alignment: Alignment(1, 1),
            child: InkWell(
              onTap: () {
                InputBarState.deleteText(_textCtrl);
              },
              child: Container(
                decoration: BoxDecoration(
                    color: Color(0x4d0E0E10),
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(4.0),
                        bottomLeft: Radius.circular(4))),
                width: 37,
                height: 28,
                child: Icon(
                  IconData(
                    0xe679,
                    fontFamily: 'iconfont',
                  ),
                  size: 16,
                  color: Colors.white,
                ),
              ),
            ),
          )),
        ],
      ),
    );
  }

  ///keyboard相关------------------------------------------------------------------------------------------------------------

  void closeEmojiAction() {
    print('### closeEmojiAction');
    FocusScope.of(context).requestFocus(FocusNode());
    isShowEmoji = false;
    _counter.value = isShowEmoji;
    _removeOverlay();
    _offset = 0;
    _kBarSize = isShowEmoji ? keyboardHeight : 45;
  }

  ScrollController _scrollController = new ScrollController();

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: Text(
        widget.isProgram
            ? I18n.of(context).release_program
            : I18n.of(context).release_dynamics,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
      elevation: 0,
      leading: CustomUI.buildCustomLeading(context, onTap: () {
        closeEmojiAction();
        Navigator.of(context).pop();
      }),
      centerTitle: true,
    );
    return WillPopScope(
        child: Scaffold(
          appBar: appBar,
          body: SafeArea(
              child: Center(
            child: Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: GestureDetector(
                onTap: () {
                  closeEmojiAction();
                },
                child: Material(
                  color: Colors.transparent,
                  child: SizedBox(
                    width: double.maxFinite,
                    key: _keyParent,
                    child: BottomAreaAvoider(
                      scrollTo: _scrollController,
                      areaToAvoid: _offset,
                      duration: Duration(
                          milliseconds:
                              (_timeToDismiss.inMilliseconds * 1.8).toInt()),
                      autoScroll: true,
                      child: Container(
                        child: Column(
                          children: <Widget>[_buildBody()],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          )),
        ),
        onWillPop: () {
          closeEmojiAction();

          return Future.value(true);
        });
  }

//  Future<bool> _willPop() {
//    print('###### willpop');
////    tempDispose=true;
////    closeEmojiAction();
////    print('isshowemoji:$isShowEmoji');
////    _counter.value = false;
////    print('关闭emoji');
////    FocusScope.of(context).requestFocus(FocusNode());
//    Navigator.pop(context);
//    return new Future.value(false);
//  }

  BoxDecoration _getCardDecoration() {
    return new BoxDecoration(
      color: Colors.white,
      boxShadow: [
        BoxShadow(
          color: Color.fromRGBO(230, 230, 230, 1),
          offset: Offset(0, 10),
          blurRadius: 8,
        )
      ],
    );
  }

  //节目主题
  Widget _buildProgramCat() {
    return new Container(
      margin: EdgeInsets.only(top: 15),
      decoration: _getCardDecoration(),
      child: _bottomBorderBox(
          I18n.of(context).program_theme,
          programCat == '' ? I18n.of(context).choose : programCat,
          false,
          null, () {
        CustomUI.buildTip(
            context, I18n.of(context).please_choose, _buildCategoryButton());
      }, rightTextGrey: programCat == ''),
    );
  }

  //选择期待对象
  void selectLovePeople() {
    var tempSet = lovePeopleId.toSet();
    List<Widget> actions = [
      FlatButton(
        child: fixedText(I18n.of(context).close),
        onPressed: () {
          tempSet.clear();
          Navigator.of(context).pop();
        },
      ),
      FlatButton(
        child: fixedText(I18n.of(context).determine),
        onPressed: () {
          Navigator.of(context).pop();
          setState(() {
            lovePeopleId = tempSet.toSet();
            lovePeople = '';
            lovePeopleId.forEach((k) {
              lovePeople += (lovePeople == '')
                  ? WebData().loverPeopleMap[k]
                  : ('/' + WebData().loverPeopleMap[k]);
            });
          });
        },
      ),
    ];
    //约会节目
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: new Align(
              alignment: Alignment.center,
              child: Text(I18n.of(context).expect_lover, textScaleFactor: 1.0),
            ),
            content: new MyDialogContent(
              mostNum: 4,
              dataMap: WebData().loverPeopleMap,
              keyList: tempSet,
            ),
            contentPadding: EdgeInsets.only(top: 10),
            actions: actions,
          );
        });
  }

  //选择约会地区
  void selectDateRange() async {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return SelectPage(
            mostNum: 4,
            dataId: dateRangeId,
            title: I18n.of(context).select_city,
            provinces: {'VietNam': WebData().provinces['VietNam']},
            cities: WebData().cities,
            isSingle: true,
            callback: (tempRankId) {
              dateRangeId = tempRankId.toSet();
              dateRange = '';
              dateRangeId.forEach((item) {
                var city = item.split('-');
                dateRange += dateRange == ''
                    ? WebData().cities[city[0]][city[1]]
                    : '/${WebData().cities[city[0]][city[1]]}';
              });
              Navigator.of(context).pop();
            },
          );
        },
      ),
    );
  }

  //选择开始时间
  void selectBegin() async {
    DateTime _date = DateTime.now();
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: _date,
        firstDate: DateTime(_date.year, _date.month, _date.day),
        locale: WebData().locale,
        lastDate: DateTime(_date.year, _date.month, _date.day + 7));
    setState(() {
      if (picked != null) {
        beginTime = '${picked.year}-${picked.month}-${picked.day}';
        beginTimeId = '${picked.year}-${picked.month}-${picked.day}';
      }
    });
    if (picked == null) _date = DateTime.now();
  }

  //分类按钮
  Widget _buildCategoryButton() {
    return Container(
        padding: EdgeInsets.only(top: 10),
        child: Column(
          children: <Widget>[
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  _buildIconButton(1, WebData().getProgramName(context, 0),
                      Constants.Category1Color, 0),
                  _buildIconButton(2, WebData().getProgramName(context, 1),
                      Constants.Category2Color, 1),
                  _buildIconButton(3, WebData().getProgramName(context, 2),
                      Constants.Category3Color, 2),
                  _buildIconButton(4, WebData().getProgramName(context, 3),
                      Constants.Category4Color, 3),
                ],
              ),
            ),
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  _buildIconButton(5, WebData().getProgramName(context, 4),
                      Constants.Category5Color, 4),
                  _buildIconButton(6, WebData().getProgramName(context, 5),
                      Constants.Category6Color, 5),
                  _buildIconButton(7, WebData().getProgramName(context, 6),
                      Constants.Category7Color, 6),
                  _buildIconButton(8, WebData().getProgramName(context, 7),
                      Constants.Category8Color, 7),
                ],
              ),
            ),
          ],
        ));
  }

  Widget _buildIconButton(iconNum, str, strColor, value) {
    Widget icon = Container(
        padding: EdgeInsets.only(bottom: 10),
        child: Image.asset(
          'assets/images/park/qz_icon$iconNum.png',
          height: 60,
        ));

    Widget text = Positioned(
        bottom: 0,
        child: Container(
          child: new Text(str,
              textScaleFactor: 1.0,
              style: TextStyle(
                  color: strColor, fontWeight: FontWeight.w700, fontSize: 13)),
        ));
    return InkWell(
        onTap: () {
          setState(() {
            programId = value;
            programCat = WebData().getProgramName(context, value);
            Navigator.of(context).pop();
          });
        },
        highlightColor: Colors.transparent,
        radius: 0,
        child: Container(
          width: (MediaQuery.of(context).size.width * 0.9) / 4,
          margin: EdgeInsets.only(top: 10),
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              icon,
              text,
            ],
          ),
        ));
  }

  Widget _buildTimeSelect(str, value) {
    return InkWell(
      child: Container(
        margin: EdgeInsets.only(top: 5, bottom: 5),
        height: 20,
        alignment: Alignment.center,
        child: Text(
          str,
          textScaleFactor: 1.0,
          style: TextStyle(fontSize: 15, color: Constants.BlackTextColor),
        ),
      ),
      onTap: () async {
        if (WebData().testTimeOver(value, beginTimeId)) {
          showToast(I18n.of(context).outTime);
          return;
        }
        setState(() {
          endTimeId = value;
          endTime = str;
          Navigator.of(context).pop();
        });
      },
    );
  }

  //选择结束时间
  void selectEnd() async {
    Widget title = Container(
      margin: EdgeInsets.only(top: 15, bottom: 10),
      alignment: Alignment.center,
      child: Text(
        I18n.of(context).select_time,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 19, color: Constants.BlackTextColor),
      ),
    );
    List<Widget> list = [title];
    WebData().getDateTime(context).forEach((k, v) {
      list.add(Divider());
      list.add(_buildTimeSelect(v, k));
    });
    if (beginTimeId == '') {
      showToast(I18n.of(context).please_choose4);
      return;
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
            child: Container(
          height: 345,
          child: Column(children: list),
        ));
      },
    ).then((val) {});
  }

  void _sendPicture() async {
    closeEmojiAction();

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

      resultList = await MultiImagePicker.pickImages(
        maxImages: Max_Img_Num - imgUrlList.length,
        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": 3, "userId": UserData().basicInfo.userId};
      data['sign'] = TokenMgr().getSign(data);
      Response res = await HttpUtil().uploadFiles(
          fileList, data, 'upload/post/postfiles', 'image',
          isShowLoading: true);
        var resData = res.data;
        if (resData['code'] == 0 && resData['msg'] != null) {
          imgUrlList.addAll(resData['msg'].split("|"));
          setState(() {});
        }
      }


//    var photos = await PhotoPicker.pickAsset(
//        context: context,
//        themeColor: Color(0xFFF0F0F0),
//        maxSelected: Max_Img_Num - imgUrlList.length,
//        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": 3, "userId": UserData().basicInfo.userId};
//      data['sign'] = TokenMgr().getSign(data);
//      Response res = await HttpUtil().uploadFiles(
//          fileList, data, 'upload/post/postfiles', 'image',
//          isShowLoading: true);
//      var resData = res.data;
//      if (resData['code'] == 0 && resData['msg'] != null) {
//        imgUrlList.addAll(resData['msg'].split("|"));
//        setState(() {});
//      }
//    }
  }

  Widget _buildDynicContent() {
    Widget moreInfo = Container(
        alignment: Alignment.topCenter,
        padding: EdgeInsets.only(left: 15, right: 15),
        child: ExtendedTextField(
          keyboardAppearance: Brightness.light,
          onTap: () {
//            if(!isActionFromButton){
            isShowEmoji = false;
            _counter.value = isShowEmoji;
            _kBarSize = isShowEmoji ? keyboardHeight : 45;
//            }
          },
          focusNode: focusNode,
          specialTextSpanBuilder:
              MySpecialTextSpanBuilder(showAtBackground: true, emojiSize: 17.0),
          decoration: new InputDecoration(
            hintText: I18n.of(context).please_civilization,
            hintStyle: TextStyle(fontSize: 13, height: 1.25),
            border: InputBorder.none,
          ),
          maxLines: 6,
          controller: _textCtrl,
          style: TextStyle(
              fontSize: ScreenUtil().setSp(14),
              textBaseline: TextBaseline.alphabetic),
          inputFormatters: [LengthLimitingTextInputFormatter(100)],
          onChanged: (str) {
            if (str.length > 100) {
              print('超过100了');
              _textCtrl.text = _textCtrl.value.text.substring(0, 100);
              int length = _textCtrl.text.length;
              Future.delayed(Duration(milliseconds: 100), () {
                _textCtrl.selection =
                    TextSelection(baseOffset: length, extentOffset: length);
              });
            }
          },
        ));

    List<Widget> imgList = imgUrlList.map((f) {
      return _buildImg(f);
    }).toList();
    if (imgList.length < Max_Img_Num) {
      imgList.add(_buildUpButton());
    }

    Widget picture = Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 15, bottom: 15),
        child: Wrap(alignment: WrapAlignment.start, children: imgList));
    List<Widget> list = [moreInfo, picture];
    return new Container(
      margin: EdgeInsets.only(top: 15),
      decoration: _getCardDecoration(),
      child: Column(
        children: list,
      ),
    );
  }

  Widget _buildUpButton() {
    var color = Colors.grey[350];
    return Container(
        child: InkWell(
            onTap: _sendPicture,
            child: Container(
                margin: EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.0),
                    border: Border.all(color: color)),
                width: 75,
                height: 75,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Icon(
                      IconData(
                        0xe616,
                        fontFamily: 'iconfont',
                      ),
                      color: color),
                ))));
  }

  //节目内容
  Widget _buildProgramContent() {
    Widget moreInfo = Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Container(
              width: Screen.width,
              padding: EdgeInsets.only(
                top: 15,
              ),
              margin: EdgeInsets.only(left: 15),
              child: Text(
                I18n.of(context).describe_details,
                textScaleFactor: 1.0,
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
              )),
          Container(
              padding: EdgeInsets.only(right: 5),
              margin: EdgeInsets.only(left: 15),
              child: ExtendedTextField(
                keyboardAppearance: Brightness.light,
                focusNode: focusNode,
                onTap: () {
//            if(!isActionFromButton){
                  isShowEmoji = false;
                  _counter.value = isShowEmoji;
                  _kBarSize = isShowEmoji ? keyboardHeight : 45;
//            }

                  if (_scrollController != null) {
                    ///解决键盘遮挡输入框
                    _scrollController.position.moveTo(
                      200,
                      duration: Duration(milliseconds: 100),
                      curve: Curves.easeIn,
                    );
                  }
                },

                controller: _textCtrl,
                specialTextSpanBuilder: MySpecialTextSpanBuilder(
                    showAtBackground: true, emojiSize: 17.0),
                decoration: new InputDecoration(
                  contentPadding:
                      EdgeInsets.only(top: 6, bottom: 10, right: 10),
                  hintText: I18n.of(context).please_civilization,
                  hintStyle:
                      TextStyle(fontSize: 12, height: 1.15),
                  border: InputBorder.none,
                ),
                style: TextStyle(
                    fontSize: 13, textBaseline: TextBaseline.alphabetic),
                maxLines: 6,
//                    inputFormatters: [LengthLimitingTextInputFormatter(100)],
                onChanged: (str) {
                  if (str.length > 100) {
                    print('超过100了');
                    _textCtrl.text = _textCtrl.value.text.substring(0, 100);
                    int length = _textCtrl.text.length;
                    Future.delayed(Duration(milliseconds: 100), () {
                      _textCtrl.selection = TextSelection(
                          baseOffset: length, extentOffset: length);
                    });
                  }
                },
              )),
        ],
      ),
    );

    List<Widget> imgList = imgUrlList.map((f) {
      return _buildImg(f);
    }).toList();
    if (imgList.length < Max_Img_Num) {
      imgList.add(_buildUpButton());
    }

    Widget picture = Container(
      alignment: Alignment.topCenter,
      child: Row(
        children: <Widget>[
          Container(
              alignment: Alignment.centerLeft,
              width: LEFT_WIDTH,
              margin: EdgeInsets.only(left: 15),
              child: fixedText(I18n.of(context).image,
                  fontSize: 14, fontWeight: FontWeight.w600)),
          Expanded(
              child: Container(
                  margin: EdgeInsets.only(top: 10, bottom: 10),
                  child:
                      Wrap(alignment: WrapAlignment.start, children: imgList))),
        ],
      ),
    );
    List<Widget> list = [
      _bottomBorderBox(
          I18n.of(context).expect_lover,
          lovePeople == '' ? I18n.of(context).choose : lovePeople,
          false,
          null,
          selectLovePeople,
          rightTextGrey: lovePeople == ''),
      _buildDivider(),
      // _bottomBorderBox(
      //     I18n.of(context).city,
      //     dateRange == '' ? I18n.of(context).choose : dateRange,
      //     false,
      //     null,
      //     selectDateRange,
      //     rightTextGrey: dateRange == ''),
      // _buildDivider(),
      _bottomBorderBox(
          I18n.of(context).time,
          beginTime == '' ? I18n.of(context).choose : beginTime,
          false,
          null,
          selectBegin,
          rightTextGrey: beginTime == ''),
      _buildDivider(),
      _bottomBorderBox('', endTime == '' ? I18n.of(context).choose : endTime,
          false, null, selectEnd,
          rightTextGrey: endTime == ''),
      _buildDivider(),
      moreInfo,
      _buildDivider(),
      picture
    ];
    return new Container(
      margin: EdgeInsets.only(top: 15),
      decoration: _getCardDecoration(),
      child: Column(
        children: list,
      ),
    );
  }

  //下划线
  Widget _buildDivider() {
    return new Container(
      margin: EdgeInsets.zero,
      padding: EdgeInsets.zero,
      decoration: BoxDecoration(border: Border(top: Constants.GreyBorderSide)),
      height: 1,
      width: MediaQuery.of(context).size.width * 0.9,
    );
  }

  Widget _buildImg(f) {
    return Stack(
      children: <Widget>[
        InkWell(
            onTap: () {
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return PicSwiper(
                      id: imgUrlList.indexOf(f),
                      pics: imgUrlList
                          .map((f) => PicSwiperItem(
                                f,
                                id: imgUrlList.indexOf(f),
                              ))
                          .toList(),
                    );
                  },
                ),
              );
            },
            child: Container(
                height: 75,
                width: 75,
                margin: EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10.0),
                  border: Border.all(color: Colors.grey[300], width: 1),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: f == null
                      ? Container()
                      : CachedNetworkImage(
                          imageUrl: f,
                          fit: BoxFit.cover,
                        ),
                ))),
        Positioned(
          right: 0,
          child: InkWell(
              onTap: () {
                imgUrlList.remove(f);
                setState(() {});
              },
              child: Image.asset(
                'assets/images/login/delete.png',
                height: 20,
              )),
        )
      ],
    );
  }

  //自定义item
  Widget _bottomBorderBox(
      String textLeft, String textRight, bool flag, controller, callback,
      {bool rightTextGrey = true}) {
    Widget left = new Container(
        width: LEFT_WIDTH,
        child: new Text(
          textLeft,
          textScaleFactor: 1.0,
          style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
        ));

    Widget right = flag
        ? new Expanded(
            child: new TextField(
              keyboardAppearance: Brightness.light,
              controller: controller,
              decoration: new InputDecoration(
                hintText: textRight,
                hintStyle: TextStyle(fontSize: 14),
                border: InputBorder.none,
              ),
              style: TextStyle(textBaseline: TextBaseline.alphabetic),
              maxLines: 1,
              onChanged: (str) {
                if (flag && callback != null) callback(str);
              },
            ),
          )
        : new Expanded(
            child: GestureDetector(
              onTap: () {
                if (!flag && callback != null) callback();
              },
              child: Container(
                color: Colors.transparent,
                height: 53,
                width: MediaQuery.of(context).size.width,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(left: 5),
                child: Text(
                  textRight,
                  textScaleFactor: 1.0,
                  style: TextStyle(
                      fontSize: 14,
                      color: rightTextGrey
                          ? Constants.GreyTextColor
                          : Constants.BlackTextColor),
                ),
              ),
            ),
          );

    return new Container(
      height: 53,
      margin: EdgeInsets.only(left: 15, bottom: 0),
      child: new Row(
        children: <Widget>[left, right],
      ),
    );
  }

  Widget _buildSwitch(str, value, callback) {
    Widget left = new Text(
      str,
      textScaleFactor: 1.0,
      style: TextStyle(
          fontSize: 14,
          fontWeight: widget.isProgram ? FontWeight.w600 : FontWeight.normal),
    );
    Widget right = new Expanded(
        child: new Align(
            alignment: Alignment.centerRight,
            child: new Switch(
              activeTrackColor: Constants.ConfrimButtonColor.withOpacity(0.3),
              value: value,
              onChanged: (bool val) {
                callback();
              },
            )));
    return new Container(
      padding: EdgeInsets.only(left: 15),
      height: 53,
      child: new Row(
        children: <Widget>[left, right],
      ),
    );
  }

  Widget _buildSelct() {
    return new Container(
        decoration: _getCardDecoration(),
        //margin: EdgeInsets.only(top: , bottom: 0),
        child: Column(
          children: <Widget>[
            _buildSwitch(I18n.of(context).prohibit_comments, isCanContent, () {
              setState(() {
                isCanContent = !isCanContent;
              });
            }),
            _buildDivider(),
            _buildSwitch(I18n.of(context).same_sex, isHidden, () {
              setState(() {
                isHidden = !isHidden;
              });
            }),
          ],
        ));
  }

  Widget _buildTip() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(top: 10, bottom: 10, left: 10),
      child: Text(
        I18n.of(context).dont,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 12, color: Constants.GreyTextColor),
      ),
    );
  }

  Widget _buildTips() {
    String str = '';
    if (UserData().isMan()) {
      str = I18n.of(context)
          .member_free
          .replaceFirst('/s1', UserData().addProgramPrice.toString());
    } else {
      str = I18n.of(context)
          .certified_free
          .replaceFirst('/s1', UserData().addProgramPrice.toString());
    }
    return Container(
      padding:  EdgeInsets.only(bottom: 100, left: 20, right: 20),
      child: Text(
        str,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 12, color: Constants.GreyTextColor),
      ),
    );
  }

  Widget _buildBody() {
    List<Widget> program = [
      _buildProgramCat(),
      _buildProgramContent(),
      _buildTip(),
      _buildSelct(),
      _buildLoginButton(),
      _buildTips()
    ];

    List<Widget> dynamics = [
      _buildDynicContent(),
      _buildTip(),
      _buildSelct(),
      _buildLoginButton(),
      _buildTips()
    ];

    return Column(
      children: widget.isProgram ? program : dynamics,
    );
  }

  //构建登陆按钮
  Widget _buildLoginButton() {
    Text text = new Text(I18n.of(context).release,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 15, color: Colors.white));

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Constants.ConfrimButtonColor,
      Constants.ConfrimButtonColor
    ]);
    callback() async {
      closeEmojiAction();

      if (widget.isProgram) {
        if (programId == -1) {
          showToast(I18n.of(context).please_choose);
          return;
        }
        if (lovePeopleId.length == 0) {
          showToast(I18n.of(context).please_choose2);
          return;
        }
        // if (dateRangeId.length == 0) {
        //   showToast(I18n.of(context).please_choose3);
        //   return;
        // }
        if (beginTimeId == '') {
          showToast(I18n.of(context).please_choose4);
          return;
        }
        if (endTimeId == -1) {
          showToast(I18n.of(context).please_choose5);
          return;
        }
      } else {
        if (_textCtrl.value.text.trim().length == 0 && imgUrlList.length == 0) {
          showToast(I18n.of(context).enter_something);
          return;
        }
      }

      payCallback() {
        if (Provider.of<MoneyChangeProvider>(context).money <
            UserData().addProgramPrice) {
          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();
        postAddProgram(UserData().addProgramPrice);
      }

      String title = widget.isProgram
          ? I18n.of(context).release_program
          : I18n.of(context).release_dynamics;

      //非会员男士提示付费
      if (!UserData().isVip && UserData().isMan()) {
        bool isMan = UserData().isMan();

        CustomUI.buildTowConfirm(
          context,
          title,
          isMan
              ? I18n.of(context).become_member2
              : I18n.of(context).now_certification,
          () {
            Navigator.of(context).push(
              new MaterialPageRoute(
                builder: (context) {
                  return isMan ? VipPage() : VerificationCenterPage();
                },
              ),
            );
          },
          I18n.of(context)
              .raid_release
              .replaceFirst('/s1', UserData().addProgramPrice.toString()),
          payCallback,
        );
        return;
      }
      //免费次数用完提示付费
      if (UserData().basicInfo.usedPublishNum >=
          UserData().basicInfo.publishNum) {
        CustomUI.buildOneConfirm(
            context,
            title,
            I18n.of(context)
                .pay_unlock
                .replaceFirst('/s1', UserData().addProgramPrice.toString()),
            payCallback);
        return;
      }
      HttpUtil().userFreeTime(context, UserData().basicInfo.userId, 3, () {
        UserData().basicInfo.usedPublishNum++;
        postAddProgram(0);
      });
    }

    return new Container(
      margin: EdgeInsets.only(top: 30, bottom: 10),
      height: 44,
      width: MediaQuery.of(context).size.width * 0.8,
      child: ShadowButton().builder(gradientColor, text, callback),
    );
  }

  postAddProgram(price) async {
    var dateRangeStr = '';
    dateRangeId.forEach((f) => dateRangeStr += dateRangeStr == '' ? f : ',$f');

    var hopeObject = '';
    lovePeopleId.forEach((f) => hopeObject += hopeObject == '' ? f : ',$f');

    String temp='';
    String postTemp='';
    imgUrlList.forEach((str) {
      temp += (temp == "" ? str : '|$str');
      postTemp += (postTemp == ""
          ? WebData().deleteDemain(str)
          : '|${WebData().deleteDemain(str)}');
    });

    var type = widget.isProgram ? 0 : 1;
    Map data = {
      "userId": UserData().basicInfo.userId,
      "type": type,
      "price": price,
    };
    data['sign'] = TokenMgr().getSign(data);
    //data['city'] = dateRangeStr;
    data['programType'] = programId;
    data['hopeObject'] = hopeObject;
    data['aboutTime'] = beginTimeId;
    data['content'] = _textCtrl.text;
    data['imgUrl'] = postTemp;
    data['evaluateStatus'] = isCanContent;
    data['sexStatus'] = isHidden;
    data['timeQuantum'] = endTimeId;

    Response res = await HttpUtil()
        .post('station/publish/program', data: data, isShowLoading: true);
    var resData = res.data;
    if (resData['code'] == 0) {
      if (widget.isProgram) {
        UserData().isCanProgram = false;
      }
      MessageMgr().emit('Add_program', {
        'Id': resData['data'],
        'UserId': UserData().basicInfo.userId,
        'NickName': UserData().basicInfo.nickName,
        'HeadimgUrl': UserData().basicInfo.headimgurl,
        'Type': type,
        'Sex': UserData().basicInfo.sex,
        'IsMember': UserData().basicInfo.isMember,
        'ProgramType': programId,
        'HopeObject': hopeObject,
        'City': dateRangeStr,
        'AboutTime': beginTimeId,
        'timeQuantum': endTimeId,
        'Content': _textCtrl.text,
        'ImgUrl': temp,
        'EvaluateStatus': isCanContent ? 1 : 0,
        'SexStatus': isHidden,
        'Status': 0,
        'CreateTime': DateTime.now().toIso8601String(),
        'FabulousNum': 0,
        'EvaluateNum': 0,
        'EnrollNum': 0,
        'IsAttestation': UserData().basicInfo.isAttestation ? 1 : 0,
        'IsFabulous': 0,
        'IsEnroll': 0,
        'EvaluateList': null,
        "FabulousList": []
      });
      Navigator.of(context).pop();
      focusNode.removeListener(_focusNodeListener);
    } else {
      showToast(resData['msg']);
    }
  }
}
