package com.common.im.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.im.adapter.AddPhotoListAdapter;
import com.common.im.contract.ImAppealContract;
import com.common.im.presenter.ImAppealPresenter;
import com.common.im_ui.R;
import com.common.im_ui.databinding.ActivityImAppealBinding;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.constanst.UploadConstants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.utils.helper.upload.UploadHelper;
import com.daya.live_teaching.utils.GlideEngine;
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 java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建日期：2022/6/13 13:54
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.ChatCenter.CHAT_IM_APPEAL)
public class ImAppealActivity extends BaseMVPActivity<ActivityImAppealBinding, ImAppealPresenter> implements ImAppealContract.ImAppealView {


    private EditText et_content;
    private Button btn_commit;
    private RecyclerView recyclerView;
    private int maxSelectNum = 3;
    private AddPhotoListAdapter addPhotoListAdapter;
    List<LocalMedia> selectList = new ArrayList<>();
    List<String> urlList = new ArrayList<>();
    private String targetId;
    private String name;
    private String type;
    private String memo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "举报");

        Intent intent = getIntent();
        targetId = intent.getStringExtra("targetId");
        name = intent.getStringExtra("name");
        type = intent.getStringExtra("type");
        et_content=viewBinding.etContent;
        btn_commit=viewBinding.btnCommit;
        recyclerView=viewBinding.recyclerView;
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        addNewEmpty();
        addPhotoListAdapter = new AddPhotoListAdapter(selectList);
        recyclerView.setAdapter(addPhotoListAdapter);
        addPhotoListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                LocalMedia item = (LocalMedia) adapter.getItem(position);
                if (item.getPath().equals("123")){
                    PictureSelector.create(ImAppealActivity.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.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                            .maxSelectNum(maxSelectNum+1 - selectList.size())
                            .compress(true)// 是否压缩 true or false
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                }else{
                    ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_PHOTO_PREVIEW)
                            .withInt("position", position)
                            .withParcelableArrayList("list", (ArrayList<? extends Parcelable>)selectList)
                            .navigation(ImAppealActivity.this,100);
                }
            }
        });
        btn_commit.setOnClickListener(view -> {
            if (null == selectList || selectList.size() <= 0) {
                ToastUtil.getInstance().showShort("请选择聊天截图");
                return;
            }
            memo = et_content.getText().toString().trim();
            if (TextUtils.isEmpty(memo)) {
                ToastUtil.getInstance().showShort("请输入投诉的理由");
                return;
            }
            for (int i = 0; i < selectList.size(); i++) {
                String compressPath = selectList.get(i).getCompressPath();
                if (!TextUtils.isEmpty(compressPath)) {
                    upLoadVideo(this,compressPath);
                }
            }
        });
    }

    private void addNewEmpty(){
        LocalMedia localMedia=new LocalMedia();
        localMedia.setPath("123");
        selectList.add(localMedia);
    }


    public void upLoadVideo(Activity activity, String filePath) {
        UploadHelper uploadHelper = new UploadHelper(activity, UploadConstants.UPLOAD_TYPE_IM);
        uploadHelper.uploadFile(new File(filePath));
        uploadHelper.setUpLoadCallBack(new UploadHelper.UpLoadCallBack() {
            @Override
            public void onSuccess(String url) {
                urlList.add(url);
                if (urlList.size() == selectList.size()) {
                    String attachment = "";
                    for (int i = 0; i < urlList.size(); i++) {
                        attachment += ("," + urlList.get(i));
                    }
                    urlList.clear();
                    String attachments = attachment.substring(1);

                    presenter.sysImComplaint(memo,targetId,type,attachments);
                }
            }

            @Override
            public void onFailure() {

            }
        });
    }



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

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


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(0,list);
                    if (selectList.size()>maxSelectNum){
                        selectList.remove(maxSelectNum);
                    }
                    addPhotoListAdapter.notifyDataSetChanged();

                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //                    GlideImageLoaderUtils.getInstance().loadCircleImage(this,selectList.get(0).getCutPath(),ivPortrait);

                    break;
                case 100:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> list1 = data.getParcelableArrayListExtra("list");
                    selectList.clear();
                    selectList.addAll(list1);
                    if (selectList.size()<maxSelectNum){
                        addNewEmpty();
                    }
                    addPhotoListAdapter.notifyDataSetChanged();
                    break;

            }
        }
    }

    @Override
    public void sysImComplaintSuccess() {
        ToastUtil.getInstance().showShort("已收到您的投诉，我们会认真审核并处理");
        finish();
    }
}
