package com.xxfc.discovery.other;

import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.utils.tools.android.IntentUtil;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.frame.base.bus.LoginSuccessfulEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.CommonApi;
import com.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.browse.ActivityImageBrowseUrl;
import com.ruiwenliu.wrapper.browse.ActivityImageBrowseUrl2;
import com.ruiwenliu.wrapper.util.um.CustomShareListener;
import com.ruiwenliu.wrapper.util.um.ShareManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.IsAppInstall;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryIMTokenBean;
import com.xxfc.discovery.bean.PatDetailsBean;
import com.xxfc.discovery.dialog.TrillCommentInputDialog;
import com.xxfc.discovery.presenter.DiscoveryPresenter;
import com.yuyife.okgo.OkGoUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.ruiwenliu.wrapper.weight.webview.SafeWebView.hasKitkat;

/**
 * 拍拍 详情
 */
@Route(path = Constance.ACTIVITY_URL_DETAILPAT)
public class DetailPatActivity extends BaseStatusActivity<DiscoveryPresenter> {

    @BindView(R2.id.pb_progress)
    ProgressBar pbProgress;
    @BindView(R2.id.webView)
    WebView mWebView;
    @BindView(R2.id.ll_item_comment)
    LinearLayout llItemComment;

    private String webUrl;
    private String content;

    @Autowired()
    String id;

    @Autowired()
    String title;

    @Autowired()
    String iconUrl;

    @Autowired()
    String userUrl;

    @Autowired()
    String userName;

    private String isPraise;

    private ShareManager shareManager;
    private ClipboardManager myClipboard;
    private String code;

    @Override
    protected int setLayout() {
        return R.layout.activity_detail_pat;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("拍拍详情");
        titleView.setImageResource(R.id.iv_title_right, R.drawable.common_icon_rv_rentingcar_icon_share);
        titleView.setChildClickListener(R.id.iv_title_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shareManager != null) {
                    shareManager.open();
                }
            }
        });

        webUrl = DiscoveryApi.DISCOVERY_FINDDETAILS + "?id=" + id;
        Log.i("CampDetailActivity", "initView: " + webUrl);
        initWeb();

        if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(iconUrl)) {
            code = Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_CODE, "");
            initShare(webUrl + "&shareType=app&code=" + code, title, "【滴房车】开着房车去旅行，一样的旅途，不一样的精彩", iconUrl);
        }

        initRxbus();
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        loadDetail();
    }

    private void loadDetail() {
        if (TextUtils.isEmpty(title)) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("id", id);
            mPresenter.getData(RvFrameConfig.HOST, 5, DiscoveryApi.DISCOVERY_MSG_GET, PatDetailsBean.class, map, false);
        }
    }

    private void initRxbus() {
        RxBus.tObservable(LoginSuccessfulEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(LoginSuccessfulEvent event) {
                        mWebView.reload();
                    }
                });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void initWeb() {
        WebSettings webSettings = mWebView.getSettings();
        if (webSettings == null) return;
        // 支持 Js 使用
        webSettings.setJavaScriptEnabled(true);
        // 开启DOM缓存,默认状态下是不支持LocalStorage的
        webSettings.setDomStorageEnabled(true);
        // 开启数据库缓存
        webSettings.setDatabaseEnabled(true);
        // 支持自动加载图片
        webSettings.setLoadsImagesAutomatically(hasKitkat());
        // 设置 WebView 的缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 支持启用缓存模式
        webSettings.setAppCacheEnabled(true);
        // 设置 AppCache 最大缓存值(现在官方已经不提倡使用，已废弃)
//        webSettings.setAppCacheMaxSize(8 * 1024 * 1024);
        // Android 私有缓存存储，如果你不调用setAppCachePath方法，WebView将不会产生这个目录
        webSettings.setAppCachePath(getCacheDir().getAbsolutePath());
        // 数据库路径
//        if (!hasKitkat()) {
//            webSettings.setDatabasePath(getDatabasePath("html").getPath());
//        }
        // 关闭密码保存提醒功能
//        webSettings.setSavePassword(false);
        // 支持缩放
        webSettings.setSupportZoom(true);
        // 设置 UserAgent 属性
        webSettings.setUserAgentString("");
        // 允许加载本地 html 文件/false
        webSettings.setAllowFileAccess(true);
        // 允许通过 file url 加载的 Javascript 读取其他的本地文件,Android 4.1 之前默认是true，在 Android 4.1 及以后默认是false,也就是禁止
        webSettings.setAllowFileAccessFromFileURLs(true);
        // 允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源，
        // Android 4.1 之前默认是true，在 Android 4.1 及以后默认是false,也就是禁止
        // 如果此设置是允许，则 setAllowFileAccessFromFileURLs 不起做用
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        mWebView.addJavascriptInterface(new AndroidJs(), "AndroidJs");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
        mWebView.loadUrl(webUrl);
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    pbProgress.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    pbProgress.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    pbProgress.setProgress(newProgress);//设置进度值
                }
            }
        });
    }

    @OnClick({R2.id.ll_item_comment})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_item_comment) {
            //评论
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
                return;
            }
            TrillCommentInputDialog trillCommentInputDialog = new TrillCommentInputDialog(mActivity, new TrillCommentInputDialog.OnSendCommentListener() {
                @Override
                public void sendComment(String str) {
                    content = str;
                    if (OkGoUtil.getToken() != null) {
                        Map<String, Object> headMap = new LinkedHashMap<>();
                        headMap.put("Authorization", OkGoUtil.getToken());
                        mPresenter.postData(RvFrameConfig.HOST, 0, DiscoveryApi.DISCOVERY_IM_LOGIN, DiscoveryIMTokenBean.class, headMap, headMap, true);
                    }

//                        headMap.put("Authorization", OkGoUtil.getToken());
//                        headMap.put("content-type ","application/json");
                }
            });
            Window window = trillCommentInputDialog.getWindow();
            if (window != null) {
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);// 软键盘弹起
                trillCommentInputDialog.show();
            }
        }
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                DiscoveryIMTokenBean intokenBean = (DiscoveryIMTokenBean) result;
                setData(intokenBean);
                break;
            case 1:
                mWebView.reload();
                break;
            case 2:
                DiscoveryIMTokenBean intokenBean2 = (DiscoveryIMTokenBean) result;
                setIMData(intokenBean2);
                break;
            case 3:
            case 4:
                mWebView.reload();
                break;
            case 5:
                PatDetailsBean patDetailsBean = (PatDetailsBean) result;
                if (patDetailsBean.getData() != null) {
                    title = patDetailsBean.getData().getBody().getText();
                    iconUrl = patDetailsBean.getData().getBody().getImages().get(0).getoUrl();
                    userName = patDetailsBean.getData().getNickname();
                    userUrl = patDetailsBean.getData().getPicUrl();
                }
                break;
        }
    }

    private void setIMData(DiscoveryIMTokenBean bean) {
        if ("0".equals(isPraise)) {//0：未点赞 1：已点赞
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("access_token", bean.getData());
            map.put("messageId", id);
            mPresenter.postData(3, DiscoveryApi.DISCOVERY_PRAISE_ADD, BaseBean.class, map, false);
        } else {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("access_token", bean.getData());
            map.put("messageId", id);
            mPresenter.postData(4, DiscoveryApi.DISCOVERY_PRAISE_DELETE, BaseBean.class, map, false);
        }
    }


    private void setData(DiscoveryIMTokenBean intokenBean) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("access_token", intokenBean.getData());
        map.put("messageId", id);
        map.put("body", content);
        mPresenter.postData(1, DiscoveryApi.DISCOVERY_COMMENT_ADD, BaseBean.class, map, true);
    }

    public class AndroidJs {
        @JavascriptInterface
        public String getToken() {
            return OkGoUtil.getToken();
        }

        @JavascriptInterface
        public void showImage(int selectPosition, String imageJson) {
            if (!TextUtil.isEmpty(imageJson)) {
                List<String> imagesList = new Gson().fromJson(imageJson,
                        new TypeToken<List<String>>() {
                        }.getType());
                Bundle bundle = new Bundle();
                bundle.putInt(ActivityImageBrowseUrl2.KEY_BACKGROUND, R.color.colorPrimary);
                bundle.putInt(ActivityImageBrowseUrl2.KEY_SELECTPOSITION, selectPosition);
                bundle.putStringArrayList(ActivityImageBrowseUrl2.KEY_IMAGE, (ArrayList<String>) imagesList);
                IntentUtil.startActivity(mActivity, ActivityImageBrowseUrl2.class, bundle);
            }
        }


        @JavascriptInterface
        public void isLike(String praise) {
            if (OkGoUtil.getToken() != null) {
                isPraise = praise;
                Map<String, Object> headMap = new LinkedHashMap<>();
                headMap.put("Authorization", OkGoUtil.getToken());
                mPresenter.postData(RvFrameConfig.HOST, 2, DiscoveryApi.DISCOVERY_IM_LOGIN, DiscoveryIMTokenBean.class, headMap, headMap, false);
            } else {
                ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
            }
        }
    }

    /**
     * 初始化分享
     */
    private void initShare(final String webUrl, final String name, final String content, final String logo) {

        shareManager = new ShareManager(this, new ShareBoardlistener() {
            @Override
            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
//                if (snsPlatform.mShowWord.equals("生成海报")) {
//                    ARouter.getInstance()
//                            .build(Constance.ACTIVITY_URL_PATGENERATEPOSTER)
//                            .withString("iconUrl", iconUrl)
//                            .withString("content", title)
//                            .withString("url", webUrl + "&shareType=app&code=" + code)
//                            .withString("userName", userName)
//                            .withString("userUrl", userUrl)
//                            .navigation();
//                } else

                if (snsPlatform.mShowWord.equals("复制链接")) {
                    copyText();
                } else if (snsPlatform.mShowWord.contains("微信")) {
                    if (!IsAppInstall.isWeixinAvilible(mActivity)) {
                        showToast("亲，您微信还没有安装呢");
                        return;
                    }
                } else if (snsPlatform.mShowWord.contains("QQ")) {
                    if (!IsAppInstall.isQQClientAvailable(mActivity)) {
                        showToast("亲，您QQ还没有安装呢");
                        return;
                    }
                }

                shareManager.showShare(share_media, webUrl, name, content, logo

                        , new CustomShareListener(mActivity) {
                            @Override
                            public void onResult(SHARE_MEDIA platform) {
                                super.onResult(platform);

                                if (platform.name().equals("WEIXIN_FAVORITE")) {

                                    showToast(" 收藏成功啦");

                                } else {
                                    if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                                            && platform != SHARE_MEDIA.EMAIL
                                            && platform != SHARE_MEDIA.FLICKR
                                            && platform != SHARE_MEDIA.FOURSQUARE
                                            && platform != SHARE_MEDIA.TUMBLR
                                            && platform != SHARE_MEDIA.POCKET
                                            && platform != SHARE_MEDIA.PINTEREST

                                            && platform != SHARE_MEDIA.INSTAGRAM
                                            && platform != SHARE_MEDIA.GOOGLEPLUS
                                            && platform != SHARE_MEDIA.YNOTE
                                            && platform != SHARE_MEDIA.EVERNOTE) {
                                        showToast("分享成功啦");
                                        sharingSuccess();
                                    }

                                }
                            }
                        });
            }
        }, "rv_um_share_copy");
    }


    /**
     * 复制文本
     */
    private void copyText() {
        if (myClipboard == null) {
            myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        }
        String code = Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_CODE, "");
        ClipData myClip = ClipData.newPlainText("text", webUrl + "&shareType=app&code=" + code);
        myClipboard.setPrimaryClip(myClip);
        showToast("复制成功！");
    }


    @Override
    protected void onStart() {
        super.onStart();

//
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();// 生命周期onResume
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();//生命周期onPause
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWebView.stopLoading();// 停止当前加载
        mWebView.clearMatches();// 清除网页查找的高亮匹配字符。
        mWebView.clearHistory();// 清除当前 WebView 访问的历史记录
        mWebView.clearSslPreferences();//清除ssl信息
        mWebView.clearCache(true);//清空网页访问留下的缓存数据。需要注意的时，由于缓存是全局的，所以只要是WebView用到的缓存都会被清空，即便其他地方也会使用到。该方法接受一个参数，从命名即可看出作用。若设为false，则只清空内存里的资源缓存，而不清空磁盘里的。
        mWebView.loadUrl("about:blank");// 清空当前加载
        mWebView.removeAllViews();// 清空子 View
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mWebView.removeJavascriptInterface("AndroidNative");// 向 Web端注入 java 对象
        }
//        mWebView.addJavascriptInterface(new AndroidJs(),"AndroidJs");
        mWebView.destroy();// 生命周期销毁
    }

    /**
     * 分享积分
     */
    private void sharingSuccess() {
        if (!TextUtils.isEmpty(OkGoUtil.getToken())) {
            BeanUserInfo.UserInfo userInfo = getUserInfo();
            if (userInfo != null) {
                Map<String, Object> headMap = new LinkedHashMap<>();
                headMap.put("Content-type", "application/json;charset=UTF-8");
                mPresenter.postBodyData(RvFrameConfig.HOST, 20, CommonApi.TOUR_SENDMESSAGE, BaseBean.class, new SharingSuccess("SHARE", userInfo.getUserid()), headMap, false);
            }
        }
    }

    private class SharingSuccess {
        private String integralRuleCode;
        private int userId;

        public SharingSuccess(String integralRuleCode, int userId) {
            this.integralRuleCode = integralRuleCode;
            this.userId = userId;
        }

        public String getIntegralRuleCode() {
            return integralRuleCode;
        }

        public void setIntegralRuleCode(String integralRuleCode) {
            this.integralRuleCode = integralRuleCode;
        }

        public int getUserId() {
            return userId;
        }

        public void setUserId(int userId) {
            this.userId = userId;
        }
    }
}
