package com.cooleshow.teacher.ui.minestyle;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.common.im.bean.ContactRoomListBean;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.ui.video.VideoPlayActivity;
import com.cooleshow.base.utils.ActivityUtils;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.GlideUtils;
import com.cooleshow.base.utils.GsonUtils;
import com.cooleshow.base.utils.MyFileUtils;
import com.cooleshow.base.utils.PopupUtil;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.SoftKeyboardUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.UiUtils;
import com.cooleshow.base.widgets.CommonItemDecoration;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.base.widgets.dialog.CommonDialog;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MineStyleFansGroupListAdapter;
import com.cooleshow.teacher.adapter.MineStyleVideoAdapter;
import com.cooleshow.teacher.adapter.TeachableSelectAdapter;
import com.cooleshow.teacher.bean.TeachableInstrumentBean;
import com.cooleshow.teacher.bean.TeacherSelfStyleInfoBean;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.contract.MineStylePageContract;
import com.cooleshow.teacher.databinding.ActivityMineStylePageBinding;
import com.cooleshow.teacher.presenter.minestyle.MineStylePagePresenter;
import com.cooleshow.teacher.widgets.MineStyleVideoItemDecoration;
import com.cooleshow.teacher.widgets.StyleEmptyView;
import com.cooleshow.usercenter.bean.SetDetailBean;
import com.cooleshow.usercenter.helper.UserHelper;
import com.daya.live_teaching.utils.GlideEngine;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions3.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

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

import io.rong.imkit.utils.StatusBarUtil;
import io.rong.imkit.utils.helper.ChatGroupHelper;
import io.rong.imkit.utils.helper.OpenChatHelper;

/**
 * 创建日期：2022/5/13 14:02
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_STYLE_PAGE)
public class MineStylePageActivity extends BaseMVPActivity<ActivityMineStylePageBinding, MineStylePagePresenter> implements MineStylePageContract.MineStylePageView, View.OnClickListener {
    private final int SELECT_RESULT = 1001;
    private final int CHOOSE_VIDEO = 1002;
    public final int REQUEST_CODE_LOCAL = 0x19;
    public final int REQUEST_CODE_AVATAR = 0x20;

    public static final String GENDER_TYPE_MALE = "1";//男
    public static final String GENDER_TYPE_FEMALE = "0";//女
    private EditText etSelfIntroduction;
    private RecyclerView videoList;
    private MineStyleVideoAdapter mMineStyleVideoListAdapter;
    private RecyclerView rvTopSelect;
    private TeachableSelectAdapter teachableSelectAdapter;
    private TeacherSelfStyleInfoBean myStyleInfoBean = null;
    private List<TeachableInstrumentBean> selectTeachableInstrument = new ArrayList<>();
    private int currentUploadCoverPosition = -1;
    private boolean isShowAuditTip = false;
    private String currentAvatarUrl;
    private String currentNickName;
    private String isReal;
    private String currentGander = "";
    private boolean isModify = false;


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_select_fans:
                isModify = true;
                Bundle bundle = new Bundle();
                bundle.putSerializable("selectTeachableInstrument", (Serializable) selectTeachableInstrument);
                ARouter.getInstance().build(RouterPath.MineCenter.MINE_TEACHABLE_INSTRUMENT)
                        .withBundle("bundle", bundle)
                        .navigation(this, SELECT_RESULT);
                break;
            case R.id.tv_right_text:
            case R.id.tv_save:
                myStyleInfoBean.styleVideo.clear();
                for (TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean : videoBeanList) {
                    if (styleVideoBean.type != 1) {
                        if (TextUtils.isEmpty(styleVideoBean.cover)) {
                            ToastUtil.getInstance().showShort("请上传个人风采视频封面");
                            return;
                        }
                        myStyleInfoBean.styleVideo.add(styleVideoBean);
                    }
                }
                myStyleInfoBean.introduction = etSelfIntroduction.getText().toString().trim();
                String subjectIdStr = "";
                String subjectNameStr = "";
                for (TeachableInstrumentBean teachableInstrumentBean : selectTeachableInstrument) {
                    subjectIdStr += "," + teachableInstrumentBean.id;
                    subjectNameStr += "," + teachableInstrumentBean.name;
                }
                if (subjectIdStr.startsWith(",")) {
                    subjectIdStr = subjectIdStr.replaceFirst(",", "");
                }
                if (subjectNameStr.startsWith(",")) {
                    subjectNameStr = subjectNameStr.replaceFirst(",", "");
                }
                myStyleInfoBean.subjectId = subjectIdStr;
                myStyleInfoBean.subjectName = subjectNameStr;
                presenter.saveTeacherStyle(GsonUtils.toJson(myStyleInfoBean));
                break;
            case R.id.tv_add_style:
                getVideoPermission();
                break;
            case R.id.iv_avatar:
                selectHeader();
                break;
            case R.id.view_nick_click:
                //昵称修改
                if (!TextUtils.isEmpty(currentNickName)) {
                    ARouter.getInstance().build(RouterPath.MineCenter.MINE_MODIFY_NICKNAME)
                            .withString("userName", currentNickName)
                            .navigation(this);
                }
                break;
            case R.id.view_real_name_click:
                //实名认证
                if (!TextUtils.isEmpty(isReal) && TextUtils.equals(isReal, "0")) {
                    ARouter.getInstance().build(RouterPath.MineCenter.MINE_PERSONAL_CERTIFICATION)
                            .navigation(this);
                }
                break;
            case R.id.view_phone_click:
                //手机号
                ARouter.getInstance().build(RouterPath.MineCenter.MINE_CHECK_MODIFY_PHONENUM)
                        .navigation(this);
                break;
            case R.id.tv_edit_introduce:
                //编辑个人介绍
                isModify = true;
                SoftKeyboardUtils.showSoftKeyboard(viewBinding.etSelfIntroduction);
                if (!TextUtils.isEmpty(viewBinding.etSelfIntroduction.getText())) {
                    int length = viewBinding.etSelfIntroduction.getText().length();
                    viewBinding.etSelfIntroduction.setSelection(length);
                }
                break;

            case R.id.tv_male:
                if (TextUtils.equals(currentGander, GENDER_TYPE_MALE)) {
                    return;
                }
                modifySex(true);
                break;
            case R.id.tv_female:
                if (TextUtils.equals(currentGander, GENDER_TYPE_FEMALE)) {
                    return;
                }
                modifySex(false);
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode
                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    @Override
    public void initData() {
        super.initData();
        if (presenter != null) {
            presenter.getTeacherSelfStyle();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter != null) {
            presenter.getUserInfoDetail();
        }
    }

    private List<TeacherSelfStyleInfoBean.StyleVideoBean> videoBeanList = new ArrayList<>();

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "我的风采编辑");
        viewBinding.toolbarInclude.tvRightText.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRightText.setText("保存");
        viewBinding.toolbarInclude.tvRightText.setTextColor(getResources().getColor(R.color.white));
        viewBinding.toolbarInclude.tvRightText.setTextSize(14);
        viewBinding.toolbarInclude.tvRightText.setBackgroundResource(com.cooleshow.base.R.drawable.shape_2dc7aa_14dp);
        viewBinding.toolbarInclude.tvRightText.setGravity(Gravity.CENTER);
        viewBinding.toolbarInclude.tvRightText.setPadding(SizeUtils.dp2px(12), SizeUtils.dp2px(4), SizeUtils.dp2px(12), SizeUtils.dp2px(4));
        etSelfIntroduction = viewBinding.etSelfIntroduction;
        videoList = viewBinding.rvTeacherStyleVideo;
        viewBinding.toolbarInclude.tvRightText.setOnClickListener(this);
        viewBinding.tvSelectFans.setOnClickListener(this);
        viewBinding.tvSave.setOnClickListener(this);
        viewBinding.tvAddStyle.setOnClickListener(this);
        viewBinding.ivAvatar.setOnClickListener(this);
        viewBinding.viewNickClick.setOnClickListener(this);
        viewBinding.viewRealNameClick.setOnClickListener(this);
        viewBinding.viewPhoneClick.setOnClickListener(this);
        viewBinding.tvEditIntroduce.setOnClickListener(this);
        viewBinding.tvMale.setOnClickListener(this);
        viewBinding.tvFemale.setOnClickListener(this);
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        videoList.setLayoutManager(manager);
//        addEmptyVideoBean();
        mMineStyleVideoListAdapter = new MineStyleVideoAdapter(videoBeanList);
        MineStyleVideoItemDecoration itemDecoration = new MineStyleVideoItemDecoration(SizeUtils.dp2px(20), SizeUtils.dp2px(14), 0, SizeUtils.dp2px(14), SizeUtils.dp2px(3.5f));
        videoList.addItemDecoration(itemDecoration);
        videoList.setAdapter(mMineStyleVideoListAdapter);
        mMineStyleVideoListAdapter.setItemAddClickAction(new MineStyleVideoAdapter.ItemAddClickAction() {
            @Override
            public void add() {
                getVideoPermission();
            }

            @Override
            public void play(String videoUrl) {
                VideoPlayActivity.start(MineStylePageActivity.this, videoUrl);
            }

            @Override
            public void delete(String url) {
                for (TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean : videoBeanList) {
                    if (styleVideoBean.type == 0 && styleVideoBean.videoUrl.equals(url)) {
                        if (TextUtils.equals(MineStyleVideoAdapter.VIDEO_AUDIT_STATUS_PASS, styleVideoBean.authStatus)) {
                            int passVideoCount = getPassVideoCount();
                            if (passVideoCount == 1) {
                                ToastUtil.getInstance().showShort("需至少保留一个通过审核风采视频");
                                return;
                            }
                        }
                        videoBeanList.remove(styleVideoBean);
                        break;
                    }
                }
                mMineStyleVideoListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onUploadCover(int position) {
                currentUploadCoverPosition = position;
                toAlbum(false);
            }
        });
        rvTopSelect = viewBinding.rvTopSelect;
        //设置LayoutManager
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
        //主轴为水平方向，起点在左端
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        //按正常方向换行
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
        //定义项目在副轴轴上如何对齐
        flexboxLayoutManager.setAlignItems(AlignItems.CENTER);
        //多个轴对齐方式
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        rvTopSelect.setLayoutManager(flexboxLayoutManager);
        teachableSelectAdapter = new TeachableSelectAdapter(selectTeachableInstrument);
        rvTopSelect.setAdapter(teachableSelectAdapter);
        teachableSelectAdapter.setOnItemClickListener((adapter, view, position) -> {
            isModify = true;
            selectTeachableInstrument.remove(position);
            teachableSelectAdapter.notifyDataSetChanged();
        });
        addETListener();
    }

    private void switchGanderUI(int selectId) {
        if (selectId == R.id.tv_male) {
            viewBinding.tvMale.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_check_select_20dp), null, null, null);
            viewBinding.tvFemale.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_check_unselect), null, null, null);
        } else {
            viewBinding.tvMale.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_check_unselect), null, null, null);
            viewBinding.tvFemale.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_check_select_20dp), null, null, null);
        }
    }


    /**
     * 获取已过审视频
     *
     * @return
     */
    private int getPassVideoCount() {
        if (videoBeanList == null || videoBeanList.size() == 0) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < videoBeanList.size(); i++) {
            TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean = videoBeanList.get(i);
            if (TextUtils.equals(MineStyleVideoAdapter.VIDEO_AUDIT_STATUS_PASS, styleVideoBean.authStatus)) {
                count++;
            }
        }
        return count;
    }


    private void toAlbum(boolean isUploadAvatar) {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        goAlbum(isUploadAvatar);
                    } else {
                        ToastUtil.getInstance().show(this, "请选择存储和相机权限！");
                    }
                });
    }

    private void goAlbum(boolean isUploadAvatar) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(com.cooleshow.base.R.style.picture_daya_style)// 主题样式设置 具体参考 values/styles   用法：R .style.picture.white.style
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .enableCrop(true)// 是否裁剪 true or false
                .cutOutQuality(90)
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .compress(true)// 是否压缩 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .forResult(isUploadAvatar ? REQUEST_CODE_AVATAR : REQUEST_CODE_LOCAL);
    }

    private void addETListener() {
        etSelfIntroduction.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    isModify = true;
                }
            }
        });
        etSelfIntroduction.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                String trim = etSelfIntroduction.getText().toString();
//                viewBinding.tvNumHint.setText(trim.length() + "/200");
            }
        });
    }

    @Override
    protected ActivityMineStylePageBinding getLayoutView() {
        return ActivityMineStylePageBinding.inflate(getLayoutInflater());
    }

    @Override
    protected MineStylePagePresenter createPresenter() {
        return new MineStylePagePresenter();
    }

    @Override
    public void getSelfStyleSuccess(TeacherSelfStyleInfoBean styleInfoBean) {
        myStyleInfoBean = styleInfoBean;
        //个人介绍
        viewBinding.etSelfIntroduction.setText(styleInfoBean.introduction);
        //视频信息
        if (mMineStyleVideoListAdapter != null) {
            videoBeanList.clear();
            videoBeanList.addAll(styleInfoBean.styleVideo);
//            addEmptyVideoBean();
            mMineStyleVideoListAdapter.notifyDataSetChanged();
        }
        if (!TextUtils.isEmpty(styleInfoBean.subjectId)) {
            if (styleInfoBean.subjectId.contains(",")) {
                try {
                    String[] splitId = styleInfoBean.subjectId.split(",");
                    String[] splitName = styleInfoBean.subjectName.split(",");
                    for (int i = 0; i < splitId.length; i++) {
                        TeachableInstrumentBean instrumentBean = new TeachableInstrumentBean();
                        instrumentBean.id = Integer.parseInt(splitId[i]);
                        instrumentBean.name = splitName[i];
                        selectTeachableInstrument.add(instrumentBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                TeachableInstrumentBean instrumentBean = new TeachableInstrumentBean();
                instrumentBean.id = Integer.parseInt(styleInfoBean.subjectId);
                instrumentBean.name = styleInfoBean.subjectName;
                selectTeachableInstrument.add(instrumentBean);
            }
            teachableSelectAdapter.notifyDataSetChanged();

        }
    }


    @Override
    public void saveTeacherStyleSuccess(TeacherSelfStyleInfoBean styleInfoBean) {
        if (isShowAuditTip) {
            ToastUtil.getInstance().showShort("提交成功，请耐心等待审核");
        } else {
            ToastUtil.getInstance().showShort("保存成功");
        }
        finish();
    }

    @Override
    public void upLoadVideoSuccess(TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean) {
        videoBeanList.add(0, styleVideoBean);
        isShowAuditTip = true;
        isModify = true;
        mMineStyleVideoListAdapter.notifyDataSetChanged();

    }

    @Override
    public void upLoadVideoFailure() {
    }

    @Override
    public void upLoadVideoCoverSuccess(String coverUrl) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (mMineStyleVideoListAdapter == null) {
            return;
        }
        if (currentUploadCoverPosition != -1 && currentUploadCoverPosition < videoBeanList.size()) {
            videoBeanList.get(currentUploadCoverPosition).cover = coverUrl;
            isShowAuditTip = true;
            isModify = true;
            mMineStyleVideoListAdapter.notifyItemChanged(currentUploadCoverPosition);
        }
    }

    @Override
    public void upLoadVideoCoverFail() {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        ToastUtil.getInstance().showShort("封面上传失败");
    }

    @Override
    public void upLoadImageSuccess(String avatarUrl) {
        if (!checkActivityExist()) {
            return;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("avatar", avatarUrl);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.submitSetDetail(jsonObject.toString());
    }

    @Override
    public void upLoadImageFailure() {

    }

    @Override
    public void submitSetDetailSuccess(SetDetailBean setDetailBean) {
        if (!checkActivityExist()) {
            return;
        }
        this.currentGander = String.valueOf(setDetailBean.gender);
        switchGanderUI(TextUtils.equals(GENDER_TYPE_MALE, currentGander) ? R.id.tv_male : R.id.tv_female);
        ToastUtil.getInstance().showShort("修改成功");
        if (setDetailBean != null) {
            GlideUtils.INSTANCE.loadImage(this, setDetailBean.avatar, viewBinding.ivAvatar, R.drawable.icon_teacher_default_head);
        }
    }

    @Override
    public void getUserInfoSuccess(TeacherUserInfo data) {
        if (!checkActivityExist()) {
            return;
        }
        if (data != null) {
            //头像
            this.currentAvatarUrl = data.heardUrl;
            GlideUtils.INSTANCE.loadImage(MineStylePageActivity.this, data.heardUrl, viewBinding.ivAvatar, R.drawable.icon_teacher_default_head);
            //名称
            String teacherName = UserHelper.getTeacherName(data.username, data.userId);
            this.currentNickName = teacherName;
            viewBinding.tvNickname.setText(teacherName);
            //实名状态
            this.isReal = String.valueOf(data.isReal);
            viewBinding.tvRealNameStatus.setText(data.isReal == 1 ? "已认证" : "未认证");
            viewBinding.tvRealNameStatus.setTextColor(getResources().getColor(data.isReal == 1 ? com.cooleshow.base.R.color.color_cccccc : com.cooleshow.base.R.color.color_ff0000));
            //性别
            this.currentGander = data.gender;
            switchGanderUI(TextUtils.equals(data.gender, GENDER_TYPE_MALE) ? R.id.tv_male : R.id.tv_female);
            //手机号
            viewBinding.tvPhoneNum.setText(data.phone);
        }
    }

    @Override
    public void getFunGroupList(List<ContactRoomListBean> list) {
    }

    private void addEmptyVideoBean() {
        TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean = new TeacherSelfStyleInfoBean.StyleVideoBean();
        styleVideoBean.type = 1;
        videoBeanList.add(styleVideoBean);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_RESULT) {
                List<TeachableInstrumentBean> dataSerializableExtra = (List<TeachableInstrumentBean>) data.getSerializableExtra("selectTeachableInstrument");
                selectTeachableInstrument.clear();
                selectTeachableInstrument.addAll(dataSerializableExtra);
                teachableSelectAdapter.notifyDataSetChanged();
            } else if (requestCode == CHOOSE_VIDEO) {
                Uri uri = data.getData();
                String v_path = FileUtils.getFilePathForN(uri, MineStylePageActivity.this);
                presenter.uploadVideo(MineStylePageActivity.this, v_path);
            } else if (requestCode == REQUEST_CODE_AVATAR) {
                if (data != null) {
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    String v_path = null;
                    if (selectList != null && selectList.size() > 0) {
                        v_path = selectList.get(0).getCompressPath();
                    }
                    if (!TextUtils.isEmpty(v_path)) {
                        boolean isImg = MyFileUtils.isImg(v_path);
                        if (isImg) {
                            presenter.upLoadImage(MineStylePageActivity.this, v_path);
                        } else {
                            ToastUtil.getInstance().showShort("请选择图片类型文件");
                        }
                    }
                }
            } else if (requestCode == REQUEST_CODE_LOCAL) {
                if (data != null) {
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    String v_path = null;
                    if (selectList != null && selectList.size() > 0) {
                        v_path = selectList.get(0).getCompressPath();
                    }
                    if (!TextUtils.isEmpty(v_path)) {
                        boolean isImg = MyFileUtils.isImg(v_path);
                        if (isImg) {
                            if (presenter != null) {
                                presenter.uploadCover(MineStylePageActivity.this, v_path);
                            }
                        } else {
                            ToastUtil.getInstance().showShort("请选择图片类型文件");
                        }
                    }
                }
            }
        }
    }


    private void getVideoPermission() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        chooseVideo();
                    } else {
                        ToastUtil.getInstance().show(this, "请选择存储和相机权限！");
                    }
                });
    }

    private void chooseVideo() {
        Intent intent = new Intent();
        intent.setType("video/*"); //选择视频 (mp4 3gp 是android支持的视频格式)
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        ActivityUtils.startActivityForResult(this, intent, CHOOSE_VIDEO);

    }

    private void modifySex(boolean isMale) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("gender", isMale ? 1 : 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.submitSetDetail(jsonObject.toString());
    }


    private void selectHeader() {
        PopupUtil.showInBottom(this, R.layout.pop_modify_header, (view, popupWindow) -> {
            TextView tv_camera = view.findViewById(R.id.tv_camera);
            TextView tv_album = view.findViewById(R.id.tv_album);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toCamera();
                    popupWindow.dismiss();
                }
            });
            tv_album.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toAlbum(true);
                    popupWindow.dismiss();
                }
            });
            tv_cancel.setOnClickListener(view1 -> popupWindow.dismiss());
        });
    }

    private void toCamera() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        goCamera();
                    } else {
                        ToastUtil.getInstance().show(this, "请选择存储和相机权限！");
                    }
                });
    }

    private void goCamera() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(com.cooleshow.base.R.style.picture_daya_style)// 主题样式设置 具体参考 values/styles   用法：R .style.picture.white.style
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .enableCrop(true)// 是否裁剪 true or false
                .cutOutQuality(100)
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .compress(true)// 是否压缩 true or false
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .forResult(REQUEST_CODE_AVATAR);
    }


    @Override
    public void onBackPressed() {
        if (isModify) {
            showModifySaveTipDialog();
            return;
        } else {
            super.onBackPressed();
        }
    }

    private void showModifySaveTipDialog() {
        CommonDialog commonDialog = new CommonDialog(this);
        commonDialog.show();
        commonDialog.setTitle("提示");
        commonDialog.setContent("您尚未保存修改信息，返回后将取消修改");
        commonDialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null) {
                    commonDialog.dismiss();
                }
                finish();
            }
        });
        commonDialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null) {
                    commonDialog.dismiss();
                }
            }
        });
    }
}
