package io.openim.android.demo.ui.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

import io.openim.android.demo.databinding.ActivityPersonInfoBinding;
import io.openim.android.demo.ui.main.EditTextActivity;
import io.openim.android.demo.vm.FriendVM;
import io.openim.android.demo.vm.PersonalVM;
import io.openim.android.ouicore.base.BaseActivity;
import io.openim.android.ouicore.base.BaseApp;
import io.openim.android.ouicore.base.vm.injection.Easy;
import io.openim.android.ouicore.databinding.LayoutCommonDialogBinding;
import io.openim.android.ouicore.databinding.LayoutCommonDialogWithTitleBinding;
import io.openim.android.ouicore.ex.MultipleChoice;
import io.openim.android.ouicore.utils.Common;
import io.openim.android.ouicore.utils.Constants;
import io.openim.android.ouicore.utils.Obs;
import io.openim.android.ouicore.utils.Routes;
import io.openim.android.ouicore.vm.ContactListVM;
import io.openim.android.ouicore.vm.GroupVM;
import io.openim.android.ouicore.vm.SelectTargetVM;
import io.openim.android.ouicore.widget.CommonDialog;
import io.openim.android.ouicore.widget.CommonWithTitleDialog;
import io.openim.android.ouicore.widget.WaitDialog;
import io.openim.android.sdk.OpenIMClient;
import io.openim.android.sdk.listener.OnBase;
import io.openim.android.sdk.listener.OnMsgSendCallback;
import io.openim.android.sdk.models.CardElem;
import io.openim.android.sdk.models.Message;
import io.openim.android.sdk.models.OfflinePushInfo;
import io.openim.android.sdk.models.UserInfo;

/**
 * 资料设置
 */
public class PersonDataActivity extends BaseActivity<PersonalVM, ActivityPersonInfoBinding> {

    private FriendVM friendVM = new FriendVM();
    private GroupVM groupVM = new GroupVM();
    private WaitDialog waitDialog;
    private String groupId;
    private Boolean isFriend;
    private Boolean isGroupAdmin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        vm = Easy.find(PersonalVM.class);
        vm.setContext(this);
        groupId = getIntent().getStringExtra(Constants.K_GROUP_ID);
        isFriend = getIntent().getBooleanExtra(Constants.K_IS_FRIEND, true);
        isGroupAdmin = getIntent().getBooleanExtra(Constants.K_IS_GROUP_ADMIN, false);
        super.onCreate(savedInstanceState);
        bindViewDataBinding(ActivityPersonInfoBinding.inflate(getLayoutInflater()));
        view.title.setText(StringUtils.isEmpty(groupId) ? io.openim.android.ouicore.R.string.friend_settings : io.openim.android.ouicore.R.string.friend_settings_group);
        sink();
        init();
        listener();

//        vm.getUserInfo(vm.uid);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) removeCacheVM();
    }

    private void init() {
        view.joinBlackList.setVisibility(StringUtils.isEmpty(groupId) ? View.VISIBLE : View.GONE);
        view.remark.setVisibility(isFriend ? View.VISIBLE : View.GONE);
        boolean show = StringUtils.isEmpty(groupId) && isFriend || isGroupAdmin;
        view.llPart.setVisibility(show ? View.VISIBLE : View.GONE);

        if (StringUtils.isEmpty(groupId) && isFriend) {
            view.part.setText(getString(io.openim.android.ouicore.R.string.disassociate));
        } else if (isGroupAdmin) {
            view.part.setText(getString(io.openim.android.ouicore.R.string.kick_out_of_group_chat));
        }

        waitDialog = new WaitDialog(this);
        friendVM.waitDialog = waitDialog;
        friendVM.setContext(this);
        friendVM.setIView(this);
        groupVM.setIView(this);
        groupVM.setContext(this);
        groupVM.groupId = groupId;
        friendVM.getBlacklist();
        vm.userInfo.observe(this, v -> {
            if (null == v) return;
            view.remarkName.setText(v.getRemark());
        });
    }

    @Override
    public void onSuccess(Object body) {
        super.onSuccess(body);
        final String cid = "single_" + vm.uid;
//        BaseApp.inst().getVMByCache(ContactListVM.class).deleteConversationAndDeleteAllMsg(cid);
        BaseApp.inst().getVMByCache(ContactListVM.class).deleteConversationAndDeleteAllMsgWithUserID(vm.uid);
        setResult(RESULT_OK);
        finish();
    }

    private void listener() {
        view.part.setOnClickListener(v -> {
            CommonWithTitleDialog commonDialog = new CommonWithTitleDialog(this);
            commonDialog.show();
            LayoutCommonDialogWithTitleBinding mainView = commonDialog.getMainView();
            if (StringUtils.isEmpty(groupId) && isFriend) {
                mainView.title.setText(getString(io.openim.android.ouicore.R.string.disassociate));
                mainView.tips.setText(String.format(getString(io.openim.android.ouicore.R.string.delete_tip), vm.userInfo.val().getNickname()));
            } else if (isGroupAdmin) {
                mainView.title.setText(getString(io.openim.android.ouicore.R.string.kick_out_of_group_chat));
                mainView.tips.setText(String.format(getString(io.openim.android.ouicore.R.string.kick_out_of_group_chat_tip), vm.userInfo.val().getNickname()));
                mainView.tips.setGravity(Gravity.CENTER);
            }

//            mainView.tips.setText(String.format(
//                    isFriend ? getString(io.openim.android.ouicore.R.string.delete_tip) : getString(io.openim.android.ouicore.R.string.kick_out_of_group_chat_tip),
//                    vm.userInfo.val().getNickname()));
            mainView.cancel.setOnClickListener(v1 -> commonDialog.dismiss());
            mainView.confirm.setOnClickListener(v1 -> {
                commonDialog.dismiss();
                if (StringUtils.isEmpty(groupId) && isFriend) {
                    friendVM.deleteFriend(vm.uid);
                } else if (isGroupAdmin) {
                    List<String> ids = new ArrayList<>();
                    ids.add(vm.uid);
                    groupVM.kickGroupMember(ids);
                    setResult(RESULT_OK);
                    finish();
                }
            });
        });
        view.recommend.setOnClickListener(v -> {
            SelectTargetVM selectTargetVM =
                    Easy.installVM(SelectTargetVM.class);
            selectTargetVM.setIntention(SelectTargetVM.Intention.singleSelect);
            selectTargetVM.setOnFinishListener(() -> {
                Common.finishRoute(Routes.Group.SELECT_TARGET, Routes.Contact.ALL_FRIEND);

                CommonDialog commonDialog = new CommonDialog(this);
                commonDialog.show();
                MultipleChoice target = selectTargetVM.metaData.val().get(0);
                LayoutCommonDialogBinding mainView = commonDialog.getMainView();
                mainView.tips.setText(String.format(getString(io.openim.android.ouicore.R.string.recommend_who), target.name));
                mainView.cancel.setOnClickListener(v1 -> commonDialog.dismiss());
                mainView.confirm.setOnClickListener(v1 -> {
                    commonDialog.dismiss();

                    CardElem cardElem = new CardElem();
                    cardElem.setUserID(vm.userInfo.val().getUserID());
                    cardElem.setNickname(vm.userInfo.val().getNickname());
                    cardElem.setFaceURL(vm.userInfo.val().getFaceURL());
                    Message message = OpenIMClient.getInstance().messageManager.createCardMessage(cardElem);
                    OfflinePushInfo offlinePushInfo = new OfflinePushInfo(); // 离线推送的消息备注；不为null
                    OpenIMClient.getInstance().messageManager.sendMessage(
                            new OnMsgSendCallback() {
                                @Override
                                public void onError(int code, String error) {
                                    toast(error + code);
                                }

                                @Override
                                public void onProgress(long progress) {
                                }

                                @Override
                                public void onSuccess(Message message) {
                                    toast(PersonDataActivity.this
                                            .getString(io.openim.android.ouicore.R.string.send_succ));
                                }
                            }, message, target.key, null, offlinePushInfo);
                });
            });
            ARouter.getInstance().build(Routes.Group.SELECT_TARGET).navigation();
        });

        view.remark.setOnClickListener(view -> {
            resultLauncher.launch(new Intent(this, EditTextActivity.class)
                    .putExtra(EditTextActivity.TITLE, getString(io.openim.android.ouicore.R.string.remark))
                    .putExtra(EditTextActivity.TIPS, "")
                    .putExtra(EditTextActivity.MAX_LENGTH, 16)
                    .putExtra(EditTextActivity.INIT_TXT, vm.userInfo.val().getRemark()));
        });
        friendVM.blackListUser.observe(this, userInfos -> {
            boolean isCon = false;
            for (UserInfo userInfo : userInfos) {
                if (userInfo.getUserID().equals(vm.uid)) {
                    isCon = true;
                    break;
                }
            }
            boolean finalIsCon = isCon;
            view.slideButton.post(() -> view.slideButton.setCheckedWithAnimation(finalIsCon));
        });
        view.joinBlackList.setOnClickListener(v -> {
            if (view.slideButton.isChecked()) friendVM.removeBlacklist(vm.uid);
            else {
                addBlackList();
            }
        });
        view.slideButton.setOnSlideButtonClickListener(isChecked -> {
            if (isChecked) addBlackList();
            else friendVM.removeBlacklist(vm.uid);
        });
    }

    private void addBlackList() {
        CommonDialog commonDialog = new CommonDialog(this);
        commonDialog.setCanceledOnTouchOutside(false);
        commonDialog.setCancelable(false);
        commonDialog.getMainView().tips.setText(String.format(StringUtils.getString(io.openim.android.ouicore.R.string.black_tip), vm.userInfo.val().getNickname()));
        commonDialog.getMainView().cancel.setOnClickListener(v -> {
            commonDialog.dismiss();
            friendVM.blackListUser.setValue(friendVM.blackListUser.getValue());
        });
        commonDialog.getMainView().confirm.setOnClickListener(v -> {
            commonDialog.dismiss();
            friendVM.addBlacklist(vm.uid, getIntent().getStringExtra(Constants.CONVERSATION_ID));
        });
        commonDialog.show();
    }

    private ActivityResultLauncher<Intent> resultLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() != Activity.RESULT_OK) return;
                String resultStr = result.getData().getStringExtra(Constants.K_RESULT);

                waitDialog.show();
                OpenIMClient.getInstance().friendshipManager.setFriendRemark(new OnBase<String>() {
                    @Override
                    public void onError(int code, String error) {
                        waitDialog.dismiss();
                        toast(error + code);
                    }

                    @Override
                    public void onSuccess(String data) {
                        waitDialog.dismiss();
                        vm.userInfo.val().setRemark(resultStr);
                        view.remarkName.setText(resultStr);
                        Obs.newMessage(Constants.Event.USER_INFO_UPDATE);
                    }
                }, vm.uid, resultStr);
            });

    @Override
    protected void fasterDestroy() {
        super.fasterDestroy();
        Easy.delete(PersonalVM.class);
    }
}
