package com.efounder.chat.utils;

//import android.app.AlertDialog;

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.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.efounder.chat.R;
import com.efounder.chat.activity.MobileShareActivity;
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.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.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.JSONUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

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

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

/**
 * 消息长按弹窗
 * Created by cherise on 2016/10/15.
 * @see ChatMessageMenuDialogUtil
 */
@Deprecated

public class ChatAdapterDialogUtil {
    public static AlertDialog alertDialog;

    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 (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_text) {
            menuList.add(new MessageMenu(imStruct002, ResStringUtil.getString(R.string.chat_copy_message), MessageMenu.COPY_MESSAGE));
            titles.add(ResStringUtil.getString(R.string.chat_copy_message));
        } else if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_image) {
            menuList.add(new MessageMenu(imStruct002, ResStringUtil.getString(R.string.chat_save_photo), MessageMenu.SAVE_IMAGE));
            titles.add(ResStringUtil.getString(R.string.chat_save_photo));
        } else if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_form) {
            menuList.add(new MessageMenu(imStruct002, ResStringUtil.getString(R.string.chat_select), MessageMenu.SERACH_FORM_MESSAGE));
            titles.add( ResStringUtil.getString(R.string.chat_select));

        } else if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_file) {
            menuList.add(new MessageMenu(imStruct002, ResStringUtil.getString(R.string.chat_file_location), MessageMenu.FILE_LOCATION));
            titles.add(ResStringUtil.getString(R.string.chat_file_location));
        }
        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 (EnvSupportManager.isSupportShareMessage()) {
            //分享消息
            if (imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_file
                    || imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_text
                    || imStruct002.getMessageChildType() == MessageChildTypeConstant.subtype_image) {
                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){
                menuList.add(new MessageMenu(imStruct002, ResStringUtil.getString(R.string.chat_send_friend), MessageMenu.SHARE_MESSAGE));
                titles.add(ResStringUtil.getString(R.string.chat_send_friend));
                }
            }

        }

        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);
    }

    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;
            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 = new String(imStruct002.getBody(), "utf-8");
            ClipboardManager cmb = (ClipboardManager) AppContext.getInstance().getSystemService
                    (CLIPBOARD_SERVICE);
            cmb.setText(message);
        } catch (UnsupportedEncodingException 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) {
        final 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();
            } else if (imStruct002.getMessage().contains("path")) {
                path = JSONUtil.parseJson(imStruct002.getMessage()).get("path").getAsString();
            } else {
                path = null;
            }
        } else {
            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;
            }
        }

        if (path == null) {
            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);
        }
    }

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