package com.yidianling.dynamic.publishTrend.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mmkv.MMKV;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.actions.imagepicker.YDLImagePicker;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.base.BaseApp;
import com.ydl.ydlcommon.base.BaseFragment;
import com.ydl.ydlcommon.data.http.BaseResponse;
import com.ydl.ydlcommon.router.YdlCommonOut;
import com.ydl.ydlcommon.ui.ParcelableImage;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.MoonUtil;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.utils.StringUtils;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.ydl.ydlcommon.view.dialog.NormalDialog;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.RxFileTool;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.bean.DynamicConstants;
import com.yidianling.dynamic.bean.DynamicDraftBean;
import com.yidianling.dynamic.common.browsePictures.BrowsePicturesActivity;
import com.yidianling.dynamic.common.emoji.EmoticonPickerView;
import com.yidianling.dynamic.common.emoji.IEmoticonSelectedListener;
import com.yidianling.dynamic.common.net.DynamicApiUtils;
import com.yidianling.dynamic.common.tool.ImageCompress;
import com.yidianling.dynamic.event.DynamicSaveEvent;
import com.yidianling.dynamic.event.EditContentEvent;
import com.yidianling.dynamic.model.Command;
import com.yidianling.dynamic.model.PublishTrendResult;
import com.yidianling.dynamic.publishTrend.DynamicPublishImageAdapter;
import com.yidianling.dynamic.publishTrend.PublishTrendActivity;
import com.yidianling.dynamic.publishTrend.SelecTopicActivity;
import com.yidianling.dynamic.router.DynamicIn;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author jiucheng
 * @描述:提问、动态的fragment--从原有的发布动态activity移过来
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/10/12
 */

public class PublishQuestionAndTrendFragment extends BaseFragment implements View.OnClickListener, IEmoticonSelectedListener {
    /**
     * 动态
     */
    public static final String TYPE_TREND = "5";
    /**
     * 提问
     */
    public static final String TYPE_QUESTION = "6";
    /**
     * 页面标记：
     * TYPE_TREND：动态
     * TYPE_TREND：提问
     * <p>
     * ext_type 5动态 6问答
     * is_doctor_show 1仅专家可见 2所有可见
     */
    private String type;

    private TextView publish_trend_content_num_tv, publish_trend_bottom_topic_tv;
    public EditText publish_trend_title_editext, publish_trend_content_editext;
    private RecyclerView publish_trend_img_rcv;
    private ImageView publish_trend_bottom_img_iv;
    private View lineTitle;
    private LinearLayout publish_anonymity_rel;
    private LinearLayout ll_to_expert;
    private ImageView publish_anonymity_iv;
    private RelativeLayout publish_trend_ad_rel;
    private CardView publish_trend_ad_relcardView;
    private ImageView publish_trend_ad_iv;
    private ImageView iv_fm;
    private ImageView iv_to_expert;
    private TextView publish_trend_ad_tv;
    private ConstraintLayout trends_publish_question;
    private LinearLayout  ll_bottom_img_emoji;
    RxFileTool fileUtils;
    private String head_dir;//目录
    private String head_path;//路径
    File head_filec;
    private List<ParcelableImage> publishTrendImgs, publishTrendImgBrows;
    private DynamicPublishImageAdapter adapter;

    String topic_id;
    String topic_title;

    String publish_type;

    int is_niming = 1;//是否匿名：1否，2匿名
    /**
     * 仅对专家可见
     * 1仅专家可见 2所有可见
     * 默认所有可见
     */
    private int isDoctorShow = 2;

    String content;//发布动态内容
    boolean is_publis_ing = false;

    List<File> imgFiles;

    ImageView publish_emoji_iv;
    private EmoticonPickerView emoticon_picker_view;
    /**
     * 表情弹窗是否显示
     */
    private boolean emojilayot_ishow;
    boolean writeing_title;

    protected Handler uiHandler;
    private boolean isKeyboardShowed = true; // 是否显示键盘
    //测试结果页(或者fm页面、文章页面)传过来的数据
    private String Test_url;
    private String Test_cover;
    private String Test_title;
    private int isFromFm = 0;
    private RxPermissions rxPermissions;
    private AlertDialog loadingDialog;

    private static final String URL = "Test_url";
    private static final String COVER = "Test_cover";
    private static final String TITLE = "Test_title";
    private View dialogContentView;
    private Activity activity;
    private int isCanlayout=0;
    DynamicDraftBean dynamicTrendsDraftBean;
    DynamicDraftBean dynamicquestionDraftBean;
    String dynamic_publish_trends_save="dynamic_publish_trends_save";
    String dynamic_question_save="dynamic_question_save";

    public static Fragment getInstance(String type) {
        PublishQuestionAndTrendFragment fragment = new PublishQuestionAndTrendFragment();
        fragment.type = type;
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
    }

    @Override
    public int layoutResId() {
        return R.layout.dynamic_fragment_publish_trend;
    }

    @Override
    public void initDataAndEvent() {

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        isCanlayout=0;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

   public void onEventMainThread(DynamicSaveEvent event) {
        Boolean isPublishTrends= publish_trend_title_editext.getVisibility() != View.VISIBLE;
        if (event.getSaveOrNot()){
            //保留草稿数据  标题、内容、话题、是否专家可见、是否匿名、图片
            if (isPublishTrends){//true是发布动态保存
                MMKV.defaultMMKV().encode(dynamic_publish_trends_save,new DynamicDraftBean(publish_trend_title_editext.getText().toString(),
                        publish_trend_content_editext.getText().toString(),
                        topic_id,
                        topic_title,
                        isDoctorShow,
                        is_niming,
                        publishTrendImgs
                ));
            }else{
                MMKV.defaultMMKV().encode(dynamic_question_save,new DynamicDraftBean(publish_trend_title_editext.getText().toString(),
                        publish_trend_content_editext.getText().toString(),
                        topic_id,
                        topic_title,
                        isDoctorShow,
                        is_niming,
                        publishTrendImgs
                ));
            }

        }else{
            if (isPublishTrends){
                publishTrendImgs.clear();
                MMKV.defaultMMKV().encode(dynamic_publish_trends_save,new DynamicDraftBean(
                        "","","44","今日打卡",2,1,publishTrendImgs));
            }else{
                publishTrendImgs.clear();
                MMKV.defaultMMKV().encode(dynamic_question_save,new DynamicDraftBean(
                        "","","44","今日打卡",2,1,publishTrendImgs));
            }
        }
    }
    @Override
    public void initDataAndEventLazy() {
        rxPermissions = new RxPermissions(getActivity());
        imgFiles = new ArrayList<File>();
        publishTrendImgs = new ArrayList<>();
        if (TextUtils.equals(type, TYPE_TREND)){
            dynamicTrendsDraftBean=MMKV.defaultMMKV().decodeParcelable(dynamic_publish_trends_save,DynamicDraftBean.class);
        }else{
            dynamicquestionDraftBean=MMKV.defaultMMKV().decodeParcelable(dynamic_question_save,DynamicDraftBean.class);
        }
        initView();
        if (TextUtils.equals(type, TYPE_TREND)){
            publish_trend_content_editext.requestFocus();
        }else{
            publish_trend_title_editext.requestFocus();
        }
        uiHandler = new Handler();
        initEvent();
        Intent intent = activity.getIntent();
        Bundle bundle = intent.getBundleExtra("bundle");
        publish_type = bundle.getString(DynamicConstants.PUBLISH_TYPE);
        if (TextUtils.equals(type, TYPE_TREND)) {//测试结果默认在动态页面展示
            Test_url = bundle.getString("Test_url");
            Test_cover = bundle.getString("Test_cover");
            Test_title = bundle.getString("Test_title");
            isFromFm = bundle.getInt("isfromfm", 0);
        }
        if ("home_publish".equals(publish_type)) {// 从首页进来的发布
            topic_id = bundle.getString("topic_ic");
            if (TextUtils.isEmpty(topic_title)){
                topic_title = bundle.getString("topic_title");
            }
            publish_trend_bottom_topic_tv.setVisibility(View.VISIBLE);
            publish_trend_bottom_topic_tv.setText("# " + topic_title);
            publish_trend_bottom_topic_tv.setTextColor(ContextCompat.getColor(activity, R.color.platform_main_theme));
        } else if ("topic_publish".equals(publish_type)) {// 从话题详情进来的发布
            topic_id = bundle.getString("topic_id");
            if (TextUtils.isEmpty(topic_title)){
                topic_title = bundle.getString("topic_title");
            }
            publish_trend_bottom_topic_tv.setVisibility(View.VISIBLE);
            publish_trend_bottom_topic_tv.setText("# " + topic_title);
            publish_trend_bottom_topic_tv.setTextColor(ContextCompat.getColor(activity, R.color.platform_main_theme));
        } else if ("default_publish".equals(publish_type)) {// 默认发布类型
            publish_trend_bottom_topic_tv.setVisibility(View.VISIBLE);
        }


        if (!"".equals(Test_url) && Test_url != null && !"".equals(Test_cover) && Test_cover != null && !"".equals(Test_title) && Test_title != null) {
            publish_trend_img_rcv.setVisibility(View.GONE);
            publish_trend_ad_rel.setVisibility(View.VISIBLE);
            publish_trend_ad_relcardView.setVisibility(View.VISIBLE);
            GlideApp.with(activity)
                    .load(Test_cover)
                    .placeholder(R.drawable.dynamic_default_img)
                    .error(R.drawable.dynamic_default_img)
                    .into(publish_trend_ad_iv);
            publish_trend_ad_tv.setText(Test_title);
            if (isFromFm == 1) {
                iv_fm.setVisibility(View.VISIBLE);
            } else {
                iv_fm.setVisibility(View.GONE);
            }
        } else {
            publish_trend_img_rcv.setVisibility(View.VISIBLE);
            publish_trend_ad_rel.setVisibility(View.GONE);
            publish_trend_ad_relcardView.setVisibility(View.GONE);
            publish_trend_bottom_img_iv.setImageResource(R.drawable.dynamic_edit_img);
            head_dir = RxFileTool.getStorageDirectory(activity) + "/img/publish_img/";

            if (adapter == null) {
                adapter = new DynamicPublishImageAdapter(publishTrendImgs, activity);
            } else {
                adapter.notifyDataSetChanged();
            }
            publish_trend_img_rcv.setLayoutManager(new GridLayoutManager(activity, 3));
            publish_trend_img_rcv.setLayoutManager(new GridLayoutManager(activity, 3));
            publish_trend_img_rcv.setAdapter(adapter);
            adapter.setOnItemClickLister(new DynamicPublishImageAdapter.OnItemClickLister() {
                @Override
                public void onItemClick(View view, int position) {
                    publishTrendImgBrows = new ArrayList<ParcelableImage>();
                    publishTrendImgBrows.clear();
                    publishTrendImgBrows.addAll(publishTrendImgs);
                    if (publishTrendImgBrows.size() < 9) {
                        publishTrendImgBrows.remove(publishTrendImgBrows.size() - 1);
                        if (publishTrendImgBrows.size() > 0) {
                            Intent intent = new Intent();
                            intent.setClass(activity, BrowsePicturesActivity.class);
                            intent.putExtra("browse_type", "preview");
                            intent.putExtra("position", position);
                            Bundle bd = new Bundle();
                            bd.putParcelableArrayList("allTrendImages", (ArrayList<? extends Parcelable>) publishTrendImgBrows);
                            intent.putExtra("allTrendImages_bd", bd);
                            startActivityForResult(intent, DynamicConstants.PUBLISH_PIC_BROW);
                        }
                    } else {
                        if ("default".equals(publishTrendImgBrows.get(8).getImage_url())) {
                            publishTrendImgBrows.remove(8);
                        }
                        Intent intent = new Intent();
                        intent.setClass(activity, BrowsePicturesActivity.class);
                        intent.putExtra("browse_type", "preview");
                        intent.putExtra("position", position);
                        Bundle bd = new Bundle();
                        bd.putParcelableArrayList("allTrendImages", (ArrayList<? extends Parcelable>) publishTrendImgBrows);
                        intent.putExtra("allTrendImages_bd", bd);
                        startActivityForResult(intent, DynamicConstants.PUBLISH_PIC_BROW);
                    }

                }

                @Override
                public void onItemLongClick(View view, int position) {

                }
            });
            adapter.setOnDeleteClickLister(new DynamicPublishImageAdapter.OnDeleteClickLister() {
                @Override
                public void onDeleteClick(View view, int position) {
                    DeleteImg(position);
                }

                @Override
                public void onDeleteLongClick(View view, int position) {

                }
            });
            adapter.setOnAddClickLister(new DynamicPublishImageAdapter.OnAddClickLister() {
                @Override
                public void OnAddClick(View view, int position) {
                    if (publishTrendImgs.size() < 9) {
                        showSelector();
                    } else {
                        if ("default".equals(publishTrendImgs.get(8).getImage_url())) {
                            showSelector();
                        } else {
                            YdlCommonOut.Companion.showToast("最多选择9张照片");
                        }
                    }

                }

                @Override
                public void OnAddLongClick(View view, int position) {

                }
            });
        }
    }

    private void initView() {
        trends_publish_question=getRootView().findViewById(R.id.trends_publish_question);
        ll_bottom_img_emoji=getRootView().findViewById(R.id.ll_bottom_img_emoji);
        publish_trend_ad_rel = getRootView().findViewById(R.id.publish_trend_ad_rel);
        publish_trend_ad_relcardView = getRootView().findViewById(R.id.publish_trend_ad_relcardview);
        iv_fm = getRootView().findViewById(R.id.iv_fm);
        publish_trend_ad_iv = getRootView().findViewById(R.id.publish_trend_ad_iv);
        publish_trend_ad_tv = getRootView().findViewById(R.id.publish_trend_ad_tv);
        publish_anonymity_iv = getRootView().findViewById(R.id.publish_anonymity_iv);
        publish_trend_content_num_tv = getRootView().findViewById(R.id.publish_trend_content_num_tv);
        publish_trend_bottom_topic_tv = getRootView().findViewById(R.id.publish_trend_bottom_topic_tv);
        publish_trend_title_editext = getRootView().findViewById(R.id.publish_trend_title_editext);
        lineTitle = getRootView().findViewById(R.id.lineTitle);
        publish_trend_content_editext = getRootView().findViewById(R.id.publish_trend_content_editext);
        publish_trend_img_rcv = getRootView().findViewById(R.id.publish_trend_img_rcv);
        publish_trend_bottom_img_iv = getRootView().findViewById(R.id.publish_trend_bottom_img_iv);
        publish_anonymity_rel = getRootView().findViewById(R.id.publish_anonymity_rel);
        ll_to_expert = getRootView().findViewById(R.id.ll_to_expert);
        iv_to_expert = getRootView().findViewById(R.id.iv_to_expert);
        publish_emoji_iv = getRootView().findViewById(R.id.publish_emoji_iv);
        publish_trend_title_editext.addTextChangedListener(textWatcher1);
        publish_trend_content_editext.addTextChangedListener(textWatcher2);
        emoticon_picker_view = getRootView().findViewById(R.id.emoticon_picker_view);
        publish_trend_content_editext.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        publish_trend_title_editext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                isCanlayout=1;
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    writeing_title = true;
                    hideEmojiLayout();
                    publish_emoji_iv.setImageResource(R.drawable.dynamic_edict_ico_emoji_dis);
                } else {
                    // 此处为失去焦点时的处理内容
                    writeing_title = false;
                    if (writeing_title == false && ("".equals(Test_url) || Test_url == null || "".equals(Test_cover) || Test_cover == null ||
                            "".equals(Test_title) || Test_title == null)) {
                        publish_emoji_iv.setImageResource(R.drawable.dynamic_edict_ico_emoji);
                        //                        publish_trend_bottom_img_iv.setImageResource(R.drawable.dynamic_edit_img);
                    }
                }
            }
        });
        publish_trend_content_editext.setOnTouchListener((v, event) -> {
            isCanlayout=1;
            hideEmojiLayout();
            publish_emoji_iv.setImageResource(R.drawable.dynamic_edict_ico_emoji);
            return false;
        });


        if (TextUtils.equals(type, TYPE_TREND)) {//动态
            publish_trend_title_editext.setVisibility(View.GONE);
            lineTitle.setVisibility(View.GONE);
            ll_to_expert.setVisibility(View.GONE);
            publish_trend_content_editext.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500)});
            publish_trend_content_num_tv.setText("0/500");
            if (dynamicTrendsDraftBean!=null){
                publish_trend_title_editext.setText(dynamicTrendsDraftBean.getTitle());
                //展示保留的草稿内容： 内容、话题、是否匿名、图片
                topic_title=dynamicTrendsDraftBean.getTopicTitle();
                publish_trend_content_editext.setText(dynamicTrendsDraftBean.getContent());
                publish_trend_bottom_topic_tv.setText(dynamicTrendsDraftBean.getTopicTitle());
                if (dynamicTrendsDraftBean.getPublishTrendImgs()!=null){
                    publishTrendImgs= dynamicTrendsDraftBean.getPublishTrendImgs();
                }
                is_niming=dynamicTrendsDraftBean.isUserAnonymous();
                isDoctorShow=dynamicTrendsDraftBean.isExpertSeen();
                if (is_niming==1){
                    publish_anonymity_iv.setImageResource(R.drawable.dynamic_checkbox);
                }else{
                    publish_anonymity_iv.setImageResource(R.drawable.dynamic_checkbox_sel);
                }
                if (isDoctorShow==1){
                    iv_to_expert.setImageResource(R.drawable.dynamic_checkbox);
                } else{
                    iv_to_expert.setImageResource(R.drawable.dynamic_checkbox_sel);
                }
            }
        } else {//提问
            publish_trend_title_editext.setVisibility(View.VISIBLE);
            lineTitle.setVisibility(View.VISIBLE);
            ll_to_expert.setVisibility(View.VISIBLE);
            publish_trend_content_editext.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)});
            publish_trend_content_editext.setHint("添加问题描述");
            publish_trend_content_num_tv.setText("0/1000");
            if (dynamicquestionDraftBean!=null){
                publish_trend_title_editext.setText(dynamicquestionDraftBean.getTitle());
                //展示保留的草稿内容： 内容、话题、是否匿名、图片
                topic_title=dynamicquestionDraftBean.getTopicTitle();
                publish_trend_content_editext.setText(dynamicquestionDraftBean.getContent());
                publish_trend_bottom_topic_tv.setText(dynamicquestionDraftBean.getTopicTitle());
                if (dynamicquestionDraftBean.getPublishTrendImgs()!=null){
                    publishTrendImgs= dynamicquestionDraftBean.getPublishTrendImgs();
                }
                is_niming=dynamicquestionDraftBean.isUserAnonymous();
                isDoctorShow=dynamicquestionDraftBean.isExpertSeen();
                if (is_niming==1){
                    publish_anonymity_iv.setImageResource(R.drawable.dynamic_checkbox);
                }else{
                    publish_anonymity_iv.setImageResource(R.drawable.dynamic_checkbox_sel);
                }
                if (isDoctorShow==1){
                    iv_to_expert.setImageResource(R.drawable.dynamic_checkbox_sel);
                }else{
                    iv_to_expert.setImageResource(R.drawable.dynamic_checkbox);
                }
            }
        }

        trends_publish_question.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (isCanlayout!=0){
                    Rect rect=new Rect();
                    trends_publish_question.getWindowVisibleDisplayFrame(rect);

//                    if (isMiuiFullScreen()){
//                        ll_bottom_img_emoji.layout(0,
//                                rect.height()-ll_bottom_img_emoji.getHeight()-160,
//                                ll_bottom_img_emoji.getWidth(),rect.height());
//                    }else{
//                        ll_bottom_img_emoji.layout(0,
//                                rect.height()-ll_bottom_img_emoji.getHeight()- getNavigationBarHeight(getContext()),
//                                ll_bottom_img_emoji.getWidth(),rect.height());
//                    }
                }
            }
        });
    }
    private Integer getNavigationBarHeight( Context context) {
        Integer result = 0;
        Resources resources = context.getResources();
        Integer resourceId =
                resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) result = resources.getDimensionPixelSize(resourceId);
        return result;
    }
    /*
    * 判断小米手机是否开启了全屏手势
    * */
    private Boolean isMiuiFullScreen(){
       return  Settings.Global.getInt(getContext().getContentResolver(), "force_fsg_nav_bar", 0) != 0;
    }
    private void initEvent() {
        publish_trend_bottom_img_iv.setOnClickListener(this);
        publish_trend_bottom_topic_tv.setOnClickListener(this);
        publish_anonymity_rel.setOnClickListener(this);
        publish_emoji_iv.setOnClickListener(this);
        ll_to_expert.setOnClickListener(this);
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.publish_anonymity_rel) {
            if (is_niming == 1) {//是否匿名：1否，2匿名
                NormalDialog.Builder builder = new NormalDialog.Builder(getActivity());
                builder.setTitle("");
                builder.setMessage("设置匿名后，将会隐藏你的个人头像、昵称");
                builder.setPositiveButton("确定匿名",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                publish_anonymity_iv.setImageResource(R.drawable.dynamic_checkbox_sel);
                                is_niming = 2;
                                dialog.dismiss();
                            }
                        });
                builder.setNegativeButton("公开",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
            } else {
                publish_anonymity_iv.setImageResource(R.drawable.dynamic_checkbox);
                is_niming = 1;
            }
        } else if (v.getId() == R.id.publish_trend_bottom_img_iv) {
            if (("".equals(Test_url) || Test_url == null || "".equals(Test_cover) || Test_cover == null ||
                    "".equals(Test_title) || Test_title == null)) {
                if (publishTrendImgs.size() < 9) {
                    showSelector();
                } else {
                    if ("default".equals(publishTrendImgs.get(8).getImage_url())) {
                        showSelector();
                    } else {
                        YdlCommonOut.Companion.showToast("最多选择9张照片");
                    }
                }
            }
        } else if (v.getId() == R.id.publish_trend_bottom_topic_tv) {
            Intent intent = new Intent();
            intent.setClass(getActivity(), SelecTopicActivity.class);
            startActivityForResult(intent, DynamicConstants.REQUEST_CODE_SELECT_TOPIC);
        } else if (v.getId() == R.id.publish_emoji_iv) {
            if (writeing_title == false) {
                toggleEmojiLayout();
            }
        } else if (v.getId() == R.id.ll_to_expert) {//仅对专家可见
            if (isDoctorShow == 1) {
                isDoctorShow = 2;
                iv_to_expert.setImageResource(R.drawable.dynamic_checkbox);
            } else {
                isDoctorShow = 1;
                iv_to_expert.setImageResource(R.drawable.dynamic_checkbox_sel);
            }
        }
    }

    /**
     * 发布
     */
    public void publish() {

        String trend_title = publish_trend_title_editext.getText().toString();
        content = publish_trend_content_editext.getText().toString().trim();
        String phone = DynamicIn.INSTANCE.getUserInfo().getPhone();
        if ("".equals(phone) || phone == null) {
            NormalDialog.Builder builder = new NormalDialog.Builder(getActivity(), "left", true);
            builder.setTitle("");
            builder.setMessage(BaseApp.instance.getResources().getString(R.string.dynamic_bindphone));
            builder.setPositiveButton("果断绑定", (dialog, which) -> {
                startActivity(DynamicIn.INSTANCE.inputPhoneIntent(getActivity(), DynamicConstants.BIND_PHONE_ACTION));
                dialog.dismiss();
            });
            builder.setNegativeButton("忍痛放弃", (dialog, which) -> dialog.dismiss());
            builder.create().show();

        } else {
            if (is_publis_ing == false) { //不是在发布中

                //提问时标题字数不能少于5
                if (TextUtils.equals(type, TYPE_QUESTION)) {
                    if (TextUtils.isEmpty(trend_title) || trend_title.length() < 5) {
                        ((PublishTrendActivity) activity).showCoustomToast("标题不能少于5个字哦");
                        return;
                    }
                }
                if (content.length() < 5) {
                    ((PublishTrendActivity) activity).showCoustomToast("输入内容不能少于5个字哦");
                    //                    YdlCommonOut.INSTANCE.showToast("输入内容长度不能少于5");
                } else {
                    if ("".equals(topic_title) || topic_title == null) {
                        //                        YdlCommonOut.INSTANCE.showToast("请点击#号选择话题");
                        ((PublishTrendActivity) activity).showCoustomToast("选择合适的话题会获得更多关注哦~");
                        ObjectAnimator animator1 = ObjectAnimator.ofFloat(publish_trend_bottom_topic_tv, "scaleX", 1f, 1.5f, 1f);
                        ObjectAnimator animator2 = ObjectAnimator.ofFloat(publish_trend_bottom_topic_tv, "scaleY", 1f, 1.5f, 1f);
                        AnimatorSet set = new AnimatorSet();
                        set.setDuration(300);
                        set.playTogether(animator1, animator2);
                        set.start();
                    } else {
                        ShowDialog();
                        is_publis_ing = true;
                        if (!"".equals(Test_url) && Test_url != null && !"".equals(Test_cover) && Test_cover != null && !"".equals(Test_title) && Test_title != null) {
                            PublishO(is_niming, topic_id, content, trend_title, null);
                        } else {
                            List<ParcelableImage> publishImgs = new ArrayList<ParcelableImage>();
                            publishImgs.addAll(publishTrendImgs);
                            if (publishTrendImgs.size() < 9 && publishTrendImgs.size() > 1) {
                                publishImgs.remove(publishImgs.size() - 1);
                            } else if (publishTrendImgs.size() == 9) {
                                if ("default".equals(publishTrendImgs.get(8).getImage_url())) {
                                    publishImgs.remove(8);
                                }
                            }

                            if (publishImgs.size() > 0) {
                                DealFile(is_niming, topic_id, content, trend_title, publishImgs);
                            } else {
                                PublishO(is_niming, topic_id, content, trend_title, imgFiles);
                            }
                        }
                    }
                }

            }
        }

    }

    private TextWatcher textWatcher1 = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            String editable = publish_trend_title_editext.getText().toString();
            String str = StringUtils.StringFilter(editable.toString());
            EventBus.getDefault().post(str.length() > 0 ? new EditContentEvent(true) : new EditContentEvent(false));
            if (!editable.equals(str)) {
                publish_trend_title_editext.setText(str);
                publish_trend_title_editext.setSelection(str.length()); //光标置后
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
        }

    };

    private TextWatcher textWatcher2 = new TextWatcher() {
        private int start;
        private int count;

        @Override
        public void onTextChanged(CharSequence arg0, int start, int before, int count) {
            this.start = start;
            this.count = count;

            String editable = publish_trend_content_editext.getText().toString();
            String str = StringUtils.StringFilter(editable.toString());
            EventBus.getDefault().post(str.length() > 0 ? new EditContentEvent(true) : new EditContentEvent(false));
            if (!editable.equals(str)) {
                publish_trend_content_editext.setText(str);
                publish_trend_content_editext.setSelection(str.length()); //光标置后
            }

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            publish_trend_content_editext.removeTextChangedListener(this);
            MoonUtil.replaceEmoticons(getActivity(), arg0, start, count);
            int editEnd = publish_trend_content_editext.getSelectionEnd();
            publish_trend_content_editext.removeTextChangedListener(this);
            while (StringUtils.counterChars(arg0.toString()) > 5000 && editEnd > 0) {
                arg0.delete(editEnd - 1, editEnd);
                editEnd--;
            }
            publish_trend_content_editext.setSelection(editEnd);
            publish_trend_content_editext.addTextChangedListener(this);


            if (TextUtils.equals(type, TYPE_TREND)) {//动态
                publish_trend_content_num_tv.setText(String.valueOf((Integer.valueOf(arg0.toString().length())) + "/500"));
            } else {//提问
                publish_trend_content_num_tv.setText(String.valueOf((Integer.valueOf(arg0.toString().length())) + "/1000"));
            }
        }

    };


    private void ShowDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            return;
        }

        if (loadingDialog == null) {
            loadingDialog = new AlertDialog.Builder(getActivity()).create();
        }
        loadingDialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                is_publis_ing = false;
            }
            return false;
        });
        if (dialogContentView == null) {
            dialogContentView = LayoutInflater.from(getActivity()).inflate(R.layout.platform_fragment_loading_dialog, null);
            dialogContentView.findViewById(R.id.tvMsg).setVisibility(View.GONE);
        }

        loadingDialog.show();
        loadingDialog.getWindow().setContentView(dialogContentView);
        WindowManager.LayoutParams p = loadingDialog.getWindow().getAttributes();  //获取对话框当前的参数值
        Point point = new Point();
        getActivity().getWindowManager().getDefaultDisplay().getSize(point);
        p.height = (int) (point.y * 0.2);
        p.width = (int) (point.x * 0.35);
        loadingDialog.getWindow().setAttributes(p);     //设置生效
        loadingDialog.show();
    }


    /**
     * 发布动态
     *
     * @param is_niming        是否匿名
     * @param topic_id         话题id
     * @param content          内容
     * @param trend_title      话题标题
     * @param publishTrendImgs 图片附件
     */
    @SuppressLint({"WrongConstant", "CheckResult"})
    private void DealFile(final int is_niming, final String topic_id, final String content, final String trend_title, final List<ParcelableImage> publishTrendImgs) {
        imgFiles = new ArrayList<File>();
        Observable.fromIterable(publishTrendImgs)
                .subscribeOn(Schedulers.io())
                .map(parcelableImage -> {
                    LogUtil.d("url: " + parcelableImage.getImage_url());
                    return DealFile2(parcelableImage.getImage_url(), 1500 / publishTrendImgs.size());
                })
                .subscribe(file -> {
                    if (file != null) {
                        LogUtil.d("xyutest", "图片压缩后大小: ==>" + file.length() + " file path: " + file.getAbsolutePath());
                        imgFiles.add(file);
                        if (imgFiles.size() == publishTrendImgs.size()) {
                            PublishO(is_niming, topic_id, content, trend_title, imgFiles);
                        }
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //                                    ToastUtil.toastShort(PublishTrendActivity.this, "有图片已被删除");
                                YdlCommonOut.Companion.showToast("有图片已被删除");
                                loadingDialog.dismiss();
                                loadingDialog = null;
                            }
                        });
                        is_publis_ing = false;
                    }
                });

    }

    private synchronized File DealFile2(final String path, int size) {
        File deal_file = null;
        deal_file = ImageCompress.scal(getActivity(),path, size);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return deal_file;
    }

    /**
     * 发布动态(OkHttp)
     *
     * @param is_niming   是否匿名
     * @param topic_id    话题id
     * @param content     内容
     * @param trend_title 话题标题
     * @param imgFiles    图片附件
     */
    @SuppressLint("CheckResult")
    private void PublishO(final int is_niming, final String topic_id, final String content, final String trend_title, final List<File> imgFiles) {
        BuryPointUtils.getInstance().createMap()
                .put("dynamic_type", topic_title)
                .put("dynamic_name", trend_title)
                .put("anonymity", is_niming);
        Command.PublishTrend cmd;
        if (!"".equals(Test_url) && Test_url != null && !"".equals(Test_cover) && Test_cover != null && !"".equals(Test_title) && Test_title != null) {
            cmd = new Command.PublishTrend(is_niming, topic_id, content, trend_title, Test_title, Test_cover, Test_url, type, isDoctorShow);
        } else {
            cmd = new Command.PublishTrend(is_niming, topic_id, content, trend_title, type, isDoctorShow);
        }
        File[] files = null;
        if (imgFiles != null) {
            files = new File[imgFiles.size()];
            for (int i = 0; i < imgFiles.size(); i++) {
                files[i] = imgFiles.get(i);
            }
        }

        DynamicApiUtils.publishTrend(cmd, files)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse<PublishTrendResult>>() {
                    @Override
                    public void accept(BaseResponse<PublishTrendResult> resp) {
                        is_publis_ing = false;
                        loadingDialog.dismiss();
                        if (resp.code == 0) {
                            BuryPointUtils.getInstance().put("publish_succeed", true).burryPoint("publishButtonClick");
                            YdlCommonOut.Companion.showToast("发布成功");
                            SharedPreferencesEditor.putString("trend_state", "success");
                            getActivity().finish();
                            publish_trend_content_editext.setText(null);
                            publish_trend_title_editext.setText(null);
                        } else if (resp.code == DynamicConstants.SILENCED_CODE) {  //被禁言
                            showUserSliencedDialog(resp.data);
                        } else {
                            BuryPointUtils.getInstance().put("publish_succeed", false).burryPoint("publishButtonClick");
                            YdlCommonOut.Companion.showToast(resp.msg);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        BuryPointUtils.getInstance().put("publish_succeed", false).burryPoint("publishButtonClick");
                        loadingDialog.dismiss();
                        is_publis_ing = false;
                        DynamicApiUtils.handleError(getActivity(), throwable);
                    }
                });
        //发布完，清空保存的草稿
        if (TextUtils.equals(type, TYPE_TREND)){
            publishTrendImgs.clear();
            MMKV.defaultMMKV().encode(dynamic_publish_trends_save,new DynamicDraftBean(
                    "","","44","今日打卡",2,1,publishTrendImgs));
        }else{
            publishTrendImgs.clear();
            MMKV.defaultMMKV().encode(dynamic_question_save,new DynamicDraftBean(
                    "","","44","今日打卡",2,1,publishTrendImgs));
        }
    }


    @Override
    public void onEmojiSelected(String key) {
        Editable mEditable = publish_trend_content_editext.getText();
        if (key.equals("/DEL")) {
            publish_trend_content_editext.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
        } else {
            int start = publish_trend_content_editext.getSelectionStart();
            int end = publish_trend_content_editext.getSelectionEnd();
            start = (start < 0 ? 0 : start);
            end = (start < 0 ? 0 : end);
            mEditable.replace(start, end, key);
        }
    }


    private void showSelector() {
        int selectedSize = publishTrendImgs.size()!=0?publishTrendImgs.size()-1:0;

        YDLImagePicker.INSTANCE.startPicker((BaseActivity) activity, 9 - selectedSize,new OnResultCallbackListener() {
            @Override
            public void onResult(List<LocalMedia> list) {
                if (list.isEmpty()) {
                    return;
                }
                if (Build.VERSION.SDK_INT>Build.VERSION_CODES.P){
                    for (int i = 0; i < list.size(); i++) {
                        LocalMedia localMedia = list.get(i);
                        String path;
                        if (!TextUtils.isEmpty(localMedia.getAndroidQToPath())) {
                            //android q路径
                            path = localMedia.getAndroidQToPath();
                        } else if (!TextUtils.isEmpty(localMedia.getCutPath())) {
                            //android 裁剪路径
                            path = localMedia.getCutPath();
                        } else if (!TextUtils.isEmpty(localMedia.getOriginalPath())) {
                            //android 初始路径
                            path = localMedia.getOriginalPath();
                        } else if (!TextUtils.isEmpty(localMedia.getCompressPath())) {
                            //android 压缩路径
                            path = localMedia.getCompressPath();
                        } else if (!TextUtils.isEmpty(localMedia.getRealPath())) {
                            //android 真实路径
                            path = localMedia.getRealPath();
                        } else {
                            path = localMedia.getPath();
                        }
                        if (!TextUtils.isEmpty(path)) {
                            AddImag(path);
                        }
                    }
                }else{
                    for (int i = 0; i < list.size(); i++) {
                        LocalMedia localMedia = list.get(i);
                        String path;
                        if (!TextUtils.isEmpty(localMedia.getPath())) {
                            path = localMedia.getPath();
                        } else if (!TextUtils.isEmpty(localMedia.getCutPath())) {
                            //android 裁剪路径
                            path = localMedia.getCutPath();
                        } else if (!TextUtils.isEmpty(localMedia.getOriginalPath())) {
                            //android 初始路径
                            path = localMedia.getOriginalPath();
                        } else if (!TextUtils.isEmpty(localMedia.getCompressPath())) {
                            //android 压缩路径
                            path = localMedia.getCompressPath();
                        } else {
                            //android 真实路径
                            path = localMedia.getRealPath();
                        }
                        if (!TextUtils.isEmpty(path)) {
                            AddImag(path);
                        }
                    }
                }

            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void showUserSliencedDialog(PublishTrendResult resp) {
        CommonDialog.create(getActivity())
                .setMessage(resp.tips)
                .setLeftOnclick(getActivity().getString(R.string.dynamic_details), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String realUrl = TextUtils.isEmpty(resp.url) ? DynamicConstants.HELP_URL : resp.url;
                        H5Params params = new H5Params(realUrl, "");
                        NewH5Activity.start(getActivity(), params);
                    }
                })
                .setRightClick(getActivity().getString(R.string.dynamic_approval), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setCancelAble(true)
                .show();
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case DynamicConstants.PUBLISH_PIC_BROW:
                    if (data == null) {
                        break;
                    }
                    boolean chane_state = data.getBooleanExtra("chane_state", false);
                    if (chane_state) {
                        Bundle bundle = data.getBundleExtra("bundle");
                        publishTrendImgs = bundle.getParcelableArrayList("publish_img");
                        if (publishTrendImgs.size() > 0) {
                            publishTrendImgs.add(new ParcelableImage("default"));
                        }
                        adapter.updateDate(publishTrendImgs);
                    }
                    break;
                case DynamicConstants.REQUEST_CODE_SELECT_TOPIC://选择话题
                    String type = data.getStringExtra("type");
                    if ("topic_select".equals(type)) {
                        Bundle bd = data.getBundleExtra("bundle");
                        if (bd != null) {
                            topic_id = bd.getString("topic_id");
                            topic_title = bd.getString("topic_title");
                        }
                        publish_trend_bottom_topic_tv.setVisibility(View.VISIBLE);
                        publish_trend_bottom_topic_tv.setText("# " + topic_title);
                        publish_trend_bottom_topic_tv.setTextColor(ContextCompat.getColor(activity, R.color.platform_main_theme));
                        // 获取编辑框焦点
                        publish_trend_content_editext.setFocusable(true);

                        hideEmojiLayout();
                        openSoftKeyBoard();
                    }
                    break;
            }
        }
    }

    private void openSoftKeyBoard() {
        //打开软键盘
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private static final String MIME_JPEG = "image/jpeg";

    /**
     * 添加照片
     */
    private void AddImag(String pic_path) {
        ParcelableImage trendImage = new ParcelableImage(pic_path);
        if (publishTrendImgs.size() < 9 && publishTrendImgs.size() > 0) {
            publishTrendImgs.add(publishTrendImgs.size() - 1, trendImage);
        } else if (publishTrendImgs.size() == 0) {
            publishTrendImgs.add(new ParcelableImage("default"));
            publishTrendImgs.add(publishTrendImgs.size() - 1, trendImage);
        } else {
            publishTrendImgs.remove(8);
            publishTrendImgs.add(8, trendImage);
        }
        adapter.updateDate(publishTrendImgs);
    }

    // 点击表情，切换到表情布局
    @SuppressLint("WrongConstant")
    private void toggleEmojiLayout() {
        if (emoticon_picker_view == null || emoticon_picker_view.getVisibility() == View.GONE) {
            showEmojiLayout();
            //            publish_emoji_iv.setImageResource(R.drawable.dynamic_edict_ico_key);
        } else {
            hideEmojiLayout();
            showInputMethod(publish_trend_content_editext);
            publish_emoji_iv.setImageResource(R.drawable.dynamic_edict_ico_emoji);
        }
    }


    // 隐藏表情布局
    @SuppressLint("WrongConstant")
    public void hideEmojiLayout() {
        if (uiHandler!=null){
            uiHandler.removeCallbacks(showEmojiRunnable);
        }
        if (emoticon_picker_view != null) {
            emoticon_picker_view.setVisibility(View.GONE);
        }
        emojilayot_ishow = false;
    }

    /**
     * 获取当前emoji表情布局显示状态
     *
     * @return
     */
    public boolean getEmojiLayoutIsShow() {
        return emojilayot_ishow;
    }

    private Runnable showEmojiRunnable = new Runnable() {
        @SuppressLint("WrongConstant")
        @Override
        public void run() {
            emoticon_picker_view.setVisibility(View.VISIBLE);
        }
    };
    private Runnable showTextRunnable = new Runnable() {
        @Override
        public void run() {
            showInputMethod(publish_trend_content_editext);
        }
    };

    // 显示表情布局
    @SuppressLint("WrongConstant")
    private void showEmojiLayout() {
        hideInputMethod();
        publish_trend_content_editext.requestFocus();
        emoticon_picker_view.setVisibility(View.VISIBLE);
        emoticon_picker_view.show(this);
        emojilayot_ishow = true;
    }

    // 隐藏键盘布局
    private void hideInputMethod() {
        isKeyboardShowed = false;
        uiHandler.removeCallbacks(showTextRunnable);
        @SuppressLint("WrongConstant") InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(publish_trend_content_editext.getWindowToken(), 0);
        publish_trend_content_editext.clearFocus();
    }

    // 显示键盘布局
    private void showInputMethod(EditText editTextMessage) {
        editTextMessage.requestFocus();
        //如果已经显示,则继续操作时不需要把光标定位到最后
        if (!isKeyboardShowed) {
            editTextMessage.setSelection(editTextMessage.getText().length());
            isKeyboardShowed = true;
        }

        @SuppressLint("WrongConstant") InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editTextMessage, 0);
    }

    /**
     * 删除照片
     */
    private void DeleteImg(int position) {
        if (publishTrendImgs.size() < 9 && publishTrendImgs.size() > 2) {
            publishTrendImgs.remove(position);
        } else if (publishTrendImgs.size() == 2) {
            publishTrendImgs.clear();
        } else {
            if ("default".equals(publishTrendImgs.get(8).getImage_url())) {
                publishTrendImgs.remove(position);
            } else {
                publishTrendImgs.remove(position);
                publishTrendImgs.add(8, new ParcelableImage("default"));
            }

        }
        adapter.updateDate(publishTrendImgs);
    }

    /**
     * 退出发布
     */
    private void ExitPublish() {
        activity.finish();
    }

    @Override
    public void onStickerSelected(String categoryName, String stickerName) {

    }
}
