package com.rv.home.rv.module.ui.main.home;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.frame.base.bus.IDCardCertificationEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
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.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.bean.UserInfoBean;
import com.ruiwenliu.wrapper.util.UtilsManager;
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.DateUtils;
import com.rv.component.utils.IsAppInstall;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.rv.home.rv.module.ui.main.home.bean.CarRentalPriceBean;
import com.rv.home.rv.module.ui.main.home.bean.CarTypeListBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderDataBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderPriceBean;
import com.rv.home.rv.module.ui.main.home.dialog.CheckPriceDialog;
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.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;

/**
 * Created :Auser
 * Date: 2019/5/29.
 * Desc:租车详情
 */
public class CarDetailActivity extends BaseStatusActivity<CommonPresenter> {
    @BindView(R2.id.pb_progress)
    ProgressBar pbProgress;
    @BindView(R2.id.webView)
    WebView mWebView;
    @BindView(R2.id.tv_center)
    TextView tvTitleCenter;
    @BindView(R2.id.iv_collect)
    ImageView ivCollect;
    @BindView(R2.id.iv_share)
    ImageView ivShare;

    private OrderDataBean dataBean;
    private CarTypeListBean.DataBeanX.DataBean mCarBean;
    private ShareManager shareManager;
    private String webUrl;
    private ClipboardManager myClipboard;
    private String begDate;
    private String endDate;
    private CheckPriceDialog checkPriceDialog;

    public static Intent getIntent(Context context, OrderDataBean bean, CarTypeListBean.DataBeanX.DataBean carBean, String startTime, String endTime) {
        return new Intent(context, CarDetailActivity.class)
                .putExtra("bean", bean)
                .putExtra("carBean", carBean)
                .putExtra("startTime", startTime)
                .putExtra("endTime", endTime);
    }

    public static Intent getIntent(Context context, int type) {
        return new Intent(context, CarDetailActivity.class)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)
                .putExtra("type", type);
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        dataBean = (OrderDataBean) intent.getSerializableExtra("bean");
        mCarBean = (CarTypeListBean.DataBeanX.DataBean) intent.getSerializableExtra("carBean");
        begDate = getIntent().getStringExtra("startTime");
        endDate = getIntent().getStringExtra("endTime");
        showTitle(false);
        tvTitleCenter.setText(mActivity.getString(R.string.vehicle_details));
        webUrl = ApiConfig.HTTP_URL_CAR_TYPE_DETAIL + "?id=" + mCarBean.getVehicleModel().getId() + "&companyId=" + mCarBean.getCompany().getId();
        initWeb();
        initRxbus();
        String code = Cookie.getStringValue(getApplicationContext(), SPConstance.USER_JSON_CODE, "");
        initShare(webUrl + "&shareType=app&code=" + code, mCarBean.getVehicleModel().getName(), mCarBean.getVehicleModel().getKeyword(), mCarBean.getVehicleModel().getIcon());

        if (checkPriceDialog == null) {
            checkPriceDialog = new CheckPriceDialog(mActivity);
            checkPriceDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    mWebView.loadUrl("JavaScript:showDailyPriceJs()"); // Android调用h5
                }
            });
        }
    }

    private void initRxbus() {
        RxBus.tObservable(IDCardCertificationEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<IDCardCertificationEvent>(disposable) {
                    @Override
                    public void onNext(IDCardCertificationEvent event) {
                        getOrderPrice();
                    }
                });

        RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PaymentSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(PaymentSuccessfulEvent event) {
                        getUserData();
                        finish();
                    }
                });

        RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PaymentFailedEvent>(disposable) {
                    @Override
                    public void onNext(PaymentFailedEvent event) {
                        getUserData();
                        finish();
                    }
                });
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }


    /**
     * 获取用户信息请求
     */
    private void getUserData() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.getDataHead(RvFrameConfig.ADMIN_POST, 0, ApiConfig.HTTP_URL_APP_USER_INFO, UserInfoBean.class, headMap, false);
        }
    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                userInfoData((UserInfoBean) result);
                break;
            case 1:
                OrderPriceBean priceBean = (OrderPriceBean) result;
                startActivity(ConfirmOrderActivity.getIntent(mActivity, dataBean, mCarBean, getIntent().getStringExtra("startTime"), getIntent().getStringExtra("endTime"), priceBean));
                break;
            case 2:
                checkPrice((CarRentalPriceBean) result);
                break;
        }
    }

    /**
     * 设置价格日历
     *
     * @param result
     */
    private void checkPrice(CarRentalPriceBean result) {
        if (checkPriceDialog != null) {
            checkPriceDialog.setNewData(result.getData());
            checkPriceDialog.show();
        }
    }


    private void userInfoData(UserInfoBean infoBean) {
        if (infoBean != null) {
            UserInfoBean.UserInfo info = infoBean.getData();
            UtilsManager.getInstance(OkGoUtil.application).setSharePreferencesSave(SPConstance.USER_JSON).putString(SPConstance.USER_JSON_USERINFO, JSON.toJSONString(info)).commit();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
//        onShowLoading();
    }

    @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();// 生命周期销毁
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int type = intent.getIntExtra("type", 0);
        if (type == 1) {
            getOrderPrice();
            finish();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

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

    @OnClick({R2.id.iv_back, R2.id.iv_collect, R2.id.iv_share, R2.id.tv_appointment})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.iv_back) {
            finish();
        } else if (view.getId() == R.id.iv_collect) {
            //添加收藏
            addCollection();
        } else if (view.getId() == R.id.iv_share) {
            if (shareManager != null) {
                shareManager.open();
            }
        } else if (view.getId() == R.id.tv_appointment) {
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                RvFrameConfig.RvFrameInfo.TYPE_LOGIN = 1;
                startActivity(LoginRvActivity.getIntent(mActivity, 0));
                return;
            }
            BeanUserInfo.UserInfo userInfo = getUserInfo();
            if (userInfo != null) {
                if (userInfo.getCertificationStatus() == 0) {
                    ARouter.getInstance().build(Constance.ACTIVITY_URL_IDCARDCERTIFICATION).navigation();
                    return;
                }
            }

            getOrderPrice();
        }
    }


    /**
     * 获得订单价格
     */
    private void getOrderPrice() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("driverType", 1);
        map.put("modelId", dataBean.getModelId());
        map.put("startTime", dataBean.getStartTime());
        map.put("endTime", dataBean.getEndTime());
        map.put("dayNum", dataBean.getDayNum());
        mPresenter.getData(RvFrameConfig.VEHICLE_ORDER, 1, ApiConfig.HTTP_URL_GET_ORDER_PRICE, OrderPriceBean.class, map, headMap, true);
    }

    //添加收藏
    private void addCollection() {

    }


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

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                WebResourceResponse response = super.shouldInterceptRequest(view, request);
                return response;
            }
        });
        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);//设置进度值
                }
            }
        });
    }


    /**
     * 初始化分享
     */
    private void initShare(final String url, 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(mActivity.getString(R.string.generate_poster))) {
                    String icon = "";
                    if (TextUtils.isEmpty(mCarBean.getVehicleModel().getPosterBackground())) {
                        icon = mCarBean.getVehicleModel().getIcon();
                    } else {
                        icon = mCarBean.getVehicleModel().getPosterBackground();
                    }

                    ARouter.getInstance()
                            .build(Constance.ACTIVITY_URL_CARPOSTERACTIVITY)
                            .withString("url", url)
                            .withString("imageUrl", icon)
                            .withString("title", mCarBean.getVehicleModel().getName())
                            .withString("content", mCarBean.getVehicleModel().getKeyword())
                            .withString("price", String.valueOf(mCarBean.getVehicleModel().getPrice()))
                            .navigation();

                } else if (snsPlatform.mShowWord.equals(mActivity.getString(R.string.copy_link))) {
                    copyText();
                } else if (snsPlatform.mShowWord.contains(mActivity.getString(R.string.wechat))) {
                    if (!IsAppInstall.isWeixinAvilible(mActivity)) {
                        showToast(mActivity.getString(R.string.not_wechat_hint));
                        return;
                    }
                } else if (snsPlatform.mShowWord.contains("QQ")) {
                    if (!IsAppInstall.isQQClientAvailable(mActivity)) {
                        showToast(mActivity.getString(R.string.not_qq_hint));
                        return;
                    }
                }

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

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

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

                                    showToast(mActivity.getString(R.string.collection_success));

                                } 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(mActivity.getString(R.string.sharing_success));
                                        sharingSuccess();
                                    }

                                }

                            }
                        });
            }
        }, "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 String getToken() {
            return OkGoUtil.getToken();
        }

        /**
         * 显示门店地图
         */
        @JavascriptInterface
        public void showMap() {
            if (mCarBean != null) {
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_CARDETAILMAP)
                        .withString("addrDetail", mCarBean.getCompany().getAddrDetail())
                        .withString("phone", mCarBean.getCompany().getLeaderContactInfo())
                        .withString("name", mCarBean.getCompany().getName())
                        .withDouble("latitude", mCarBean.getCompany().getLatitude())
                        .withDouble("longitude", mCarBean.getCompany().getLongitude())
                        .navigation();
            }

        }

        @JavascriptInterface
        public void toMemberCenter() {
            ComponentName componentName = new ComponentName(getApplicationContext(), "com.rv.member.MemberCenterActivity");
            Intent in = new Intent();
            in.setComponent(componentName);
            startActivity(in);
        }

        /**
         * 查看每天价格
         */
        @JavascriptInterface
        public void showDailyPrice() {
            Map<String, Object> headMap = new LinkedHashMap<>();
            if (OkGoUtil.getToken() != null)
                headMap.put("Authorization", OkGoUtil.getToken());
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("start", begDate);
            map.put("end", endDate);
            mPresenter.getData(RvFrameConfig.HOST, 2, ApiConfig.HTTP_URL_CALENDAR_PRICE + mCarBean.getVehicleModel().getId(), CarRentalPriceBean.class, map, headMap, false);
        }

        @JavascriptInterface
        public void toVR(String url) {
            startActivity(CarVRActivity.getIntent(mActivity, url));
        }
    }

    /**
     * 复制文本
     */
    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(mActivity.getString(R.string.copy_successful));
    }


    /**
     * 分享积分
     */
    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;
        }
    }

}
