package com.rv.tourism.other;


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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.ui.datetime.selector.util.TextUtil;
import com.frame.base.bus.IDCardCertificationEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.util.um.CustomShareListener;
import com.ruiwenliu.wrapper.util.um.ShareManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.ruiwenliu.wrapper.weight.refresh.IFooterWrapper;
import com.rv.component.control.ProgressWebView;
import com.rv.tourism.R;
import com.rv.tourism.R2;
import com.rv.tourism.api.TourismApi;
import com.rv.tourism.bean.BeanOrderParam;
import com.rv.tourism.bean.BeanTourAround;
import com.rv.tourism.bean.BeanTourismCollection;
import com.rv.tourism.presenter.TourismPresenter;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.yuyife.okgo.OkGoUtil;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;

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

/**
 * 旅游详情
 */
@Route(path = Constance.ACTIVITY_URL_TRAVELDETAILS)
public class TravelDetailsActivity extends BaseStatusActivity<TourismPresenter> {

    @BindView(R2.id.webView)
    ProgressWebView mWebView;
    @BindView(R2.id.tv_center)
    TextView tvTitleCenter;
    @BindView(R2.id.iv_collect)
    ImageView ivCollect;
    @BindView(R2.id.iv_share)
    ImageView ivShare;
    @BindView(R2.id.ll_item_bottom)
    LinearLayout llItemBottom;
    @BindView(R2.id.tv_appointment)
    TextView TvAppointment;

    private ShareManager shareManager;
    private String webUrl;
    private BeanOrderParam beanOrderParam;
    private String mCollectId;
    private static String isCollection = "0";  //0 没有收藏  1 收藏
    private ClipboardManager myClipboard;

    @Autowired()
    String id;

    @Autowired()
    String name;

    @Autowired()
    String content;

    @Autowired()
    String url;


//    public static Intent getIntent(Context context, BeanTourAround.DataBeanX.DataBean dataBean) {
//        return new Intent(context, TravelDetailsActivity.class)
//                .putExtra("dataBean", dataBean);
//    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);
        tvTitleCenter.setText("旅游详情");
        webUrl = "https://xxtest.upyuns.com/h5/appHtml/view/travelDetails.html?id=" + id;
        initWeb();
        initRxbus();
        initShare(webUrl+"&shareType=app", name, content, url);
        mWebView.loadUrl("JavaScript:getTourStock()"); // Android调用h5
    }

    private void initRxbus() {
        RxBus.tObservable(IDCardCertificationEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<IDCardCertificationEvent>(disposable) {
                    @Override
                    public void onNext(IDCardCertificationEvent event) {
                        mWebView.loadUrl("JavaScript:openModal()"); // Android调用h5
                        llItemBottom.setVisibility(View.GONE);
                    }
                });
    }

    @OnClick({R2.id.iv_back, R2.id.tv_appointment, R2.id.iv_collect, R2.id.iv_share, R2.id.tv_customer_service})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_collect) {
            //收藏
            if ("1".equals(isCollection)) {
                cancelCollect();
                ivCollect.setImageResource(R.drawable.travel_rv_collect);
            } else {
                addCollect();
                ivCollect.setImageResource(R.drawable.common_icon_collected);
            }
            ivCollect.setEnabled(false);

        } else if (id == R.id.iv_share) {
            //分享
            if (shareManager != null) {
                shareManager.open();
            }

        } else if (id == R.id.tv_customer_service) {
            //联系客户

        } else if (id == R.id.tv_appointment) {
            //预订
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGINRV).navigation();
                return;
            }

            BeanUserInfo.UserInfo userInfo = getUserInfo();
            if (userInfo !=null){
                if (userInfo.getCertificationStatus() ==0){
                    ARouter.getInstance().build(Constance.ACTIVITY_URL_IDCARDCERTIFICATION).navigation();
                    return;
                }
            }

            mWebView.loadUrl("JavaScript:openModal()"); // Android调用h5
            llItemBottom.setVisibility(View.GONE);
        }
    }

    private void cancelCollect() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postBodyData(RvFrameConfig.HOST, 2, TourismApi.COMMIT_COLLECT_REMOVE, BaseBean.class, new CancelCollection(mCollectId, "1"), headMap, false);
        }
    }

    private void addCollect() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postBodyData(RvFrameConfig.HOST, 1, TourismApi.COMMIT_COLLECT_ADD, BaseBean.class, new AddCollection(id, "2"), headMap, false);
        }
    }

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

    //收藏请求
    private void requestCollect() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        Map<String, String> map = new HashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            map.put("id", id);
            map.put("type", "2");
            mPresenter.getData(RvFrameConfig.HOST, 0, TourismApi.COMMIT_COLLECT_IS, BeanTourismCollection.class, map, headMap, false);
        }
    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                setCollect((BeanTourismCollection) result);
                break;
            case 1:
                showToast("收藏成功");
                isCollection = "1";
                ivCollect.setEnabled(true);
                break;
            case 2:
                showToast("取消收藏成功");
                isCollection = "0";
                ivCollect.setEnabled(true);
                break;

        }
    }


    /**
     * 查看是否已收藏
     *
     * @param data
     */
    private void setCollect(BeanTourismCollection data) {
        isCollection = data.getData().getStatus();
        mCollectId = data.getData().getId();
        if ("1".equals(data.getData().getStatus())) {
            ivCollect.setImageResource(R.drawable.common_icon_collected);
        } else {
            ivCollect.setImageResource(R.drawable.travel_rv_collect);
        }
    }

    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, String url) {
                return false;
            }
        });
        mWebView.loadUrl(webUrl);

//        mWebView.setWebChromeClient(new WebChromeClient() {
//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//                super.onProgressChanged(view, newProgress);
//                if (newProgress == 100) {
//                    onHideLoading();
//                }
//            }
//        });
    }

    /**
     * 初始化分享
     */
    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_SHAREIMAGE)
                            .withString("icon",url)
                            .withString("name",name)
                            .withString("keyword",content)
                            .withDouble("price",0).navigation();
                } else if (snsPlatform.mShowWord.equals("复制链接")) {
                    copyText();
                }
                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(platform + " 收藏成功啦");

                                } 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(platform + "分享成功啦");

                                    }

                                }

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * 与h5交互
     */
    public class AndroidJs {

        @JavascriptInterface
        public void showButton() {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    llItemBottom.setVisibility(View.VISIBLE);
                }
            });

        }

        @JavascriptInterface
        public void tourStock(int num) {
            if (num > 0) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            } else {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        TvAppointment.setEnabled(false);
                        TvAppointment.setText("已售完");
                        TvAppointment.setBackground(mActivity.getResources().getDrawable(R.color.gray_707070));
                    }
                });

            }
        }

        @JavascriptInterface
        public void readyOrder(String orderJson) {
            if (!TextUtil.isEmpty(orderJson)) {
                beanOrderParam = new Gson().fromJson(orderJson,
                        new TypeToken<BeanOrderParam>() {
                        }.getType());
                if (Integer.valueOf(beanOrderParam.getAdultNum()) < Integer.valueOf(beanOrderParam.getChildNum())){
                    showToast("成人数要大于或等于儿童数");
                }else if (Integer.valueOf(beanOrderParam.getAdultNum()) ==0){
                    showToast("成人数不能为空！");
                }else {
                    startActivity(TravelerConfirmOrderActivity.getIntent(mActivity, beanOrderParam));
                }

            }
        }
    }


    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        shareManager.close();
    }


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

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        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.destroy();// 生命周期销毁

    }

    private class AddCollection {
        private String typeId;
        private String type;

        public AddCollection(String typeId, String type) {
            this.typeId = typeId;
            this.type = type;
        }

        public String getTypeId() {
            return typeId;
        }

        public void setTypeId(String typeId) {
            this.typeId = typeId;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }
    }

    private class CancelCollection {
        private String id;
        private String status;

        public CancelCollection(String id, String status) {
            this.id = id;
            this.status = status;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }


    /**
     * 复制文本
     */
    private void copyText() {
        if (myClipboard == null) {
            myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        }
        ClipData myClip = ClipData.newPlainText("text", webUrl);
        myClipboard.setPrimaryClip(myClip);
        showToast("复制成功！");
    }
}
