package com.efounder.chat.utils;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.activity.MobileShareActivity;
import com.efounder.chat.activity.TranslateSettingActivity;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.model.MessageMenu;
import com.efounder.chat.publicnumber.fragment.AppAccountFormStateSearchFragment;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.zxing.qrcode.QRManager;
import com.efounder.common.TCommonRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.service.Registry;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.JSONUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ActivityUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

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

import static android.content.Context.CLIPBOARD_SERVICE;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 消息长按弹窗（读取配置文件）
 * Created by yqs on 2018/10/22.
 */

public class ChatMessageMenuDialogUtil {
    public static AlertDialog alertDialog;
    private static List<StubObject> chatMessageMenuList;
    private static Map<Integer, List<StubObject>> messageMenuMap = new HashMap<>();


    public static void showDialog(final Context context, final IMStruct002 imStruct002, final
    BaseAdapter adapter) {
        final List<MessageMenu> menuList = new ArrayList<>();
        final List<String> titles = new ArrayList<>();
        boolean isSelf = false;//是否是自己发送的消息
        if (imStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
            isSelf = true;
        }
        if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_form_native) {
            //如果是原生表单消息（代记账），不允许删除消息，不弹框
            return;
        }
        if (imStruct002.isRecall() == true) {
            return;
        }

        //读取配置文件
        if (chatMessageMenuList == null) {
            chatMessageMenuList = Registry.getRegEntryList("ChatMessageMenu");
        }
        if (chatMessageMenuList == null) {
            //没有配置文件，按照之前的方式处理
            ChatAdapterDialogUtil.showDialog(context, imStruct002, adapter);
            return;
        } else {
            parseMessageTypeList(chatMessageMenuList);
            if (messageMenuMap.containsKey(Integer.valueOf(imStruct002.getMessageChildType()))) {
                parseShowMenu(menuList, titles, messageMenuMap.get(Integer.valueOf(imStruct002.getMessageChildType())), imStruct002);
            } else {
                //没有配置的默认都有删除消息的菜单
                menuList.add(new MessageMenu(imStruct002, ResStringUtil.getString(R.string.chat_delete_message), MessageMenu.DELETE_MESSAGE));
                titles.add(ResStringUtil.getString(R.string.chat_delete_message));
            }
        }
        //支持撤回消息，添加撤回消息
        if (isSelf && EnvSupportManager.isSupportRecallMessage()) {
            menuList.add(new MessageMenu(imStruct002, context.getResources().getString(R.string.wechatview_recallmessage), MessageMenu.RECALL_MESSAGE));
            titles.add(context.getResources().getString(R.string.wechatview_recallmessage));
        }
        //图片消息动态添加识别二维码
        if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_image) {
            String path = JSONUtil.parseJson(imStruct002.getMessage()).get("url").getAsString();
            final IdentifyQrCodeManager manager = new IdentifyQrCodeManager();
            Glide.with(context.getApplicationContext())
                    .asFile()
                    .apply(new RequestOptions().dontAnimate())
                    .load(path)
                    .into(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(@NonNull File file,
                                                    Transition<? super File> transition) {
                            if (file == null) {
                                return;
                            }
                            if (!file.exists()) {
                                return;
                            }
                            manager.scanImage(file.getAbsolutePath(), new IdentifyQrCodeManager.ScanCallBack() {
                                @Override
                                public void scanSuccess(String filePath, String reult) {
                                    menuList.add(new MessageMenu(imStruct002, ResStringUtil.getString(R.string.chat_recognition_photo_two), MessageMenu.SCAN_IMAGE_QR, reult));
                                    titles.add(ResStringUtil.getString(R.string.chat_recognition_photo_two));
                                    if (alertDialog != null && alertDialog.isShowing()) {
                                        alertDialog.dismiss();
                                        showMenuDialog(context, adapter, menuList, titles);
                                    }
                                }

                                @Override
                                public void scanFail() {

                                }
                            });
                        }
                    });
        }

        showMenuDialog(context, adapter, menuList, titles);
    }


    /**
     * 从配置文件解析过滤MessageMenu
     *
     * @param menuList
     * @param titles
     * @param stubObjects
     * @param imStruct002
     * @return
     */
    private static void parseShowMenu(List<MessageMenu> menuList, List<String> titles, List<StubObject> stubObjects, IMStruct002 imStruct002) {
        if (stubObjects == null) {
            return;
        }
        for (int i = 0; i < stubObjects.size(); i++) {
            StubObject stubObject = stubObjects.get(i);
            String caption = stubObject.getCaption();
            int menuType = getMenuType(stubObject.getString("id", ""));
            if (menuType == -1) {
                continue;
            }
            //如果是发送给好友
            if (menuType == MessageMenu.SHARE_MESSAGE) {
                if (imStruct002.getState() == IMStruct002.MESSAGE_STATE_PRESEND
                        || imStruct002.getState() == IMStruct002.MESSAGE_STATE_WAITSEND
                        || imStruct002.getState() == IMStruct002.MESSAGE_STATE_SENDING
                        || imStruct002.getState() == IMStruct002.MESSAGE_STATE_FAILURE) {
                    continue;
                }
            }
            titles.add(caption);
            menuList.add(new MessageMenu(imStruct002, caption, menuType));
        }
    }

    private static int getMenuType(String id) {
        switch (id) {
            case "copyMessage":
                return MessageMenu.COPY_MESSAGE;
            case "deleteMessage":
                return MessageMenu.DELETE_MESSAGE;
            case "shareMessage":
                return MessageMenu.SHARE_MESSAGE;
            case "saveImage":
                return MessageMenu.SAVE_IMAGE;
            case "fileLocation":
                return MessageMenu.FILE_LOCATION;
            case "searchFormMessage":
                return MessageMenu.SERACH_FORM_MESSAGE;
            case "translateMessage":
                return MessageMenu.TRANSLATE_MESSAGE;
            default:
                return -1;
        }
    }


    /**
     * 解析每种消息类型对应的菜单
     *
     * @param chatMessageMenuList
     */
    private static void parseMessageTypeList(List<StubObject> chatMessageMenuList) {
        for (int i = 0; i < chatMessageMenuList.size(); i++) {
            StubObject stubObject = chatMessageMenuList.get(i);
            String messageTypeId = stubObject.getString("messageTypeId", "");
            List<StubObject> stubObjects = Registry.getRegEntryList(stubObject.getString("id", ""));
            if (stubObject == null) {
                continue;
            }
            messageMenuMap.put(Integer.valueOf(messageTypeId), stubObjects);
        }

    }

    private static void showMenuDialog(final Context context, final BaseAdapter adapter, final List<MessageMenu> menuList, List<String> titles) {
        alertDialog = new AlertDialog.Builder(context)
                .setItems(titles.toArray(new String[menuList.size()]),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MessageMenu menu = menuList.get(which);
                                menuClick(context, menu);
                                dialog.cancel();
                                alertDialog = null;
                                adapter.notifyDataSetChanged();
                            }
                        }).create();
        alertDialog.show();
    }

    private static void menuClick(Context context, MessageMenu menu) {
        switch (menu.getMenuType()) {
            case MessageMenu.COPY_MESSAGE:
                copyMessage(menu.getImStruct002());
                break;
            case MessageMenu.SAVE_IMAGE:
                savePicture(menu.getImStruct002());
                break;
            case MessageMenu.SERACH_FORM_MESSAGE:
                queryFormMessage(menu.getImStruct002());
                break;
            case MessageMenu.DELETE_MESSAGE:
                JFMessageManager.getInstance().removeMessage(menu.getImStruct002());
                break;
            case MessageMenu.FILE_LOCATION:
                showFileLocation(context, menu.getImStruct002());
                break;
            case MessageMenu.RECALL_MESSAGE:
                recallMessage(menu.getImStruct002());
                break;
            case MessageMenu.SCAN_IMAGE_QR:
                scanQR(context, menu.getOtherResult());
                break;
            case MessageMenu.SHARE_MESSAGE:
                sendToFriend(context, menu.getImStruct002());
                break;
            case MessageMenu.TRANSLATE_MESSAGE:
                translateMessge(context, menu.getImStruct002());
                break;
            default:
                break;

        }
    }


    //发送给好友
    private static void sendToFriend(Context context, IMStruct002 imStruct002) {
        Intent intent = new Intent(context, MobileShareActivity.class);
        intent.putExtra("sendImStruct002", true);
        intent.putExtra("imStruct002", imStruct002);
        context.startActivity(intent);
    }

    //识别图片二维码
    private static void scanQR(Context context, Object otherResult) {
        QRManager.handleresult(context, (String) otherResult, false);
    }

    //撤回消息
    private static void recallMessage(IMStruct002 imStruct002) {
        //更改内存以及数据库的消息为撤回
        JFMessageManager.getInstance().setMessageToRecall(imStruct002.getMessageID());
        //发送撤回消息
        int toUserId = imStruct002.getToUserId();
        IMStruct002 recallMessage = StructFactory.getInstance().createRecallMessage(imStruct002.getMessageID(), toUserId, imStruct002.getToUserType());
        JFMessageManager.getInstance().sendMessage(recallMessage);
    }


    //显示更大的textextview dialog
    public static void showBigTextView(Context mContext, IMStruct002 iMStruct002) {
        final Dialog dlg = new Dialog(mContext, R.style.FullScreenDialog);
        dlg.setContentView(R.layout.chatavtivity_bigtext);
        TextView bigTextView = (TextView) dlg.findViewById(R.id.tv_big_text);
        bigTextView.setText(SmileUtils.getSmiledText(mContext, iMStruct002.getMessage()));
        dlg.show();
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context
                .WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dlg.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        lp.height = (int) (display.getHeight()); //设置宽度
        dlg.getWindow().setAttributes(lp);
        bigTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dlg.dismiss();
            }
        });
    }

    private static String getFileName(IMStruct002 imStruct002) {
        String fileName;
        try {
            fileName = JSONUtil.parseJson(imStruct002.getMessage()).get("FileName").getAsString();
        } catch (Exception e) {
            fileName = "";
        }
        return fileName;
    }

    //复制消息
    private static void copyMessage(IMStruct002 imStruct002) {
        try {
            String message = imStruct002.getMessage();
            if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_format_text) {
                message = TextFormatMessageUtil.disposeJsonTextMessage(imStruct002);
            }
            ClipboardManager cmb = (ClipboardManager) AppContext.getInstance().getSystemService
                    (CLIPBOARD_SERVICE);
            cmb.setText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ToastUtil.showToast(AppContext.getInstance(), R.string.chat_copy_to_clipboard);
    }

    //保存图片消息
    private static void savePicture(IMStruct002 imStruct002) {
        String url = JSONUtil.parseJson(imStruct002.getMessage()).get("url").getAsString();
        final Handler mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        // Toast.makeText(AppContext.getCurrentActivity(), "图片已保存至" + ImageUtil.CHATPICTRE + "目录下", Toast.LENGTH_SHORT).show();
                        Toast.makeText(AppContext.getCurrentActivity(), ResStringUtil.getString(R.string.chat_photo_save_to) +
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
                                + ResStringUtil.getString(R.string.chat_under_catalog), Toast.LENGTH_SHORT).show();

                        break;
                    case 2:
                        Toast.makeText(AppContext.getCurrentActivity(), R.string.chat_photo_save_fail, Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(AppContext.getCurrentActivity(), R.string.chat_photo_existed, Toast.LENGTH_SHORT).show();
                    default:
                        break;
                }
            }
        };
        ImageUtil.saveNetWorkImage(url, mHandler);
    }

    //查询表单数据
    private static void queryFormMessage(IMStruct002 imStruct002) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("imStruct002", imStruct002);
        bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, false);
        bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_LEFT_VISIBILITY, View.VISIBLE);
        bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_RIGHT_VISIBILITY, View.INVISIBLE);
        bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME, ResStringUtil.getString(R.string.chat_select));
        EFFrameUtils.pushFragment(AppAccountFormStateSearchFragment.class, bundle);
    }

    //显示文件位置
    private static void showFileLocation(Context mContext, IMStruct002 imStruct002) {
        String path;
        if (imStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
            if (imStruct002.getMessage().contains("FileLocalPath")) {
                path = JSONUtil.parseJson(imStruct002.getMessage()).get("FileLocalPath").getAsString();
                if (!new File(path).exists()) {
                    path = getFilePathbyFileId(imStruct002);
                }
            } else if (imStruct002.getMessage().contains("path")) {
                path = JSONUtil.parseJson(imStruct002.getMessage()).get("path").getAsString();
            } else {
                path = null;
            }
        } else {
            path = getFilePathbyFileId(imStruct002);
        }

        if (path == null) {
            Toast.makeText(AppContext.getInstance(), R.string.chat_file_not_down_remove, Toast.LENGTH_LONG).show();
        } else if (!new File(path).exists()) {
            Toast.makeText(AppContext.getInstance(), R.string.chat_file_not_down_remove, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(AppContext.getInstance(), path, Toast.LENGTH_LONG).show();

//            File file = new File(path);
//            File parentFlie = new File(file.getParent());
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//            intent.setDataAndType(UriUtils.getUriForFile(parentFlie), "*/*");
//            intent.addCategory(Intent.CATEGORY_OPENABLE);
//            mContext.startActivity(intent);
        }
    }


    /**
     * 通过比用接口翻译消息
     *
     * @param context
     * @param imStruct002
     */
    private static void translateMessge(final Context context, final IMStruct002 imStruct002) {
        //文本消息和 json 格式化消息需要翻译
        short messageChildType = imStruct002.getMessageChildType();
        if (messageChildType != MessageChildTypeConstant.subtype_text
                && messageChildType != MessageChildTypeConstant.subtype_format_text) {
            return;
        }
        //1.获取原始文本消息
        String originalText = imStruct002.getMessage();
        if (messageChildType == MessageChildTypeConstant.subtype_format_text) {
            originalText = TextFormatMessageUtil.disposeJsonTextMessage(imStruct002);
        }
        //2.获取要翻译成的语言
        String toLanguage = TranslateSettingActivity.getCurrentTranlateToLanguage();
//        Locale systemLocale = MultiLanguageUtil.getSetLanguageLocale(AppContext.getInstance());
//        String toLanguage = systemLocale.getLanguage();
//
//        // 多语言代码表 https://blog.csdn.net/qq_40395278/article/details/83269513
//        //todo 注意 翻译 印度尼西亚语 in-》id 才能用，不支持亚美尼亚语
//        if ("in".equals(toLanguage)){
//            toLanguage ="id";
//        }else  if ("hy".equals(toLanguage)){
//            //直接翻译英语
//            toLanguage ="en";
//        }
//        String toLanguage ="en";
        //3.拼请求参数
        JSONArray jsonArray = new JSONArray();
        JSONObject textObject = new JSONObject();
        try {
            textObject.put("Text", originalText);
            jsonArray.put(textObject);
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("toLanguage", toLanguage);
            paramMap.put("jsonText", jsonArray.toString());
            //翻译服务的地址
            String reuquestUrl = EnvironmentVariable.getProperty("translateBaseUrl", "http://mobile-server.openserver.cn/TranslateServer");

            try {
                ((BaseActivity) ActivityUtils.getTopActivity()).showLoading(R.string.wechat_is_translating);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JFCommonRequestManager.getInstance(context).requestPostByAsyn(ActivityUtils.getTopActivity().getClass().getSimpleName(),
                    reuquestUrl + "/translate", paramMap, new TCommonRequestManager.ReqCallBack<String>() {
                        @Override
                        public void onReqSuccess(String result) {
                            try {
                                ((BaseActivity) ActivityUtils.getTopActivity()).dismissLoading();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

//{"result":"success","data":[{"translations":[{"text":"我真的很想开车绕着街区转几圈。","to":"zh-Hans"}],"detectedLanguage":{"score":1,"language":"en"}}]}
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getString("result").equals("success")) {
                                    String translateString = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray("translations")
                                            .getJSONObject(0).optString("text", "");
                                    //翻译结果放入消息
                                    imStruct002.putExtra("translate", translateString);
                                    //更新数据库
                                    JFMessageManager.dbManager.update(imStruct002);
                                    //通知界面刷新
                                    EventBus.getDefault().post(new NotifyChatUIRefreshEvent());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            ((BaseActivity) ActivityUtils.getTopActivity()).dismissLoading();
                            ToastUtil.showToast(context, R.string.wechat_translate_fail);
                        }
                    });

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

        }


    }

    @Nullable
    private static String getFilePathbyFileId(IMStruct002 imStruct002) {
        String path;
        String fileId;
        if (imStruct002.getMessage().contains("Fileid")) {
            fileId = JSONUtil.parseJson(imStruct002.getMessage()).get("Fileid").getAsString();
        } else if (imStruct002.getMessage().contains("FileId")) {
            fileId = JSONUtil.parseJson(imStruct002.getMessage()).get("FileId").getAsString();
        } else {
            fileId = "";
        }
        File desFile = new File(FileUtil.filePath + "/" + fileId + "/" + getFileName(imStruct002));

        if (desFile.exists()) {
            path = desFile.getAbsolutePath();
        } else {
            //path = "文件未下载或已经移除";
            path = null;
        }
        return path;
    }

    public static void release() {
        if (alertDialog != null) {
            if (alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            alertDialog = null;
        }
        ChatAdapterDialogUtil.release();
    }
}
