package com.meeting.demo.view.sdk;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;

import androidx.fragment.app.DialogFragment;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.cloudlink.openapi.model.HWMUserState;
import com.huawei.clpermission.CLEasyPermission;
import com.huawei.clpermission.CLGrantResult;
import com.huawei.clpermission.CLPermissionHelper;
import com.huawei.clpermission.CLPermissionRequestListener;
import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmbiz.Login;
import com.huawei.hwmbiz.eventbus.LogoutResult;
import com.huawei.hwmbiz.impl.BizOpenApiImpl;
import com.huawei.hwmbiz.login.cache.LoginSettingCache;
import com.huawei.hwmcommonui.ui.popup.dialog.base.BaseDialogBuilder;
import com.huawei.hwmconf.presentation.util.PermissionUtil;
import com.huawei.hwmconf.sdk.model.login.entity.RequestPairParam;
import com.huawei.hwmconf.sdk.util.Utils;
import com.meeting.demo.delegate.DelegateHolder;
import com.meeting.demo.model.ApiPageModel;
import com.meeting.demo.utils.ControllerUtils;
import com.meeting.demo.utils.DemoUtil;
import com.meeting.demo.view.DemoActivity;
import com.meeting.demo.view.FragmentContainerActivity;
import com.meeting.demo.view.base.BaseListFragment;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmfoundation.utils.DeviceUtil;
import com.huawei.hwmfoundation.utils.FileUtil;
import com.huawei.hwmfoundation.utils.StringUtil;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmmediapicker.media.MediaModel;
import com.huawei.hwmmediapicker.mediapicker.ImagePicker;
import com.huawei.hwmprivatesdk.PrivateNativeSDK;
import com.huawei.hwmsdk.NativeSDK;
import com.huawei.hwmsdk.common.SdkCallback;
import com.huawei.hwmsdk.enums.LoginState;
import com.huawei.hwmsdk.enums.SDKERR;
import com.huawei.hwmsdk.enums.VerifyMode;
import com.huawei.hwmsdk.model.param.CorpConfigParam;
import com.huawei.hwmsdk.model.param.VerifyParam;
import com.huawei.hwmsdk.model.result.LoginStateInfo;
import com.huawei.hwmsdk.model.result.RequestPairInfo;
import com.huawei.hwmsdk.model.result.RequestPairResult;
import com.huawei.hwmsdk.model.result.ServerInfo;
import com.meeting.demo.R;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;

public class  SDKListFragment extends BaseListFragment {
    public final static String TAG = SDKListFragment.class.getSimpleName();
    private static final int PICKER_REQUEST_CODE = 13434;
    private final List<ApiPageModel> features = DelegateHolder.getHwmUiDelegate().getSdkApiFeatures();

    @Override
    public List<ApiPageModel> getItems() {
        return features;
    }

    @Override
    public void handleItemClick(int position, ApiPageModel data) {
        if ("登出".equals(features.get(position).name)) {
            logout();
        } else if ("SSO登录".equals(features.get(position).name)) {
            startActivity(new Intent(SDKListFragment.this.getActivity(), FragmentContainerActivity.class));
        } else if ("设置头像".equals(features.get(position).name)) {
            showPictureActivity();
        } else if ("用户状态".equals(features.get(position).name)) {
            getHWMUserState();
        } else if ("控制器配对（在线）".equals(features.get(position).name)) {
            goOnlinePair();
        } else if ("控制器配对（离线）".equals(features.get(position).name)) {
            checkOfflinePair(data);
        }else if ("拉起会中主界面".equals(features.get(position).name)) {
            showMeetingWindow();
        } else if ("获取登录信息".equals(features.get(position).name)) {
            showLoginStateInfo();
        } else {
            showDialogFragment(data);
        }
    }

    private void showLoginStateInfo() {
        DemoUtil.showToast("登录状态 : " + BizOpenApiImpl.getInstance(DemoUtil.getApplication()).getLoginState() + "\n" +
                "accessToken : " + StringUtil.formatTokenString(BizOpenApiImpl.getInstance(DemoUtil.getApplication()).getAccessToken()));
    }

    private void showMeetingWindow() {
        HWMSdk.getOpenApi(DemoUtil.getApplication()).showMeetingWindow();
    }

    @SuppressLint("CheckResult")
    private void checkOfflinePair(ApiPageModel data) {
        if (getActivity() != null) {
            ((DemoActivity) getActivity()).showLoading();
        }
        LoginSettingCache.getInstance(DemoUtil.getApplication())
                .getCacheDataAsyncBlock()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(loginSetting -> {
                    ServerInfo serverInfo = new ServerInfo();
                    serverInfo.setServerAddr(loginSetting.getLoginServerAddress());
                    serverInfo.setServerPort(Integer.parseInt(loginSetting.getLoginServerPort()));
                    NativeSDK.getNetworkApi().setServerAddress(serverInfo);

                    VerifyParam verifyParam = new VerifyParam();
                    verifyParam.setVerifyMode(Integer.parseInt(loginSetting.getIsSupportCACertCheck()) == 1
                            ? VerifyMode.VERIFY_MODE_SERVER
                            : VerifyMode.VERIFY_MODE_NONE);
                    verifyParam.setCertPath(
                            Login.getServerCaHandle().getCaPath() == null ? "" : Login.getServerCaHandle().getCaPath());
                    PrivateNativeSDK.getPrivateNetworkApi().setTlsVerify(verifyParam);

                    RequestPairParam requestPairInfo = new RequestPairParam();
                    requestPairInfo.setDeviceId(FileUtil.encryptSHA256(
                            DeviceUtil.getAndroidId(Utils.getApp()).getBytes()));
                    HWMBizSdk.getBizOpenApi().requestPair(requestPairInfo, new SdkCallback<RequestPairResult>() {
                        @Override
                        public void onFailed(SDKERR error) {
                            if (getActivity() != null) {
                                ((DemoActivity) getActivity()).dismissLoading();
                            }
                            if (error == SDKERR.SDK_LOGINLOGIC_NEED_REPAIR_CONTROLLER
                                    || error == SDKERR.USG_OFFLINE_PAIR_AUTH_FIXED_LINK_UNFOUND) {
                                showDialogFragment(data);
                            }
                            DemoUtil.showToast(error.getDescription());
                        }

                        @Override
                        public void onSuccess(RequestPairResult requestPairResult) {
                            if (getActivity() != null) {
                                ((DemoActivity) getActivity()).dismissLoading();
                            }
                            ControllerUtils.goRouteControllerH5Page(getContext(), requestPairResult.getNonce(),
                                    "", false);
                        }
                    });
                });
    }

    private void showDialogFragment(ApiPageModel data) {
        if (data.page != null) {
            try {
                DialogFragment f = (DialogFragment) data.page.newInstance();
                if (!f.isAdded()) {
                    f.show(getActivity().getSupportFragmentManager(), null);
                }
            } catch (IllegalAccessException | java.lang.InstantiationException e) {
                Log.e("SDKListFragment", e.getMessage());
            }
        } else {
            Log.e("SDKListFragment", "not found page");
        }
    }

    private void goOnlinePair() {
        LoginStateInfo loginStateInfo = NativeSDK.getLoginApi().getLoginStateInfo();
        if (loginStateInfo == null || loginStateInfo.getLoginState() != LoginState.LOGIN_STATUS_LOGINED) {
            DemoUtil.showToast("登录后才可以使用在线配对！");
            return;
        }
        CorpConfigParam corpConfigParam = NativeSDK.getLoginApi().getCorpConfigInfo();
        if (corpConfigParam != null && corpConfigParam.getSupportController()) {
            PrivateNativeSDK.getPrivateLoginApi().requestPair(new RequestPairInfo(), new SdkCallback<RequestPairResult>() {
                @Override
                public void onFailed(SDKERR error) {
                    DemoUtil.showToast(error.getDescription());
                }

                @Override
                public void onSuccess(RequestPairResult requestPairResult) {
                    ControllerUtils.goRouteControllerH5Page(getContext(), requestPairResult.getNonce(), "", false);
                }
            });
        } else {
            DemoUtil.showToast("当前企业不支持控制器！");
        }
    }

    public void getHWMUserState() {
        HWMUserState hwmUserState = HWMSdk.getOpenApi(HWMBizSdk.getApplication()).getHWMUserState();
        DemoUtil.showToast("user state: " + hwmUserState.getDescription());
    }

    public void showPictureActivity() {
        if (permissionsGranted()) {
            doShowPictureActivity();
        } else {
            requestPermission(PermissionUtil.getMediaImagesPermissionType(), PICKER_REQUEST_CODE);
        }
    }

    private boolean permissionsGranted() {
        return CLPermissionHelper.hasPermissionWithType(getActivity(), PermissionUtil.getMediaImagesPermissionType());
    }

    private void requestPermission(String type, int requestCode) {
        final String[] permissions = CLPermissionHelper.convertPermissionType2Perm(getContext(), type);
        CLEasyPermission.with(getActivity()).addPermissions(permissions).setRequestCode(requestCode).request(new CLPermissionRequestListener() {
            @Override
            public void onGrant(Map<String, CLGrantResult> result, int requestCode) {
                if (permissionsGranted()) {
                    doShowPictureActivity();
                } else {
                    retryPermission(permissions);
                    DemoUtil.showToast("permission denied!");
                }
            }

            @Override
            public void onCancel(String stopPermission) {
                HCLog.e(TAG, "request Permission onCancel :" + stopPermission);
            }
        });
    }

    private void retryPermission(String[] permissions) {
        //权限被拒绝，判断是否禁止后不再弹出
        List<String> permissionList = Arrays.asList(permissions);
        if (CLPermissionHelper.somePermissionPermanentlyDenied(getActivity(), permissionList)) {
            new BaseDialogBuilder(getActivity())
                .setMessage(DemoUtil.getAppName(getActivity().getApplicationContext())
                    + String.format(DemoUtil.getResContext().getString(R.string.hwmconf_mediapicker_launcher_permission_rationale),
                    DemoUtil.getResContext().getString(R.string.hwmconf_launcher_permission_storage)))
                .setMessageSize(14)
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addAction(DemoUtil.getResContext().getString(
                    R.string.hwmconf_cancel_text), R.style.hwmconf_ClBtnBlueNoBg, null)
                .addAction(DemoUtil.getResContext().getString(
                    R.string.hwmconf_confirm), R.style.hwmconf_ClBtnBlueNoBg,
                    (dialog, button, index) -> {
                        dialog.dismiss();
                        DeviceUtil.showInstalledAppDetails(getActivity(),  getActivity().getPackageName());
                    }).show();
        }
    }

    private void doShowPictureActivity() {
        ImagePicker picker = new ImagePicker.Builder(getActivity())
            .setContainVideo(false)
            .setMaxLimit(1)
            .setRightBtnText(DemoUtil.getResContext().getString(R.string.hwmconf_complete))
            .setCompleteListener(new HwmCallback<List<MediaModel>>() {
                @Override
                public void onSuccess(List<MediaModel> mediaModels) {
                    if (mediaModels.size() > 0) {
                        uploadAvatar(mediaModels.get(0).getPath());
                    }
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    HCLog.i(TAG,"ImagePicker onFailed" + retCode + " " + desc);
                }
            }).build();
        picker.start();
    }

    private void uploadAvatar(String filepath) {
        if (getActivity() != null) {
            ((DemoActivity) getActivity()).showLoading();
        }
        HWMBizSdk.getBizOpenApi().uploadSelfAvatar(filepath, new HwmCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                if (getActivity() != null) {
                    ((DemoActivity) getActivity()).dismissLoading();
                }
                DemoUtil.showToast("设置头像成功！");
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG, "uploadSelfAvatar onFailed" + retCode + " " + desc);
                if (getActivity() != null) {
                    ((DemoActivity) getActivity()).dismissLoading();
                }
                DemoUtil.showToastDialog("旧立即会议发起", retCode, desc);
            }
        });
    }

    private void logout() {
        if (getActivity() != null) {
            ((DemoActivity) getActivity()).showLoading();
        }
        HWMSdk.getOpenApi(getActivity().getApplication()).logout(new HwmCallback<LogoutResult>() {
            @Override
            public void onSuccess(LogoutResult result) {
                if (getActivity() != null) {
                    ((DemoActivity) getActivity()).dismissLoading();
                }
                if (result == null) {
                    DemoUtil.showToast("登出成功但未获取到回调信息");
                    return;
                }
                DemoUtil.showToast("登出成功:" + result.getUserUuid() + "; account：" + result.getAccount()
                    + "; thirdAccount：" + result.getThirdAccount());
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG, "logout onFailed" + retCode + " " + desc);
                if (getActivity() != null) {
                    ((DemoActivity) getActivity()).dismissLoading();
                }
                DemoUtil.showToastDialog("logout", retCode, desc);
            }
        });
    }
}
