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

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
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.TextView;

import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.statusbar.StatusBarUtil;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.dialog.PaymentTypeSelection;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.ruiwenliu.wrapper.base.presenter.PickerPresenter;
import com.rv.home.rv.module.ui.main.home.bean.OrderPayBean;
import com.rv.home.rv.module.ui.main.home.order.bean.OrderDetailBean;
import com.rv.home.rv.module.ui.main.home.order.bean.OrderListBean;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
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.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

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

/**
 * 会员
 */
public class MemberOrderDetailsActivity extends BaseStatusActivity<PickerPresenter> {


    private static final int TYPE_REQUEST_EVALUATION = 102;
    @BindView(R2.id.webView)
    WebView mWebView;
    @BindView(R2.id.tv_cancel_order)
    TextView tvCancelOrder;
    @BindView(R2.id.tv_pick_up_the_car)
    TextView tvPickUpTheCar;
    @BindView(R2.id.ll_item_bottom)
    LinearLayout llItemBottom;

    private String webUrl;
    private int status;
    private String no;
    private IWXAPI api;
    private double orderAmount;
    private OrderDetailBean.DataBeanX dataBean;


    public static Intent getIntent(Context context, String no) {
        return new Intent(context, MemberOrderDetailsActivity.class)
                .putExtra("no", no);
    }
    @Override
    protected int setLayout() {
        return R.layout.activity_travel_order_details;
    }

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

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

    private void loadDetailData() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.getDataHead(RvFrameConfig.HOST, 1, ApiConfig.HTTP_URL_PRICE_BASEORDER + no, OrderDetailBean.class, headMap, false);
        }
    }

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

        if (disposableSuc != null && !disposableSuc.isDisposed()) {
            disposableSuc.dispose();
        }

        if (disposableFail != null && !disposableFail.isDisposed()) {
            disposableFail.dispose();
        }
    }


    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);
        initRxBus();
        api = WXAPIFactory.createWXAPI(mActivity, RvFrameConfig.APP_ID);

        no = intent.getStringExtra("no");

        webUrl = String.format(ApiConfig.HTTP_URL_VIP_ORDERDETAIL, no);
        initWeb();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                pay((OrderPayBean) result);
                break;
            case 1:
                setData((OrderDetailBean)result);
                break;
        }
    }

    private void setData(OrderDetailBean result) {
        dataBean = result.getData();

        if (dataBean != null) {
            status = dataBean.getStatus();
            orderAmount = dataBean.getRealAmount();
        }
        /**
         *
         (query)
         订单状态
         0–删除
         1–创建订单
         2–取消
         3–待付款
         4–待出行
         5–出行中（进行中）
         6–已完成
         */
        switch (status) {
            case 3:
                tvCancelOrder.setVisibility(View.GONE);
                tvPickUpTheCar.setVisibility(View.VISIBLE);
                break;
            case 6:
                tvCancelOrder.setVisibility(View.GONE);
                tvPickUpTheCar.setVisibility(View.VISIBLE);
                tvPickUpTheCar.setText("去评价");
                break;
            default:
                tvCancelOrder.setVisibility(View.GONE);
                tvPickUpTheCar.setVisibility(View.GONE);
                llItemBottom.setVisibility(View.GONE);
                break;
        }
    }

    private Disposable disposableSuc;
    private Disposable disposableFail;

    @SuppressLint("CheckResult")
    private void initRxBus() {
        disposableSuc = RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<PaymentSuccessfulEvent>() {
                    @Override
                    public void accept(PaymentSuccessfulEvent payEvent) throws Exception {
                        finish();
                    }
                });

        disposableFail = RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<PaymentFailedEvent>() {
                    @Override
                    public void accept(PaymentFailedEvent payEvent) throws Exception {
                        finish();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @OnClick({R2.id.iv_back, R2.id.iv_customer_service, R2.id.tv_cancel_order, R2.id.tv_pick_up_the_car})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();
        } else if (i == R.id.iv_customer_service) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri uri = Uri.parse("tel:" + "4000369369");
            intent.setData(uri);
            startActivity(intent);
        } else if (i == R.id.tv_cancel_order) {
            cancelOnclick();

        } else if (i == R.id.tv_pick_up_the_car) {
            okOnclick();
        }
    }

    /**
     * * 3–待付款
     * * 4–待出行
     * * 5–出行中（进行中）
     * * 6–已完成
     */
    private void okOnclick() {
        switch (status) {
            case 3:
                payShowSelect(no, orderAmount);
                break;
            case 6:
                startActivityForResult(EvaluationActivity.getIntent(mActivity, dataBean.getNo()), TYPE_REQUEST_EVALUATION);
                break;
        }
    }

    private void cancelOnclick() {
        switch (status) {
            case 3:
            case 4:
                break;
            case 5:
                break;
            case 6:
                break;
        }
    }


    /**
     * 支付类型选择
     */
    private void payShowSelect(final String no, final double orderAmount) {
        PaymentTypeSelection dialog = new PaymentTypeSelection(mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.tv_amount, String.format("￥%1$s", orderAmount));
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = v.getId();
                        if (id == R.id.iv_close) {
                            dismiss();
                        } else if (id == R.id.ll_item_wechat) {
//                            payType = 1;
                            helper.getView(R.id.iv_wx_select).setSelected(true);
                            helper.getView(R.id.iv_alipy_select).setSelected(false);
                        } else if (id == R.id.ll_item_alipay) {
//                            payType = 2;
                            helper.getView(R.id.iv_wx_select).setSelected(false);
                            helper.getView(R.id.iv_alipy_select).setSelected(true);
                        } else if (id == R.id.tv_pay_immediately) {
                            dismiss();
                            createOrder(no, 1, 1);
                        }
                    }
                }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);
            }
        };
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    private void createOrder(String orderNo, int payWay, int type) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 0, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderPayBean.class, new payBody(orderNo, payWay, type), headMap, true);
    }

    public class payBody {
        private String orderNo;
        private int payWay;
        private int type;

        public payBody(String orderNo, int payWay, int type) {
            this.orderNo = orderNo;
            this.payWay = payWay;
            this.type = type;
        }

        public String getOrderNo() {
            return orderNo;
        }

        public void setOrderNo(String orderNo) {
            this.orderNo = orderNo;
        }

        public int getPayWay() {
            return payWay;
        }

        public void setPayWay(int payWay) {
            this.payWay = payWay;
        }

        public int getType() {
            return type;
        }

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

    private void pay(OrderPayBean data) {
        try {

            PayReq req = new PayReq();
            req.appId = data.getData().getAppid();
            req.partnerId = data.getData().getPartnerid();
            req.prepayId = data.getData().getPrepayid();
            req.nonceStr = data.getData().getNoncestr();
            req.timeStamp = data.getData().getTimestamp();
            req.packageValue = data.getData().getPackageX();
            req.sign = data.getData().getSign();
            req.extData = "app data"; // optional
            api.sendReq(req);

        } catch (Exception e) {
            showToast("异常");
        }

    }


    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.loadUrl(webUrl);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 85) {
                    onHideLoading();
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setRootViewFitsSystemWindows(mActivity, false);
        ButterKnife.bind(this);
    }

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

        @JavascriptInterface
        public void getCopy() {

        }


        @JavascriptInterface
        public void showMore() {

            ComponentName cmn = new ComponentName(getApplicationContext(), "com.rv.member.MemberCenterActivity");
            Intent intent = new Intent();
            intent.setComponent(cmn);
            startActivity(intent);
            finish();

        }
    }
}
