package com.gh.gamecenter;

import static com.gh.gamecenter.suggest.SuggestSelectFragment.SUGGEST_TYPE_REQUEST;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gh.gamecenter.common.base.activity.ToolBarActivity;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.util.AdHelper;
import com.gh.common.util.ApkActiveUtils;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DirectUtils;
import com.gh.gamecenter.common.constant.Config;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.utils.NotificationHelper;
import com.gh.common.util.PackageUtils;
import com.gh.gamecenter.common.utils.UploadImageUtils;
import com.gh.gamecenter.common.base.TrackableDialog;
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment;
import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.gamecenter.common.utils.TextHelper;
import com.gh.gamecenter.common.view.FixLinearLayoutManager;
import com.gh.gamecenter.core.AppExecutor;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.GsonUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.TimeUtils;
import com.gh.gamecenter.core.utils.ToastUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.databinding.ActivitySuggestBinding;
import com.gh.gamecenter.entity.ErrorEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.InstallGameEntity;
import com.gh.gamecenter.common.entity.NotificationUgc;
import com.gh.gamecenter.entity.SettingsEntity;
import com.gh.gamecenter.entity.SimpleGameEntity;
import com.gh.gamecenter.login.entity.UserInfoEntity;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gamecenter.suggest.SuggestGameCollectAdapter;
import com.gh.gamecenter.suggest.SuggestPicAdapter;
import com.gh.gamecenter.suggest.SuggestSelectGameAdapter;
import com.gh.gamecenter.suggest.SuggestType;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Util_System_ClipboardManager;
import com.lightgame.utils.Util_System_Keyboard;
import com.lightgame.utils.Utils;
import com.lightgame.view.CheckableImageView;
import com.walkud.rom.checker.RomIdentifier;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import kotlin.collections.CollectionsKt;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * Created by khy on 2017/3/31.
 */
public class SuggestionActivity extends ToolBarActivity implements OnRequestCallBackListener<Object>, OnListClickListener, View.OnClickListener {

    EditText mSuggestContentEt;
    RecyclerView mSuggestPicRv;
    EditText mSuggestEmailEt;
    TextView mSuggestPostBtn;
    View suggestPostLl;
    TextView mSuggestSelectGame;
    TextView mSuggestGameName;
    View mSuggestGameLl;
    ScrollView mScrollView;
    CheckedTextView mTypeAccelerate;
    CheckedTextView mTypeStandalone;
    CheckedTextView mTypeMaterial;
    CheckedTextView mTypeOther;
    LinearLayout mSuggestTypeContainer;
    EditText mTypeOtherName;
    TextView mGameNameTitle;
    TextView mTypeName;
    TextView mEmailName;
    TextView mAdTv;
    View mPlatformContainer;
    TextView mPlatformEt;
    TextView mPlatformTitle;
    TextView mLinkEt;
    View mLinkContainer;
    View mContactMethodContainer;
    View mPicContainer;

    View mCopyrightContainer;
    RadioGroup mSuggestIdentityRg;
    TextView mSuggestIdentityTv;
    TextView mCredentialsCodeTv;
    EditText mCredentialsCodeEt;
    TextView mCredentialsPhotoTv;
    RecyclerView mCredentialsPhotoRv;
    TextView mAppNameTv;
    EditText mAppNameEt;
    TextView mInfringementAppScreenshotTv;
    RecyclerView mInfringementAppScreenshotRv;
    TextView mExplanationTv;
    EditText mExplanationEt;
    TextView mContactMethodTv;
    EditText mContactMethodEt;
    TextView mLookDetailDesTv;
    View mCrashTypeContainer;
    CheckableImageView mAppCrashTypeIv;
    CheckableImageView mGameCrashTypeIv;

    public static final int MEDIA_STORE_REQUEST = 1;
    public static final int MEDIA_STORE_CREDENTIALS_REQUEST = 2;
    public static final int MEDIA_STORE_SCREENSHOT_REQUEST = 3;
    public static final String SUGGESTION_HINT_TYPE = "SUGGESTION_HINT_TYPE";
    public static final String FROM_RATING_KEY = "from_rating_key";

    private SuggestPicAdapter mAdapter;
    private SuggestPicAdapter mCredentialsAdapter;
    private SuggestPicAdapter mScreenshotAdapter;

    private ArrayList<String> mCredentialsPathList = new ArrayList<>();
    private ArrayList<String> mScreenshotPathList = new ArrayList<>();

    private Dialog selectGameDialog;
    private WaitingDialogFragment postDialog;

    private SharedPreferences sp;

    @Nullable
    private SimpleGameEntity mGameEntity;

    @Nullable
    private InstallGameEntity mSelectGameEntity;

    private String[] mFunctionTypeName;

    private SuggestType mSuggestType;

    private String mGameInfo;
    private String mHideHint;
    private String mSuggestContent;
    private String mSuggestHintType;
    private String mDiagnosisResult;
    private String mDiagnosisMessage;

    private boolean mAgreePostPic;
    private boolean fromRating = false;
    private boolean isQaFeedback = false;
    private String qaContentId = "";

    private int mFunctionType = -1;

    private String mCollectCancelPkgName = "";

    private String mSuggestIdentity = "person";//版权方身份

    public static void startSuggestionActivity(Context context, SuggestType suggestType, String suggestHintType, String content) {
        startSuggestionActivity(context, suggestType, suggestHintType, content, false, "");
    }

    public static void startSuggestionActivity(Context context, SuggestType suggestType, String suggestHintType, String content, boolean isQaFeedback, String qaContentId) {
        DirectUtils.directToSuggestion(context, suggestType, suggestHintType, content, isQaFeedback, qaContentId);
    }

    // 上传相关游戏ID
    public static void startSuggestionActivity(Context context,
                                               SuggestType suggestType,
                                               String suggestHintType,
                                               String content,
                                               SimpleGameEntity game) {
        startSuggestionActivity(context, suggestType, suggestHintType, content, game, "");
    }

    public static void startSuggestionActivity(Context context,
                                               SuggestType suggestType,
                                               String suggestHintType,
                                               String content,
                                               SimpleGameEntity game,
                                               String gamePlatform) {
        DirectUtils.directToSuggestion(context, suggestType, suggestHintType, content, game, gamePlatform);
    }

    public static void startSuggestionActivity(Context context, SuggestType suggestType, String hint) {
        DirectUtils.directToSuggestion(context, suggestType, hint);
    }

    public static Intent getIntentFromNetworkDiagnosis(Context context, String diagnosis) {
        Intent intent = new Intent(context, SuggestionActivity.class);
        intent.putExtra(EntranceConsts.KEY_SUGGESTTYPE, SuggestType.normal);
        intent.putExtra(EntranceConsts.KEY_CONTENT, "网络诊断结果" + TimeUtils.getFormatTime(System.currentTimeMillis(), "yyyy.MM.dd"));
        intent.putExtra(EntranceConsts.KEY_DIAGNOSIS, diagnosis);
        return intent;
    }

    public static Intent getIntent(
            Context context,
            SuggestType suggestType,
            String hiddenHint,
            String suggestHintType,
            String content,
            String platform,
            SimpleGameEntity game,
            boolean isQaFeedback,
            String qaContentId,
            boolean fromRatingKey,
            String diagnosis
    ) {
        Intent intent = new Intent(context, SuggestionActivity.class);
        if (!diagnosis.isEmpty()) {
            intent.putExtra(EntranceConsts.KEY_SUGGESTTYPE, SuggestType.normal);
            intent.putExtra(EntranceConsts.KEY_CONTENT, "网络诊断结果" + TimeUtils.getFormatTime(System.currentTimeMillis(), "yyyy.MM.dd"));
            intent.putExtra(EntranceConsts.KEY_DIAGNOSIS, diagnosis);
        } else {
            intent.putExtra(EntranceConsts.KEY_SUGGESTTYPE, suggestType);
            intent.putExtra(EntranceConsts.KEY_HIDE_SUGGEST_HINT, hiddenHint);
            intent.putExtra(EntranceConsts.KEY_SUGGEST_HINT_TYPE, suggestHintType);
            intent.putExtra(EntranceConsts.KEY_CONTENT, content);
            intent.putExtra(FROM_RATING_KEY, fromRatingKey);
            intent.putExtra(EntranceConsts.KEY_PLATFORM, platform);
            intent.putExtra(SimpleGameEntity.class.getSimpleName(), game);
            intent.putExtra(EntranceConsts.KEY_IS_QA_FEEDBACK, isQaFeedback);
            intent.putExtra(EntranceConsts.KEY_QA_CONTENT_ID, qaContentId);
        }
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_suggest;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (requestCode == MEDIA_STORE_REQUEST || requestCode == MEDIA_STORE_CREDENTIALS_REQUEST || requestCode == MEDIA_STORE_SCREENSHOT_REQUEST) {
            Uri selectedImage = data.getData();
            if (selectedImage == null) {
                return;
            }
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            if (cursor == null || !cursor.moveToFirst()) {
                return;
            }
            try {
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

                Utils.log("picturePath = " + picturePath);

                File file = new File(picturePath);
                if (file.length() > ImageUtils.getUploadFileMaxSize()) {
                    long count = ImageUtils.getUploadFileMaxSize() / 1024 / 1024;
                    Utils.toast(this, getString(R.string.pic_max_hint, count));
                } else {
                    if (requestCode == MEDIA_STORE_REQUEST) {
                        mAdapter.addFileList(picturePath);
                    } else if (requestCode == MEDIA_STORE_CREDENTIALS_REQUEST) {
                        mCredentialsAdapter.addFileList(picturePath);
                    } else {
                        mScreenshotAdapter.addFileList(picturePath);
                    }
                }
            } catch (Exception e) {
                Utils.toast(this, e.getMessage());
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExtensionsKt.updateStatusBarColor(this, R.color.background_white, R.color.background_white);
        initView();

        Bundle extras = getIntent().getExtras();
        if (extras == null) return;

        Object suggestType = extras.get(EntranceConsts.KEY_SUGGESTTYPE);
        if (suggestType instanceof SuggestType) {
            mSuggestType = (SuggestType) suggestType;
        } else {
            mSuggestType = SuggestType.normal;
        }
        mSuggestContent = extras.getString(EntranceConsts.KEY_CONTENT);
        mSuggestHintType = extras.getString(EntranceConsts.KEY_SUGGEST_HINT_TYPE);
        mHideHint = extras.getString(EntranceConsts.KEY_HIDE_SUGGEST_HINT, "");
        String gamePlatform = extras.getString(EntranceConsts.KEY_PLATFORM, "");
        mFunctionTypeName = getResources().getStringArray(R.array.suggest_function_type);
        mGameEntity = extras.getParcelable(SimpleGameEntity.class.getSimpleName());
        fromRating = extras.getBoolean(FROM_RATING_KEY, false);
        isQaFeedback = extras.getBoolean(EntranceConsts.KEY_IS_QA_FEEDBACK, false);
        qaContentId = extras.getString(EntranceConsts.KEY_QA_CONTENT_ID, "");
        mDiagnosisResult = extras.getString(EntranceConsts.KEY_DIAGNOSIS, "");
        if (!mDiagnosisResult.isEmpty()) {
            mDiagnosisMessage = mSuggestContent;
        }

        setNavigationTitle("意见反馈-" + mSuggestType.getType());

        SettingsEntity.AD ad = AdHelper.INSTANCE.getAd(AdHelper.LOCATION_SUGGESTION_FUNCTION);
        if (mSuggestType == SuggestType.functionSuggest
                && ad != null) {
            mAdTv.setVisibility(View.VISIBLE);
            mAdTv.setText(ad.getTitle());
            mAdTv.setOnClickListener(v -> {
                MtaHelper.onEvent("广告位统计", "意见反馈_功能收录", ad.getTitle());
                DirectUtils.directToLinkPage(this,
                        ad.toLinkEntity(),
                        "(意见反馈-功能收录-广告位)",
                        "");
            });
        }

        sp = PreferenceManager.getDefaultSharedPreferences(this);

        // 意见反馈上传图片列表
        mSuggestPicRv.setLayoutManager(new GridLayoutManager(this, 5) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mAdapter = new SuggestPicAdapter(this, this);
        mSuggestPicRv.setAdapter(mAdapter);

        if (!TextUtils.isEmpty(mSuggestContent)) {
            if (mSuggestType == SuggestType.gameQuestion
                    && ("game".equals(mSuggestHintType) || "welfare_game".equals(mSuggestHintType) || "online_game".equals(mSuggestHintType) || "local_game".equals(mSuggestHintType))) {
                mSuggestContentEt.setText("问题反馈：");
                mSuggestSelectGame.setVisibility(View.GONE);
                mSuggestGameName.setVisibility(View.VISIBLE);
                mSuggestGameName.setText(mSuggestContent);
            } else if (mSuggestType == SuggestType.gameQuestion && "notfound".equals(mSuggestHintType) && mGameEntity != null) {
                mSuggestContentEt.setText(mSuggestContent);
                mSuggestSelectGame.setVisibility(View.GONE);
                mSuggestGameName.setVisibility(View.VISIBLE);
                mSuggestGameName.setText(mGameEntity.getName());
            } else {
                mSuggestContentEt.setText(mSuggestContent);
            }
            if (!TextUtils.isEmpty(gamePlatform)) {
                mPlatformEt.setText(gamePlatform);
            }
            mSuggestContentEt.setSelection(mSuggestContentEt.getText().length());
        }

        initSuggest(mSuggestType);

        String suggestionType = sp.getString(SUGGESTION_HINT_TYPE, null);
        if (!TextUtils.isEmpty(mSuggestHintType) && !TextUtils.isEmpty(suggestionType)) {
            SettingsEntity.Suggestion typeEntity = GsonUtils.fromJson(suggestionType, SettingsEntity.Suggestion.class);
            if (typeEntity != null) {
                switch (mSuggestHintType) {
                    case EntranceConsts.KEY_PLUGIN:
                        List<String> plugin = typeEntity.getPlugin();
                        if (plugin != null && plugin.size() > 0) {
                            showHintDialog(plugin);
                        }
                        break;
                    case "local_game":
                        List<String> localGameList = typeEntity.getLocalGame();
                        if (localGameList != null && localGameList.size() > 0) {
                            showHintDialog(localGameList);
                        }
                        break;
                    case "welfare_game":
                        List<String> welfareGame = typeEntity.getWelfareGame();
                        if (welfareGame != null && welfareGame.size() > 0) {
                            showHintDialog(welfareGame);
                        }
                        break;
                    case "online_game":
                        List<String> onlineGame = typeEntity.getOnlineGame();
                        if (onlineGame != null && onlineGame.size() > 0) {
                            showHintDialog(onlineGame);
                        }
                        break;
                    case "gjlocal_game":
                        List<String> internationalLocalGame = typeEntity.getInternationalLocalGame();
                        if (internationalLocalGame != null && internationalLocalGame.size() > 0) {
                            showHintDialog(internationalLocalGame);
                        }
                        break;
                    case "gjonline_game":
                        List<String> internationalOnlineGame = typeEntity.getInternationalOnlineGame();
                        if (internationalOnlineGame != null && internationalOnlineGame.size() > 0) {
                            showHintDialog(internationalOnlineGame);
                        }
                        break;
                    case "libao":
                        List<String> libao = typeEntity.getLibao();
                        if (libao != null && libao.size() > 0) {
                            showHintDialog(libao);
                        }
                        break;
                    case "service":
                        List<String> service = typeEntity.getService();
                        if (service != null && service.size() > 0) {
                            showHintDialog(service);
                        }
                        break;
                    case "report":
                        List<String> report = typeEntity.getReport();
                        if (report != null && report.size() > 0) {
                            showHintDialog(report);
                        }
                        break;

                    case "video":
                        List<String> video = typeEntity.getVideo();
                        if (video != null && video.size() > 0) {
                            showHintDialog(video);
                        }
                        break;
                }
            }
        }

        UserInfoEntity userInfo = UserManager.getInstance().getUserInfoEntity();
        if (userInfo != null && !TextUtils.isEmpty(userInfo.getQq())) {
            mSuggestEmailEt.setText(userInfo.getQq());
        }

        mTypeOtherName.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                mTypeAccelerate.setChecked(false);
                mTypeMaterial.setChecked(false);
                mTypeOther.setChecked(true);
                mTypeStandalone.setChecked(false);
                mFunctionType = 3;
            }
        });

        if (mGameEntity != null && fromRating) {
            mGameInfo = mGameEntity.getName();
            mSuggestGameName.setText(mGameEntity.getName());
            mSuggestSelectGame.setVisibility(View.GONE);
            mSuggestGameName.setVisibility(View.VISIBLE);
            mSuggestGameLl.setEnabled(false);
        }
        mSuggestContentEt.setFilters(new InputFilter[]{TextHelper.getFilter(256, "最多输入256个字")});
        mSuggestEmailEt.setFilters(new InputFilter[]{TextHelper.getFilter(64, "最多输入64个字")});
        mTypeOtherName.setFilters(new InputFilter[]{TextHelper.getFilter(30, " 最多输入30个字")});
        Util_System_Keyboard.showSoftKeyboard(this, mSuggestContentEt);
        if (mSuggestType != SuggestType.copyright) {
            mSuggestContentEt.setFocusable(true);
            mSuggestContentEt.setFocusableInTouchMode(true);
            mSuggestContentEt.requestFocus();
        } else {
            mCredentialsAdapter = new SuggestPicAdapter(this, 5, new OnListClickListener() {
                @Override
                public <T> void onListClick(View view, int position, T data) {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, MEDIA_STORE_CREDENTIALS_REQUEST);
                }
            }, null);
            mCredentialsAdapter.setPicItem(R.layout.game_upload_pic_item);
            mCredentialsAdapter.setSuggestAddPicIcon(R.drawable.icon_pic_add);
            mCredentialsPhotoRv.setLayoutManager(new GridLayoutManager(this, 5) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            mCredentialsPhotoRv.setAdapter(mCredentialsAdapter);

            mScreenshotAdapter = new SuggestPicAdapter(this, 5, new OnListClickListener() {
                @Override
                public <T> void onListClick(View view, int position, T data) {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, MEDIA_STORE_SCREENSHOT_REQUEST);
                }
            }, null);
            mScreenshotAdapter.setPicItem(R.layout.game_upload_pic_item);
            mScreenshotAdapter.setSuggestAddPicIcon(R.drawable.icon_pic_add);
            mInfringementAppScreenshotRv.setLayoutManager(new GridLayoutManager(this, 5) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            mInfringementAppScreenshotRv.setAdapter(mScreenshotAdapter);

            mSuggestIdentityRg.setOnCheckedChangeListener((group, checkedId) -> {
                if (checkedId == R.id.suggestPersonalRb) {
                    mSuggestIdentity = "person";
                    mCredentialsCodeEt.setHint("请填写身份证号或护照号");
                    mCredentialsPhotoTv.setText(Html.fromHtml(getString(R.string.suggestion_credentials_pic)));
                } else if (checkedId == R.id.suggestCompanyRb) {
                    mSuggestIdentity = "company";
                    mCredentialsCodeEt.setHint("请填写公司营业执照或组织代码等");
                    mCredentialsPhotoTv.setText(Html.fromHtml(getString(R.string.suggestion_company_pic)));
                }
            });
        }
    }

    private void initView() {
        mSuggestContentEt = findViewById(R.id.suggest_content_et);
        mSuggestPicRv = findViewById(R.id.suggest_pic_rv);
        mSuggestEmailEt = findViewById(R.id.suggest_email_et);
        mSuggestPostBtn = findViewById(R.id.suggest_post_btn);
        suggestPostLl = findViewById(R.id.suggest_post_ll);
        mSuggestSelectGame = findViewById(R.id.suggest_game_select);
        mSuggestGameName = findViewById(R.id.suggest_game_name);
        mSuggestGameLl = findViewById(R.id.suggest_game_container);
        mScrollView = findViewById(R.id.suggest_scrollview);
        mTypeAccelerate = findViewById(R.id.type_accelerate);
        mTypeStandalone = findViewById(R.id.type_standalone);
        mTypeMaterial = findViewById(R.id.type_material);
        mTypeOther = findViewById(R.id.type_other);
        mSuggestTypeContainer = findViewById(R.id.suggest_type_container);
        mTypeOtherName = findViewById(R.id.type_other_name);
        mGameNameTitle = findViewById(R.id.suggest_game_name_title);
        mTypeName = findViewById(R.id.suggest_type_name);
        mEmailName = findViewById(R.id.suggest_email_name);
        mAdTv = findViewById(R.id.tv_ad);
        mPlatformContainer = findViewById(R.id.suggest_platform_container);
        mPlatformEt = findViewById(R.id.suggest_platform_et);
        mPlatformTitle = findViewById(R.id.suggest_platform_title);
        mLinkEt = findViewById(R.id.suggest_link_et);
        mLinkContainer = findViewById(R.id.suggest_link_container);
        mContactMethodContainer = findViewById(R.id.contactMethodContainer);
        mPicContainer = findViewById(R.id.picContainer);

        mCopyrightContainer = findViewById(R.id.copyrightContainer);
        mSuggestIdentityRg = findViewById(R.id.suggestIdentityRg);
        mSuggestIdentityTv = findViewById(R.id.suggestIdentityTv);
        mCredentialsCodeTv = findViewById(R.id.credentialsCodeTv);
        mCredentialsCodeEt = findViewById(R.id.credentialsCodeEt);
        mCredentialsPhotoTv = findViewById(R.id.credentialsPhotoTv);
        mCredentialsPhotoRv = findViewById(R.id.credentialsPhotoRv);
        mAppNameTv = findViewById(R.id.appNameTv);
        mAppNameEt = findViewById(R.id.appNameEt);
        mInfringementAppScreenshotTv = findViewById(R.id.infringementAppScreenshotTv);
        mInfringementAppScreenshotRv = findViewById(R.id.infringementAppScreenshotRv);
        mExplanationTv = findViewById(R.id.explanationTv);
        mExplanationEt = findViewById(R.id.explanationEt);
        mContactMethodTv = findViewById(R.id.contactMethodTv);
        mContactMethodEt = findViewById(R.id.contactMethodEt);
        mLookDetailDesTv = findViewById(R.id.lookDetailDesTv);
        mCrashTypeContainer = findViewById(R.id.suggest_crash_type_container);
        mAppCrashTypeIv = findViewById(R.id.appCrashTypeIv);
        mGameCrashTypeIv = findViewById(R.id.gameCrashTypeIv);

        ArrayList<View> clickableViewList = CollectionsKt.arrayListOf(
                mSuggestPostBtn,
                mSuggestGameLl,
                mTypeAccelerate,
                mTypeMaterial,
                mTypeOther,
                mTypeStandalone,
                mLookDetailDesTv,
                mAppCrashTypeIv,
                mGameCrashTypeIv
        );
        for (View view : clickableViewList) {
            view.setOnClickListener(this);
        }
    }

    private void initSuggest(SuggestType type) {
        if (type == SuggestType.normal) {
            mSuggestContentEt.setHint("请详细描述你遇到的问题... \n ↓↓你还可以上传截图");
            mSuggestTypeContainer.setVisibility(View.GONE);
            mSuggestGameLl.setVisibility(View.GONE);
            mCopyrightContainer.setVisibility(View.GONE);
        } else if (type == SuggestType.crash) {
            mSuggestContentEt.setHint("请详细描述闪退之前你所进行的操作... \n ↓↓你还可以上传截图");
            mSuggestTypeContainer.setVisibility(View.GONE);
            mSuggestGameLl.setVisibility(View.GONE);
            mCopyrightContainer.setVisibility(View.GONE);
            mCrashTypeContainer.setVisibility(View.VISIBLE);
            // 通过提示弹窗点击进入的意见反馈-发生闪退，[闪退类型]需要自动选择App闪退
            if (mHideHint.equals("APP闪退：")) {
                mAppCrashTypeIv.setChecked(true);
            }
        } else if (type == SuggestType.gameQuestion) {
            mSuggestTypeContainer.setVisibility(View.GONE);
            mCopyrightContainer.setVisibility(View.GONE);
            if (!EntranceConsts.KEY_PLUGIN.equals(mSuggestHintType)) {
                mSuggestContentEt.setHint("请描述具体遇到的问题... \n ↓↓你还可以上传截图");
                mSuggestGameLl.setVisibility(View.VISIBLE);
                mPlatformContainer.setVisibility(View.VISIBLE);
                mGameNameTitle.setText(Html.fromHtml(getString(R.string.suggestion_game_name)));
                mPlatformTitle.setText(Html.fromHtml(getString(R.string.suggestion_platform_name)));
            } else {
                mSuggestContentEt.setHint("请写上游戏名字，以及具体遇到的问题... \n ↓↓你还可以上传截图");
                mSuggestGameLl.setVisibility(View.GONE);
                mPlatformContainer.setVisibility(View.GONE);
            }
        } else if (type == SuggestType.gameCollect) {
            mLinkContainer.setVisibility(View.VISIBLE);
            mSuggestGameLl.setVisibility(View.VISIBLE);
            mGameNameTitle.setText(Html.fromHtml(getString(R.string.suggestion_game_name)));
            mSuggestTypeContainer.setVisibility(View.GONE);
            mSuggestContentEt.setHint("请在上方选择或填写游戏名↑↑ \n 在此处可输入补充信息（例如游戏的平台版本等）");
            mEmailName.setText(Html.fromHtml(getString(R.string.suggestion_contact)));
            mCopyrightContainer.setVisibility(View.GONE);
        } else if (type == SuggestType.functionSuggest) {
            mSuggestContentEt.setHint("请详细描述你的建议... \n ↓↓你还可以上传截图");
            mSuggestTypeContainer.setVisibility(View.VISIBLE);
            mSuggestGameLl.setVisibility(View.VISIBLE);
            mGameNameTitle.setText(Html.fromHtml(getString(R.string.suggestion_game_name)));
            mTypeName.setText(Html.fromHtml(getString(R.string.suggestion_function)));
            mEmailName.setText(Html.fromHtml(getString(R.string.suggestion_contact)));
            mCopyrightContainer.setVisibility(View.GONE);
        } else if (type == SuggestType.articleCollect) {
            mSuggestContentEt.setHint("简单介绍帖子内容，别忘了填写帖子链接哦 \n ↓↓你还可以上传截图");
            mSuggestTypeContainer.setVisibility(View.GONE);
            mSuggestGameLl.setVisibility(View.GONE);
            mCopyrightContainer.setVisibility(View.GONE);
        } else if (type == SuggestType.copyright) {
            mSuggestGameLl.setVisibility(View.GONE);
            mSuggestTypeContainer.setVisibility(View.GONE);
            mPlatformContainer.setVisibility(View.GONE);
            mLinkContainer.setVisibility(View.GONE);
            mContactMethodContainer.setVisibility(View.GONE);
            mPicContainer.setVisibility(View.GONE);
            mCopyrightContainer.setVisibility(View.VISIBLE);
            mCredentialsCodeEt.requestFocus();
            mSuggestIdentityTv.setText(Html.fromHtml(getString(R.string.suggestion_identity)));
            mCredentialsCodeTv.setText(Html.fromHtml(getString(R.string.suggestion_credentials_code)));
            mCredentialsPhotoTv.setText(Html.fromHtml(getString(R.string.suggestion_credentials_pic)));
            mAppNameTv.setText(Html.fromHtml(getString(R.string.suggestion_app_name)));
            mInfringementAppScreenshotTv.setText(Html.fromHtml(getString(R.string.suggestion_infringement)));
            mExplanationTv.setText(Html.fromHtml(getString(R.string.suggestion_explanation)));
            mContactMethodTv.setText(Html.fromHtml(getString(R.string.suggestion_contact_method)));
            mLookDetailDesTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        }
    }

    private void showHintDialog(List<String> dialogType) {
        final Dialog dialog = new Dialog(SuggestionActivity.this);

        LinearLayout container = new LinearLayout(SuggestionActivity.this);
        container.setOrientation(LinearLayout.VERTICAL);
        container.setBackgroundColor(ContextCompat.getColor(this, R.color.background_white));
        container.setPadding(0, DisplayUtils.dip2px(SuggestionActivity.this, 12), 0, DisplayUtils.dip2px(SuggestionActivity.this, 12));

        for (String s : dialogType) {
            final TextView reportTv = new TextView(SuggestionActivity.this);
            reportTv.setText(s);
            reportTv.setTextSize(17);
            reportTv.setTextColor(ContextCompat.getColor(this, R.color.text_title));
            reportTv.setBackgroundResource(R.drawable.textview_white_style);
            int widthPixels = getResources().getDisplayMetrics().widthPixels;
            reportTv.setLayoutParams(new LinearLayout.LayoutParams((widthPixels * 9) / 10,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            reportTv.setPadding(
                    DisplayUtils.dip2px(SuggestionActivity.this, 20),
                    DisplayUtils.dip2px(SuggestionActivity.this, 12),
                    DisplayUtils.dip2px(SuggestionActivity.this, 20),
                    DisplayUtils.dip2px(SuggestionActivity.this, 12));
            container.addView(reportTv);

            reportTv.setOnClickListener(v -> {
                dialog.cancel();
                mSuggestContentEt.setText((mSuggestContentEt.getText().toString() + reportTv.getText().toString()));
                mSuggestContentEt.setSelection(mSuggestContentEt.getText().length());
            });
        }

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(container);
        dialog.show();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        autoFilledContentIfAvailable();
    }

    private void autoFilledContentIfAvailable() {
        if (!TextUtils.isEmpty(mSuggestContentEt.getText())) {
            return;
        }

        String clipboardText = Util_System_ClipboardManager.getText(this);
        if (clipboardText != null
                && clipboardText.contains("游戏名")
                && clipboardText.contains("游戏ID")
                && clipboardText.contains("游戏包MD5")) {
            mSuggestContentEt.setText(clipboardText + "\n");
            mSuggestContentEt.post(() -> {
                mSuggestContentEt.setSelection(mSuggestContentEt.getText().length());
            });
        }
    }

    @Override
    public void loadDone() {
        // do nothing
    }

    @Override
    public void loadDone(Object obj) {
        if (selectGameDialog != null) {
            selectGameDialog.cancel();
        }

        mSuggestSelectGame.setVisibility(View.GONE);
        mSuggestGameName.setVisibility(View.VISIBLE);
        if (obj instanceof InstallGameEntity) {
            InstallGameEntity entity = (InstallGameEntity) obj;
            mGameInfo = entity.getGameName() + "(" + entity.getPackageName() + ", " + entity.getGameVersion() + ")";
            mSuggestGameName.setText(entity.getGameName());

            mSelectGameEntity = entity;
        } else {
            String name = obj.toString().replace(" ", "");
            mGameInfo = name;
            mSuggestGameName.setText(name);
        }
    }

    @Override
    public void loadError() {
        // do nothing
    }

    @Override
    public void loadEmpty() {
        // do nothing
    }

    @Override
    public void loadNotFound() {
        // do nothing
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.suggest_post_btn:
                clickPostBtn();
                break;
            case R.id.suggest_game_container:
                showSelectDialog();
                break;
            case R.id.type_accelerate:
                mTypeAccelerate.setChecked(true);
                mTypeMaterial.setChecked(false);
                mTypeOther.setChecked(false);
                mTypeStandalone.setChecked(false);
                mFunctionType = 0;
                mSuggestContentEt.requestFocus();
                break;
            case R.id.type_standalone:
                mTypeAccelerate.setChecked(false);
                mTypeMaterial.setChecked(false);
                mTypeOther.setChecked(false);
                mTypeStandalone.setChecked(true);
                mFunctionType = 1;
                mSuggestContentEt.requestFocus();
                break;
            case R.id.type_material:
                mTypeAccelerate.setChecked(false);
                mTypeMaterial.setChecked(true);
                mTypeOther.setChecked(false);
                mTypeStandalone.setChecked(false);
                mFunctionType = 2;
                mSuggestContentEt.requestFocus();
                break;
            case R.id.type_other:
                mTypeAccelerate.setChecked(false);
                mTypeMaterial.setChecked(false);
                mTypeOther.setChecked(true);
                mTypeStandalone.setChecked(false);
                mFunctionType = 3;
                mTypeOtherName.requestFocus();
                break;
            case R.id.lookDetailDesTv:
                startActivity(WebActivity.getWebIntent(this, getString(R.string.copyright_title), getString(R.string.copyright_rules_url)));
                break;
            case R.id.appCrashTypeIv:
                if (!mAppCrashTypeIv.isChecked()) {
                    mAppCrashTypeIv.setChecked(!mAppCrashTypeIv.isChecked());
                    mGameCrashTypeIv.setChecked(!mAppCrashTypeIv.isChecked());
                }
                break;
            case R.id.gameCrashTypeIv:
                if (!mGameCrashTypeIv.isChecked()) {
                    mGameCrashTypeIv.setChecked(!mGameCrashTypeIv.isChecked());
                    mAppCrashTypeIv.setChecked(!mGameCrashTypeIv.isChecked());
                }
                break;
        }
    }

    private void clickPostBtn() {
        if (mSuggestType != SuggestType.copyright) {
            postNormalSuggestion();
        } else {
            postCopyrightSuggestion();
        }
    }

    private void postNormalSuggestion() {
        boolean isStatusNotPass = !isEnterContent()
                || !isSelectCrashType()
                || !isSelectGame()
                || !isSelectFunctionType()
                || !isEnterPlatform();
        if (isStatusNotPass) return;

        String email = mSuggestEmailEt.getText().toString().trim();
        // 闪退反馈不需要反馈(由闪退提示框跳转)
        if (mSuggestType == SuggestType.crash && !mHideHint.isEmpty()) {
            readPostSuggestion(email);
        } else {
            CheckLoginUtils.checkLogin(this, getPostEntrance(), () -> readPostSuggestion(email));
        }
    }

    private void postCopyrightSuggestion() {
        CheckLoginUtils.checkLogin(this, "我的光环-反馈-[提交]", () -> {
            if (checkCopyrightData()) {
                postDialog = WaitingDialogFragment.newInstance(getString(R.string.dialog_feedback_doing));
                postDialog.show(getSupportFragmentManager(), null);
                postCopyrightPic(true);
            }
        });
    }

    private boolean isEnterContent() {
        if (TextUtils.isEmpty(mSuggestContentEt.getText().toString()) &&
                mSuggestType != SuggestType.functionSuggest &&
                mSuggestType != SuggestType.gameCollect) {
            toast("请输入反馈内容");
            return false;
        }
        return true;
    }

    private boolean isSelectCrashType() {
        if (mSuggestType == SuggestType.crash
                && !mAppCrashTypeIv.isChecked()
                && !mGameCrashTypeIv.isChecked()) {
            toast("请选择闪退类型");
            return false;
        }
        return true;
    }

    private boolean isSelectGame() {
        if (mSuggestGameLl.getVisibility() == View.VISIBLE &&
                TextUtils.isEmpty(mSuggestGameName.getText().toString())) {
            toast("请选择游戏");
            return false;
        }
        return true;
    }

    private boolean isSelectFunctionType() {
        if ((mSuggestTypeContainer.getVisibility() == View.VISIBLE) &&
                (mFunctionType == -1 || (mFunctionType == 3 && TextUtils.isEmpty(mTypeOtherName.getText().toString().trim())))) {
            toast("请选择功能需求");
            return false;
        }
        return true;
    }

    private boolean isEnterPlatform() {
        if (mPlatformContainer.getVisibility() == View.VISIBLE &&
                TextUtils.isEmpty(mPlatformEt.getText().toString())) {
            toast("请填写游戏平台");
            return false;
        }
        return true;
    }

    private String getPostEntrance() {
        String entrance = "我的光环-反馈-[提交]";
        if (!TextUtils.isEmpty(mSuggestContent)) {
            switch (mSuggestContent) {
                case "问题投诉":
                    entrance = "问题详情-投诉-提交反馈";
                    break;
                case "回答投诉":
                    entrance = "回答详情-投诉-提交反馈";
                    break;
                case "文章投诉":
                    entrance = "社区文章详情-投诉-提交反馈";
                    break;
            }
        }
        return entrance;
    }

    private boolean checkCopyrightData() {
        if (TextUtils.isEmpty(mSuggestIdentity)) {
            ToastUtils.showToast("请先选择版权方身份");
            return false;
        } else {
            if (TextUtils.isEmpty(mCredentialsCodeEt.getText().toString())) {
                ToastUtils.showToast(mSuggestIdentity.equals("person") ? "请填写身份证号或护照号等" : "请填写公司营业执照或组织代码等");
                return false;
            }
        }
        if (mCredentialsAdapter.getFileList().size() == 0) {
            ToastUtils.showToast("请先添加版权证明文件");
            return false;
        }
        if (TextUtils.isEmpty(mAppNameEt.getText().toString())) {
            ToastUtils.showToast("请先填写侵权的应用名字");
            return false;
        }
        if (mScreenshotAdapter.getFileList().size() == 0) {
            ToastUtils.showToast("请先添加侵权应用截图");
            return false;
        }
        if (TextUtils.isEmpty(mExplanationEt.getText().toString())) {
            ToastUtils.showToast("请先填写说明");
            return false;
        }
        if (TextUtils.isEmpty(mContactMethodEt.getText().toString())) {
            ToastUtils.showToast("请先填写联系方式");
            return false;
        }
        return true;
    }

    private void readPostSuggestion(String email) {
        if (TextUtils.isEmpty(email)) {
            if (mSuggestType == SuggestType.functionSuggest || mSuggestType == SuggestType.gameCollect) {
                toast("请填写联系方式");
            } else {
                showConfirmDialog(email);
            }
        } else if (mSuggestType == SuggestType.gameCollect && mSelectGameEntity != null) {
            getGameCollectDialogData();
        } else {
            postSuggestion(email);
        }
    }

    private void postSuggestion(String email) {
        postDialog = WaitingDialogFragment.newInstance(getString(R.string.dialog_feedback_doing));
        postDialog.show(getSupportFragmentManager(), null);

        List<String> fileList = mAdapter.getFileList();
        if (fileList != null && fileList.size() > 0) {
            postPic(email);
        } else {
            initPostData(email, null);
        }
    }

    private void getGameCollectDialogData() {
        postDialog = WaitingDialogFragment.newInstance("反馈中...");
        postDialog.show(getSupportFragmentManager(), null);
        String filter = UrlFilterUtils.getFilterQuery("package", mSelectGameEntity.getPackageName(), "type", "suggestion_check");
        RetrofitManager.getInstance()
                .getApi()
                .getSuggestGameCollectHintData(filter)
                .map(RegionSettingHelper.filterGame)
                .map(ApkActiveUtils.filterMapperList)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<GameEntity>>() {
                    @Override
                    public void onResponse(@Nullable List<GameEntity> response) {
                        MtaHelper.onEvent("意见反馈", "意见反馈-游戏收录弹窗", "出现提示弹窗");

                        for (GameEntity gameEntity : response) {
                            ArrayList<String> tagStyle = gameEntity.getTag();
                            for (int i = 0; i < tagStyle.size(); i++) {
                                if (i >= 2) {
                                    tagStyle.remove(i);
                                    i--;
                                }
                            }
                        }
                        showGameCollectDialog(response);
                        postDialog.dismiss();
                    }

                    @Override
                    public void onFailure(@Nullable HttpException e) {
                        postDialog.dismiss();
                        postSuggestion(mSuggestEmailEt.getText().toString().trim());
                    }
                });
    }

    private void showGameCollectDialog(List<GameEntity> gameList) {
        View view = View.inflate(this, R.layout.dialog_game_collect, null);
        View back = view.findViewById(R.id.back);
        View forcePost = view.findViewById(R.id.force_post);
        RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new FixLinearLayoutManager(this));
        recyclerView.setAdapter(new SuggestGameCollectAdapter(this, gameList));

        Dialog dialog = new TrackableDialog(this,
                R.style.GhAlertDialog,
                "意见反馈",
                "意见反馈-游戏收录弹窗",
                null,
                "点击空白",
                "点击手机返回键", false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        dialog.show();

        back.setOnClickListener(v -> {
            MtaHelper.onEvent("意见反馈", "意见反馈-游戏收录弹窗", "点击返回");
            dialog.dismiss();

            if (mSelectGameEntity != null) {
                mCollectCancelPkgName = mSelectGameEntity.getPackageName();
            }
        });
        forcePost.setOnClickListener(v -> {
            MtaHelper.onEvent("意见反馈", "意见反馈-游戏收录弹窗", "点击不是我要的游戏，继续提交");
            dialog.dismiss();
            postSuggestion(mSuggestEmailEt.getText().toString().trim());
        });
    }

    // 弹出确认对话框
    private void showConfirmDialog(final String email) {
        DialogHelper.showCenterWarningDialog(this, "温馨提示", "填写联系方式有助于我们更好地一对一解决您的问题，确定不填写吗？",
                "直接提交", "我要填写",
                () -> {
                    mSuggestEmailEt.requestFocus();
                    mSuggestEmailEt.postDelayed(() -> Util_System_Keyboard.showSoftKeyboard(getApplicationContext(), mSuggestEmailEt), 300);
                    return null;
                },
                () -> {
                    postSuggestion(email);
                    return null;
                });
    }

    private void postPic(final String email) {
        UploadImageUtils.INSTANCE.compressAndUploadImageList(UploadImageUtils.UploadType.suggestion
                , mAdapter.getFileList(), false, new UploadImageUtils.OnUploadImageListListener() {
                    @Override
                    public void onCompressSuccess(@NotNull List<String> imageUrls) {

                    }

                    @Override
                    public void onProgress(long total, long progress) {
                        int percent = (int) (100 * (progress / (float) total));
                        if (percent >= 100) percent = 99;
                        if (postDialog != null) {
                            postDialog.uploadWaitingHint("图片上传中 " + percent + "%");
                        }
                    }

                    @Override
                    public void onSingleSuccess(@NotNull Map<String, String> imageUrlMap) {

                    }

                    @Override
                    public void onSuccess(@NotNull LinkedHashMap<String, String> imageUrlMap, @NotNull Map<String, ? extends Exception> errorMap) {
                        Utils.log("意见反馈:图片上传完成");
                        final JSONArray picArray = new JSONArray();
                        for (String s : imageUrlMap.keySet()) {
                            picArray.put(imageUrlMap.get(s));
                        }
                        initPostData(email, picArray);
                    }

                    @Override
                    public void onError(@NotNull Map<String, ? extends Exception> errorMap) {
                        if (postDialog != null) {
                            postDialog.dismissAllowingStateLoss();
                        }
                        Utils.toast(SuggestionActivity.this, "上传失败");
                        Utils.log("意见反馈:图片上传失败");
                    }
                });
    }

    private void postCopyrightPic(boolean isCredentialsPic) {
        UploadImageUtils.INSTANCE.uploadImageListOneByOne(UploadImageUtils.UploadType.suggestion,
                isCredentialsPic ? mCredentialsAdapter.getFileList() : mScreenshotAdapter.getFileList(),
                false, new UploadImageUtils.OnUploadImageListCountListener() {
                    @Override
                    public void onSuccess(@NotNull Map<String, String> map) {
                        for (Map.Entry<String, String> entry : map.entrySet()) {
                            if (isCredentialsPic) {
                                mCredentialsPathList.add(entry.getValue());
                            } else {
                                mScreenshotPathList.add(entry.getValue());
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        if (isCredentialsPic) {
                            postCopyrightPic(false);
                        } else {
                            initPostCopyRightData();
                        }
                    }

                    @Override
                    public void onError() {
                        if (postDialog != null) {
                            postDialog.dismissAllowingStateLoss();
                        }
                        mCredentialsPathList.clear();
                        mScreenshotPathList.clear();
                        Utils.toast(SuggestionActivity.this, "上传失败");
                        Utils.log("意见反馈:图片上传失败");
                    }
                });
    }

    private void initPostCopyRightData() {
        Map<String, Object> params = new HashMap<>();

        params.put("from", mContactMethodEt.getText().toString());
        params.put("ghversion", PackageUtils.getGhVersionName());
        params.put("channel", HaloApp.getInstance().getChannel());
        params.put("type", android.os.Build.MODEL);
        params.put("sdk", String.valueOf(android.os.Build.VERSION.SDK_INT));
        params.put("version", android.os.Build.VERSION.RELEASE);
        params.put("source", getString(R.string.app_name));
        params.put("jnfj", MetaUtil.getBase64EncodedIMEI());
        params.put("manufacturer", Build.MANUFACTURER);
        params.put("rom", RomIdentifier.getRom().name() + " " + RomIdentifier.getRom().getVersionName());

        params.put("owner_type", mSuggestIdentity);
        params.put("owner_card", mCredentialsCodeEt.getText().toString());
        params.put("certificates", mCredentialsPathList);
        params.put("screenshots", mScreenshotPathList);
        params.put("app_name", mAppNameEt.getText().toString());
        params.put("message", mExplanationEt.getText().toString());
        params.put("suggestion_type", "版权申诉");

        sendSuggestion(new JSONObject(params));
//        if (CheckLoginUtils.isLogin()) {
//            // 创建一条信息至七陌客服
//            String feedbackType = "意见反馈-" + mSuggestType.getType();
//            ImManager.sendFeedbackMessage(feedbackType + ": " + mExplanationEt.getText().toString());
//        }
    }

    private void initPostData(String email, JSONArray picArray) {
        Map<String, String> params = new HashMap<>();

        params.put("from", email);
        params.put("ghversion", PackageUtils.getGhVersionName());
        params.put("channel", HaloApp.getInstance().getChannel());
        params.put("type", android.os.Build.MODEL);
        params.put("sdk", String.valueOf(android.os.Build.VERSION.SDK_INT));
        params.put("version", android.os.Build.VERSION.RELEASE);
        params.put("source", getString(R.string.app_name));
        params.put("jnfj", MetaUtil.getBase64EncodedIMEI());
        params.put("manufacturer", Build.MANUFACTURER);
        params.put("rom", RomIdentifier.getRom().name() + " " + RomIdentifier.getRom().getVersionName());
        params.put("link", mLinkEt.getText().toString());

        if (fromRating) {
            params.put("suggestion_type", mSuggestType.getType() + "（评论）");
        } else if (!mDiagnosisResult.isEmpty()) {
            params.put("suggestion_type", "网络诊断");
        } else if (mSuggestType == SuggestType.crash) {
            if (mAppCrashTypeIv.isChecked()) {
                params.put("suggestion_type", "APP闪退");
            } else {
                params.put("suggestion_type", "游戏闪退");
            }
        } else if (isQaFeedback) {
            params.put("suggestion_type", "QA反馈");
        } else {
            params.put("suggestion_type", mSuggestType.getType());
        }

        if (mGameEntity != null) {
            params.put("game_id", mGameEntity.getId());
        }

        String message;
        String content = mSuggestContentEt.getText().toString().trim();
        if (mSuggestType == SuggestType.gameCollect) {
            message = mGameInfo + "，" + content;
        } else if (mSuggestType == SuggestType.functionSuggest) {
            String typeName;
            if (mFunctionType == 3) {
                typeName = "其他（" + mTypeOtherName.getText().toString().trim() + "）";
            } else {
                typeName = mFunctionTypeName[mFunctionType];
            }
            message = mGameInfo + "，" + typeName + "，" + content;
        } else if (mSuggestType == SuggestType.gameQuestion) {
            if (EntranceConsts.KEY_PLUGIN.equals(mSuggestHintType)) {
                message = "【插件问题】" + content;
            } else {
                if (isQaFeedback && !qaContentId.isEmpty()) {
                    final String gameName = (String) HaloApp.get(Constants.GAME_NAME, false);
                    if (gameName.isEmpty()) {
                        message = "【游戏问题】" + qaContentId + "；" + mSuggestGameName.getText() + "-" + mPlatformEt.getText() + "，" + content;
                    } else {
                        //https://git.shanqu.cc/pm/halo/halo-app-issues/-/issues/1928 第4点
                        message = "【来自：" + gameName + "-游戏问题】" + qaContentId + "；" + mSuggestGameName.getText() + "-" + mPlatformEt.getText() + "，" + content;
                    }
                } else {
                    message = mSuggestGameName.getText() + "-" + mPlatformEt.getText() + "，" + content;
                }
            }
        } else if (mSuggestType == SuggestType.normal && !mDiagnosisResult.isEmpty()) {
            message = mDiagnosisMessage;
            params.put("log", mDiagnosisResult);
        } else if (mSuggestType == SuggestType.normal && isQaFeedback && !qaContentId.isEmpty()) {
            final String gameName = (String) HaloApp.get(Constants.GAME_NAME, false);
            if (TextUtils.isEmpty(gameName)) {
                message = "【普通问题】" + qaContentId + "；" + content;
            } else {
                //https://git.shanqu.cc/pm/halo/halo-app-issues/-/issues/1928 第4点
                message = "【来自：" + gameName + "-普通问题】" + qaContentId + "；" + content;
            }
        } else {
            message = content;
            if (mSuggestType == SuggestType.crash) {
                params.put("log", Config.getExceptionMsg());
                Config.setExceptionMsg(null);
                Config.updateContainsErrorMsg(false);
                if (com.gh.gamecenter.common.BuildConfig.BUILD_TIME != 0) {
                    message = message + " [此闪退基于" + com.gh.gamecenter.common.BuildConfig.BUILD_TIME + "测试包]";
                }
            }
        }
        message = mHideHint + message;
        params.put("message", message);

        JSONObject jsonObject = new JSONObject(params);

        if (picArray != null && picArray.length() > 0) {
            try {
                jsonObject.put("pic", picArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        sendSuggestion(jsonObject);

//        if (CheckLoginUtils.isLogin()) {
//            // 创建一条信息至七陌客服
//            String feedbackType = "意见反馈-" + mSuggestType.getType();
//            ImManager.sendFeedbackMessage(feedbackType + ": " + message);
//        }
    }

    private void sendSuggestion(JSONObject jsonObject) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json"),
                jsonObject.toString());
        RetrofitManager.getInstance().getApi().postSuggestion(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<ResponseBody>() {
                    @Override
                    public void onResponse(ResponseBody response) {
                        if (postDialog != null) {
                            postDialog.dismissAllowingStateLoss();
                        }
                        setResult(SUGGEST_TYPE_REQUEST);
                        toast("感谢您的反馈！");
                        finish();
                        AppExecutor.getUiExecutor().executeWithDelay(() -> NotificationHelper.showNotificationHintDialog(NotificationUgc.FEEDBACK, null), 1000);
                    }

                    @Override
                    public void onFailure(HttpException e) {

                        if (postDialog != null) {
                            postDialog.dismissAllowingStateLoss();
                        }

                        try {
                            if (e != null && e.code() == 403) {
                                String string = e.response().errorBody().string();
                                ErrorEntity error = GsonUtils.fromJson(string, ErrorEntity.class);
                                if (error.getCode() == 403052) {
                                    DialogHelper.showCenterDialog(SuggestionActivity.this, "提醒", "你已经提交过相同的反馈了"
                                            , "关闭提交", "返回修改", () -> {
                                                setResult(SUGGEST_TYPE_REQUEST);
                                                finish();
                                            }, () -> {
                                            });
                                    return;
                                } else if (error.getCode() == 403062) {
                                    DialogHelper.showCenterDialog(SuggestionActivity.this,
                                            "提示", "光环助手已收录游戏：" + error.getData().getGameName(),
                                            "退出并查看游戏", "仍然提交", () -> {
                                                GameDetailActivity.startGameDetailActivity(SuggestionActivity.this,
                                                        error.getData().getGameId(), "(意见反馈-游戏收录-存在相同游戏)", null);
                                                finish();
                                            }, () -> {
                                                try {
                                                    jsonObject.put("again", true);
                                                } catch (Exception e1) {
                                                    e1.printStackTrace();
                                                }
                                                postDialog = WaitingDialogFragment.newInstance(getString(R.string.dialog_feedback_doing));
                                                postDialog.show(getSupportFragmentManager(), null);
                                                sendSuggestion(jsonObject);
                                            });
                                    return;
                                }
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }

                        toast("提交失败，请检查网络状态");
                    }
                });

    }

    private void showSelectDialog() {
        View view = View.inflate(this, R.layout.dialog_suggest_game, null);
        RecyclerView recyclerView = view.findViewById(R.id.dialog_suggest_game_rv);
        View back = view.findViewById(R.id.dialog_suggest_game_back);
        ProgressBar pb = view.findViewById(R.id.dialog_suggest_game_load);
        View manualBtn = view.findViewById(R.id.dialog_suggest_manual);
        View manualContainer = view.findViewById(R.id.dialog_suggest_manual_container);
        View manualConfirm = view.findViewById(R.id.dialog_suggest_confirm);
        EditText manualEdit = view.findViewById(R.id.dialog_suggest_edit);
        manualEdit.setFilters(new InputFilter[]{TextHelper.getFilter(30, " 最多输入30个字")});
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setAdapter(new SuggestSelectGameAdapter(this, pb));

        selectGameDialog = new Dialog(this);
        selectGameDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        selectGameDialog.setCanceledOnTouchOutside(false);
        selectGameDialog.setContentView(view);
        selectGameDialog.show();

        back.setOnClickListener(v -> selectGameDialog.cancel());
        manualBtn.setOnClickListener(v -> {
            manualContainer.setVisibility(View.VISIBLE);
            manualBtn.setVisibility(View.GONE);
        });
        manualConfirm.setOnClickListener(v -> {
            String gameName = manualEdit.getText().toString();
            if (!TextUtils.isEmpty(gameName)) {
                loadDone(gameName);
            } else {
                toast("请输入游戏名字");
            }
        });
    }

    @Override
    public <T> void onListClick(View view, int position, T data) {
        if (!mAgreePostPic && !NetworkUtils.isWifiConnected(this)) {
            mAgreePostPic = true;
            DialogHelper.showCenterDialog(this,
                    "警告",
                    "当前使用移动网络，上传图片会消耗手机流量",
                    "我知道了", "", () -> {
                        List<String> picList = (List<String>) data;
                        if (position == mAdapter.getItemCount() - 1 && picList.size() < 5) {
                            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, MEDIA_STORE_REQUEST);
                        }
                    }, () -> {
                    });
            return;
        }
        List<String> picList = (List<String>) data;
        if (position == mAdapter.getItemCount() - 1 && picList.size() < 5) {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, MEDIA_STORE_REQUEST);
        }
    }

    @Override
    protected boolean handleBackPressed() {
        if (mSelectGameEntity != null && mCollectCancelPkgName.equals(mSelectGameEntity.getPackageName())) {
            return super.handleBackPressed();
        }

        if (!TextUtils.isEmpty(mSuggestContentEt.getText().toString()) ||
                !TextUtils.isEmpty(mSuggestGameName.getText().toString()) ||
                !TextUtils.isEmpty(mLinkEt.getText().toString()) ||
                !TextUtils.isEmpty(mPlatformEt.getText().toString()) ||
                !TextUtils.isEmpty(mCredentialsCodeEt.getText().toString()) ||
                !TextUtils.isEmpty(mAppNameEt.getText().toString()) ||
                !TextUtils.isEmpty(mExplanationEt.getText().toString()) ||
                !TextUtils.isEmpty(mContactMethodEt.getText().toString()) ||
                (mCredentialsAdapter != null && mCredentialsAdapter.getFileList().size() > 0) ||
                (mScreenshotAdapter != null && mScreenshotAdapter.getFileList().size() > 0) ||
                (mAdapter != null && mAdapter.getFileList().size() > 0) ||
                mFunctionType != -1) {
            DialogHelper.showCenterDialog(this, "提示",
                    "确定放弃反馈吗？", "继续反馈", "放弃",
                    () -> {
                    }, this::finish);
            return true;
        }
        return super.handleBackPressed();
    }

    @Override
    protected boolean isAutoResetViewBackgroundEnabled() {
        return true;
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        ExtensionsKt.updateStatusBarColor(this, R.color.background_white, R.color.background_white);
        ActivitySuggestBinding binding = ActivitySuggestBinding.bind(mContentView);
        binding.divider1.setBackgroundColor(ContextCompat.getColor(this, R.color.cutting_line));
        binding.divider2.setBackgroundColor(ContextCompat.getColor(this, R.color.cutting_line));
        binding.divider3.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
        binding.divider4.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
        binding.divider5.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
        binding.divider6.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
        binding.divider7.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
        binding.divider8.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
        binding.divider9.setBackgroundColor(ContextCompat.getColor(this, R.color.background));
    }
}
