package com.bokecc.livemodule.live.qa.qainputlayout;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bokecc.dwlivedemo.R;
import com.bokecc.dwlivedemo.activity.ImageDetailsActivity;
import com.bokecc.dwlivedemo.utils.PermissionRequestBean;
import com.bokecc.livemodule.live.DWLiveCoreHandler;
import com.bokecc.livemodule.utils.DebouncingUtils;
import com.bokecc.livemodule.utils.FileUtils;
import com.bokecc.livemodule.view.BaseRelativeLayout;
import com.bokecc.sdk.mobile.live.BaseLiveCallback;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.pojo.QaSendErrorBean;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

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

/**
 * Copyright (C), 20105-2021, 创盛视联数码科技（北京）有限公司
 * FileName:
 * Author: huanghai
 * Date: 2023/3/3
 * Description:
 */
public class QaInputLayout extends BaseRelativeLayout{


    public static final int REQUEST_CODE_CHOOSE = 10055;

    private ArrayList<QaInputItemBean> mList = new ArrayList<>();
    private ImageView ivQaInputListMode;
    private ImageView ivQaInputShowImg;
    private Button btnQaInputSend;
    private RecyclerView rvQaInputImgList;
    private HorizontalScrollView scrollQaInputImgListCon;
    private RelativeLayout rlQaInputAddBtn;
    private QaInputImageListAdapter adapter;

    private boolean isShowImgList = false;

    private boolean isSending = false;
    private EditText etQaInputContent;
    private LinearLayout llQaInputContentCont;
    private ImageView ivQaInputAddIcon;

    private QaSendListener qaSendListener;

    private boolean isLookSelf = false;

    private QaImagePanelListener qaImagePanelListener;

    private boolean keyUp = false;

    private InputMethodManager mImm;

    public QaInputLayout(Context context) {
        this(context, null, 0);
    }

    public QaInputLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public QaInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    @Override
    public void initViews() {

    }


    private void initView() {
        Context context = getContext();
        if (!(context instanceof Activity)) {
            return;
        }
        mList.clear();
        View view = View.inflate(context, R.layout.layout_qa_input, this);
        mImm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);


        ivQaInputListMode = view.findViewById(R.id.iv_qa_input_list_mode);
        ivQaInputShowImg = view.findViewById(R.id.iv_qa_input_show_img);
        btnQaInputSend = view.findViewById(R.id.btn_qa_input_send);
        scrollQaInputImgListCon = view.findViewById(R.id.scroll_qa_input_img_list_con);
        llQaInputContentCont = view.findViewById(R.id.ll_qa_input_content_cont);
        rvQaInputImgList = view.findViewById(R.id.rv_qa_input_img_list);
        rlQaInputAddBtn = view.findViewById(R.id.rl_qa_input_add_btn);
        ivQaInputAddIcon = view.findViewById(R.id.iv_qa_input_add_icon);
        //输入框
        etQaInputContent = view.findViewById(R.id.et_qa_input_content);

        rvQaInputImgList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));

        adapter = new QaInputImageListAdapter(context);

        rvQaInputImgList.setAdapter(adapter);

        rvQaInputImgList.setHasFixedSize(true);
        rvQaInputImgList.setNestedScrollingEnabled(false);

        if (DWLiveCoreHandler.getInstance().isAllowQaImageUpload()) {
            ivQaInputShowImg.setVisibility(View.VISIBLE);
        } else {
            ivQaInputShowImg.setVisibility(View.GONE);
        }

        showImgList(false);
        adapter.setOnItemClickListener(new QaInputImageListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (isSending) {
                    return;
                }
                showGallery(position);
            }

            @Override
            public void onItemRemoveClick(int position) {
                if (isSending) {
                    return;
                }

                removeImg(position);

            }

            @Override
            public void onItemWarningClick(int position) {
                if (isSending) {
                    return;
                }

                showWarning(position);
            }
        });

        ivQaInputListMode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //1s 防抖
                if (DebouncingUtils.isValid(v, 1000)) {
                    isLookSelf = !isLookSelf;
                    if (qaSendListener != null) {
                        qaSendListener.onLookStateChanged(isLookSelf);
                    }
                    if (isLookSelf) {
                        ivQaInputListMode.setImageResource(R.drawable.question_ic_lookoff);
                    } else {
                        ivQaInputListMode.setImageResource(R.drawable.question_ic_lookon);
                    }
                }

            }
        });

        ivQaInputShowImg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImg();

            }
        });
        rlQaInputAddBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImg();
            }
        });


        btnQaInputSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //限制2s调用1次
                boolean debounce = DebouncingUtils.isValid(btnQaInputSend, 2000);
                if (debounce) {
                    if (DWLive.getInstance().getPlayStatus() == DWLive.PlayStatus.PREPARING) {
                        toastOnUiThread("直播未开始，无法提问");
                        return;
                    }

                    // 直播中，提问判断内容是否符合要求，符合要求，进行提问
                    String questionMsg = etQaInputContent.getText().toString().trim();
                    if (TextUtils.isEmpty(questionMsg)) {
                        toastOnUiThread("输入信息不能为空");
                    } else {
                        try {
                            isSending = true;
                            enableViews(false);
                            //设置所有图片上传中状态
                            List<String> imgPathList = new ArrayList<>();
                            for (int i = 0; i < mList.size(); i++) {
                                QaInputItemBean qaInputItemBean = mList.get(i);
                                if (qaInputItemBean != null && !TextUtils.isEmpty(qaInputItemBean.getFilePath())) {
                                    imgPathList.add(qaInputItemBean.getFilePath());
                                }
                            }
                            setAllImgItemState(QaInputItemBean.STATE_UPLOADING);

                            DWLive.getInstance().sendQuestionMsg(questionMsg, imgPathList, new BaseLiveCallback<String, QaSendErrorBean>() {
                                @Override
                                public void onError(QaSendErrorBean error) {
                                    handleQaSendError(error);
                                }

                                @Override
                                public void onSuccess(String msg) {
                                    handleQaSendSuccess(msg);

                                }
                            });

                            hideKeyboard();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                }


            }
        });


        etQaInputContent.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) {
                checkShowModeButton();
                if (s.length() > 0) {
                    llQaInputContentCont.setBackgroundResource(R.drawable.shape_qainput_input_bg_2);
                } else {
                    llQaInputContentCont.setBackgroundResource(R.drawable.shape_qainput_input_bg);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    private void checkShowModeButton() {
        //et中存在文字或者输入框弹起状态
        if (etQaInputContent.getText().length()>0||keyUp){
            ivQaInputListMode.setVisibility(View.GONE);
        }else {
            ivQaInputListMode.setVisibility(View.VISIBLE);
        }

    }

    private void selectImg() {
        if (mContext==null||!(mContext instanceof Activity)){
            return;
        }
        //防抖
        if (DebouncingUtils.isValid("selectImg", 1000) && mList != null) {
            final int selectSize = 6 - mList.size();
            if (selectSize == 0) {
                toastOnUiThread("最多选择6张图片");
                return;
            }
            //检查相机与存储权限
            PermissionRequestBean permissionRequestBean = new PermissionRequestBean(new String[]{Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE});

            permissionRequestBean.request((Activity) mContext, new PermissionRequestBean.PermissionCallback() {
                @Override
                public void onResult(boolean success) {
                    if (!success){
                        Toast.makeText(mContext, "前往系统权限设置页面中手动打开相机与存储权限后方可使用扫码功能", Toast.LENGTH_SHORT).show();
                    }else {
                        String authority = getContext().getPackageName() + ".interact.fileprovider";
                        Matisse.from((Activity) getContext())
                                .choose(MimeType.ofImage())
                                .countable(true)
                                .maxSelectable(selectSize)
                                .showSingleMediaType(true)
                                .capture(true)
                                .theme(R.style.Matisse_Dracula)
                                .captureStrategy(new CaptureStrategy(true, authority))
                                .imageEngine(new MatisseGlideEngine())
                                .forResult(REQUEST_CODE_CHOOSE);
                    }
                }

            });

        } else {
            toastOnUiThread("请勿重复点击");
        }

    }

    private void handleQaSendError(QaSendErrorBean error) {
        isSending = false;
        enableViews(true);
        String errorMsg = getSendErrorMsg(error.getErrorCode());
        if (TextUtils.isEmpty(errorMsg)){
            errorMsg = error.getErrorMsg();
        }
        toastOnUiThread(errorMsg);

        setAllImgItemState(QaInputItemBean.IDLE);
        if (error.getImgErrorList() != null && error.getImgErrorList().size() > 0) {
            for (int i = 0; i < error.getImgErrorList().size(); i++) {
                QaSendErrorBean.QaSendImgError qaSendImgError = error.getImgErrorList().get(i);
                int index = qaSendImgError.getOrder();
                if (mList.size() > index) {
                    QaInputItemBean itemBean = mList.get(index);
                    if (itemBean != null) {
                        itemBean.setState(QaInputItemBean.STATE_UPLOAD_FAILED);
                        String fileError = getImgFileErrorMsg(qaSendImgError.getErrorCode());
                        if (TextUtils.isEmpty(fileError)){
                            fileError = qaSendImgError.getErrorMsg();
                        }
                        itemBean.setWarning(fileError);
                    }
                }
            }
            refreshList();
        }
    }

    private void setAllImgItemState(int state) {
        for (int i = 0; i < mList.size(); i++) {
            QaInputItemBean itemBean = mList.get(i);
            if (itemBean != null) {
                itemBean.setState(state);
            }
        }
        refreshList();
    }

    private void handleQaSendSuccess(String msg) {
        isSending = false;
        etQaInputContent.setText("");
        //  设置所有item的状态
        setAllImgItemState(QaInputItemBean.STATE_UPLOAD_SUCCESS);

        toastOnUiThread("发送成功");
        mList.clear();
        refreshList();
        //隐藏图片上传布局
        showImgList(false);
        enableViews(true);
    }

    private void showGallery(int index) {
        Context context = getContext();
        if (!(context instanceof Activity)) {
            return;
        }
        if (mList != null && mList.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mList.size(); i++) {
                QaInputItemBean bean = mList.get(i);

                if (bean != null && bean.getUri() != null && !TextUtils.isEmpty(bean.getUri().toString())) {
                    sb.append(bean.getUri().toString());
                    if (i < mList.size() - 1) {
                        sb.append("###");
                    }
                }
            }

            // 2023/3/9 显示画廊
            Intent intent = new Intent(context, ImageDetailsActivity.class);
            intent.putExtra("imageUrl", sb.toString());
            intent.putExtra("hasDelete", true);
            intent.putExtra("index", index);
            ((Activity) context).startActivityForResult(intent, ImageDetailsActivity.REQUEST_CODE);
        }
    }

    private void hideKeyboard() {
        if (mImm!=null){
            mImm.hideSoftInputFromWindow(etQaInputContent.getWindowToken(), 0);
        }
    }

    private void showWarning(int position) {
        if (mList != null && mList.size() > position) {
            QaInputItemBean qaInputItemBean = mList.get(position);
            if (qaInputItemBean != null && !TextUtils.isEmpty(qaInputItemBean.getWarning())) {
                toastOnUiThread(qaInputItemBean.getWarning());
            }
        }
    }

    private void removeImg(int index) {
        if (mList != null && mList.size() > index) {
            QaInputItemBean qaInputItemBean = mList.get(index);
            if (qaInputItemBean != null) {
                mList.remove(index);
                refreshList();
            }
        }
    }

    private void removeImg(List<Integer> indexList) {
        if (indexList.size() == 0) {
            return;
        } else if (indexList.size() == 1) {
            int p = indexList.get(0);
            if (mList != null && mList.size() > p) {
                QaInputItemBean qaInputItemBean = mList.get(p);
                if (qaInputItemBean != null) {
                    mList.remove(p);
                    refreshList();
                }
            }

        } else {
            List<QaInputItemBean> qaInputItemBeanList = new ArrayList<>();
            for (int i = 0; i < mList.size(); i++) {
                if (!indexList.contains(i)) {
                    QaInputItemBean bean = mList.get(i);
                    qaInputItemBeanList.add(bean);
                }
            }
            mList.clear();
            mList.addAll(qaInputItemBeanList);
            refreshList();
        }

    }

    private void enableViews(boolean enable) {
        //  2023/3/9 设置禁用、非禁用状态view的显示
        if (enable) {
            ivQaInputShowImg.setImageResource(R.drawable.icon_qainput_img_label);
            ivQaInputShowImg.setClickable(true);

            ivQaInputAddIcon.setImageResource(R.drawable.icon_qa_input_img_add);
            rlQaInputAddBtn.setClickable(true);
        } else {
            ivQaInputShowImg.setImageResource(R.drawable.icon_qainput_img_label_disable);
            ivQaInputShowImg.setClickable(false);

            ivQaInputAddIcon.setImageResource(R.drawable.icon_qa_input_img_add_disable);
            rlQaInputAddBtn.setClickable(false);
        }
    }

    private void showImgList(boolean show) {
        isShowImgList = show;
        if (show) {
            scrollQaInputImgListCon.setVisibility(View.VISIBLE);
            if (qaImagePanelListener != null) {
                qaImagePanelListener.onImagePanelShow();
            }
        } else {
            scrollQaInputImgListCon.setVisibility(View.GONE);
            if (qaImagePanelListener != null) {
                qaImagePanelListener.onImagePanelHide();
            }
        }
    }



    public void onKeyboardHeightChanged(int height, int orientation) {
        if (height > 5) {
            keyUp = true;
            setTranslationY(-height);
        } else {
            keyUp = false;
            setTranslationY(0);
        }
        keyboardUp();
    }

    private void keyboardUp() {
        checkShowModeButton();
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> uriList = Matisse.obtainResult(data);
            ContentResolver contentResolver = getContext().getContentResolver();
            for (Uri uri : uriList) {
                try {
                    String displayName = System.currentTimeMillis() + Math.round((Math.random() + 1) * 1000)
                            + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));


                    InputStream is = contentResolver.openInputStream(uri);
                    File cache = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath(), displayName);
                    FileUtils.copyFromInputStream(is, cache.getAbsolutePath());

                    QaInputItemBean qaInputItemBean = new QaInputItemBean();

                    qaInputItemBean.setFilePath(cache.getAbsolutePath());

                    qaInputItemBean.setUri(uri);

                    if (mList.size() < 7) {
                        mList.add(qaInputItemBean);
                    } else {
                        Toast.makeText(getContext(), "最多选择6张", Toast.LENGTH_SHORT).show();
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (mList.size()>=6){
                enableViews(false);
            }else {
                enableViews(true);
            }

            if (uriList.size() > 0) {
                //有返回数据刷新列表
                refreshList();
            }


        } else if (requestCode == ImageDetailsActivity.REQUEST_CODE && resultCode == ImageDetailsActivity.RESULT_CODE) {
            //查看图片返回，删除图片
            String delete = data.getStringExtra("delete");
            if (!TextUtils.isEmpty(delete)) {
                String[] strings = delete.split(",");
                List<Integer> list = new ArrayList<>();
                for (int i = 0; i < strings.length; i++) {
                    try {
                        int position = Integer.parseInt(strings[i]);
                        list.add(position);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (list.size() > 0) {
                    removeImg(list);
                }
            }
        }
    }

    private void refreshList() {
        if (adapter == null || mList == null) {
            return;
        }
        adapter.setList(mList);
        if (mList.size() >= 6) {
            rlQaInputAddBtn.setVisibility(View.GONE);
            showImgList(true);
        } else {
            rlQaInputAddBtn.setVisibility(View.VISIBLE);
            if (mList.size() == 0) {
                showImgList(false);
            } else {
                showImgList(true);
            }
        }
        if (mList.size()>=6){
            enableViews(false);
        }else {
            enableViews(true);
        }
    }


    public String getSendErrorMsg(int errorCode) {
        switch (errorCode){
            case QaSendErrorBean.ERROR_FILE_INVALID:
                //图片文件校验失败，包括 文件不存在、接口返回文件不合法
                return getContext().getString(R.string.str_qa_send_error_file_invalid);
            case QaSendErrorBean.ERROR_CONTENT_INVALID:
                //输入内容为空，或者输入内容长度大于1000
                return getContext().getString(R.string.str_qa_send_error_content_invalid);
            case QaSendErrorBean.ERROR_IMG_NUMBER_INVALID:
                //图片数量超出6张
                return getContext().getString(R.string.str_qa_send_error_number_invalid);
            case QaSendErrorBean.ERROR_DEBOUNCE:
                //1s防抖
                return getContext().getString(R.string.str_qa_send_error_debounce);
            case QaSendErrorBean.ERROR_NOT_LIVING:
                //直播未开始
                return getContext().getString(R.string.str_qa_send_error_not_living);
            case QaSendErrorBean.ERROR_REQUEST_FAILED:
                //网络请求失败
                return getContext().getString(R.string.str_qa_send_error_request_failed);
            case QaSendErrorBean.ERROR_FILE_UPLOAD_FAILED:
                //图片上传oss 失败
                return getContext().getString(R.string.str_qa_send_error_file_upload_failed);
            case QaSendErrorBean.ERROR_JSON_PARSE_FAILED:
                //发送问答失败，socket抛出错误
                return getContext().getString(R.string.str_qa_send_error_json_parse_failed);
            case QaSendErrorBean.ERROR_TEMPLATE_INVALID:
                //房间没有问答模板
                return getContext().getString(R.string.str_qa_send_error_template_invalid);
            case QaSendErrorBean.ERROR_NETWORK_ERROR:
                //网络错误
                return getContext().getString(R.string.str_qa_send_error_network_invalid);
            default:
                return "";
        }
    }

    public String getImgFileErrorMsg(int errorCode) {

        switch (errorCode){
            case QaSendErrorBean.QaSendImgError.ERROR_IMAGE_SIZE_INVALID:
                return getContext().getString(R.string.str_qa_send_img_error_size_over);
            case QaSendErrorBean.QaSendImgError.ERROR_IMAGE_SUFFIX_INVALID:
                return getContext().getString(R.string.str_qa_send_img_error_suffix_invalid);
            case QaSendErrorBean.QaSendImgError.ERROR_IMAGE_UPLOAD_FAILED:
                return getContext().getString(R.string.str_qa_send_img_error_upload_failed);
            case QaSendErrorBean.QaSendImgError.ERROR_LOGIN_FAILED:
                return getContext().getString(R.string.str_qa_send_img_error_login_failed);
            case QaSendErrorBean.QaSendImgError.ERROR_PARAMS_INVALID:
                return getContext().getString(R.string.str_qa_send_img_error_params_invalid);
            case QaSendErrorBean.QaSendImgError.ERROR_UNSPECIFIED:
                return getContext().getString(R.string.str_qa_send_img_error_unspecified);
            case QaSendErrorBean.QaSendImgError.ERROR_FILE_INVALID:
                return getContext().getString(R.string.str_qa_send_img_error_file_invalid);
            case QaSendErrorBean.QaSendImgError.ERROR_FILE_NOT_EXISTS:
                return getContext().getString(R.string.str_qa_send_img_error_file_not_exist);
            default:
                return "";
        }

    }

    public void setQaSendListener(QaSendListener qaSendListener) {
        this.qaSendListener = qaSendListener;
    }

    public void setQaImagePanelListener(QaImagePanelListener qaImagePanelListener) {
        this.qaImagePanelListener = qaImagePanelListener;
    }

    public boolean getIsImgListShow() {
        return isShowImgList;
    }

    public interface QaSendListener {
        void onLookStateChanged(boolean isSelf);
    }

    public interface QaImagePanelListener {
        void onImagePanelShow();

        void onImagePanelHide();
    }
}
