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.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.frame.base.bus.CancelOrderEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.rv.config.RvFrameConfig;
import com.frame.rv.widget.PayResult;
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.rv.home.rv.module.basic.WebActivity;
import com.ruiwenliu.wrapper.base.presenter.PickerPresenter;
import com.rv.home.rv.module.ui.main.home.bean.OrderAliPayBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderPayBean;
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.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
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;

/**
 * 旅游订单详情页面
 */
public class TravelOrderDetailsActivity extends BaseStatusActivity<PickerPresenter> {

    private static final int TYPE_REQUEST_EVALUATION = 102;
    @BindView(R2.id.pb_progress)
    ProgressBar pbProgress;
    @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 static final int SDK_ALI_PAY_FLAG = 11;
    private String webUrl;
    private int status;
    private String no;
    private IWXAPI api;
    private double orderAmount;
    private OrderListBean.DataBeanX.DataBean dataBean;
    private int payType = 1;//选择支付类型


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

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

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


    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        showTitle(false);
        initRxBus();
        api = WXAPIFactory.createWXAPI(mActivity, RvFrameConfig.APP_ID);
        dataBean = (OrderListBean.DataBeanX.DataBean) intent.getSerializableExtra("dataBean");
        if (dataBean != null) {
            status = dataBean.getStatusX();
            no = dataBean.getNo();
            orderAmount = dataBean.getRealAmount();
        }
        /**
         *
         (query)
         订单状态
         0–删除
         1–创建订单
         2–取消
         3–待付款
         4–待出行
         5–出行中（进行中）
         6–已完成
         */
        switch (status) {
            case 3:
                tvCancelOrder.setVisibility(View.VISIBLE);
                tvPickUpTheCar.setVisibility(View.VISIBLE);
                break;
            case 4:
                tvCancelOrder.setVisibility(View.VISIBLE);
                tvPickUpTheCar.setVisibility(View.VISIBLE);
                tvPickUpTheCar.setText("立即上车");
                break;
            case 5:
                tvCancelOrder.setVisibility(View.GONE);
                tvPickUpTheCar.setVisibility(View.VISIBLE);
                tvPickUpTheCar.setText("去评价");
                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;
        }


        webUrl = ApiConfig.HTTP_URL_CAR_TYPE_TRAVELORDERDETAIL + "?no=" + no;
        initWeb();
    }

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


    @SuppressLint("CheckResult")
    private void initRxBus() {
        RxBus.tObservable(CancelOrderEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<CancelOrderEvent>(disposable) {
                    @Override
                    public void onNext(CancelOrderEvent event) {
                        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 4:
                startActivity(GetOnTheCarQRCodeActivity.getIntent(mActivity, dataBean));
                break;
            case 5:
                break;
            case 6:
                startActivityForResult(EvaluationActivity.getIntent(mActivity, dataBean), TYPE_REQUEST_EVALUATION);
                break;
        }
    }

    private void cancelOnclick() {
        switch (status) {
            case 3:
            case 4:
                startActivityForResult(CancelTheTripActivity.getIntent(mActivity, no,"3"), 1);
                break;
            case 5:
                break;
            case 6:
                break;
        }
    }


    /**
     * 支付类型选择
     */
    private void payShowSelect(final String no, final double orderAmount) {
        payType = 1;
        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);
                        }
                    }
                }, 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) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        headMap.put("Authorization", OkGoUtil.getToken());
        if (payType == 1) {
            mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 0, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderPayBean.class, new payBody(orderNo, payType, 1), headMap, true);
        }else {
            mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 1, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderAliPayBean.class, new payBody(orderNo, payType, 1), 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("异常");
        }

    }


    /**
     * 显示支付宝签名
     */
    public void aliPayData(final OrderAliPayBean bean) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(TravelOrderDetailsActivity.this);
                Map<String, String> result = alipay.payV2(bean.getData(), true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_ALI_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * 支付宝返回数据handler
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_ALI_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        RxBus.post(new PaymentSuccessfulEvent());
                    } else if ("6001".equals(resultStatus)) {
                        showToast("支付取消！");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast(payResult.toString());
                    }
                    break;
                }
            }
        }
    };


    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);//设置进度值
                }
            }
        });
    }

    @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 onClick() {
            startActivity(WebActivity.getIntent(mActivity, mActivity.getString(R.string.rv_charge_details), ApiConfig.HTTP_URL_CAR_TYPE_COSTDETAIL));
        }


        @JavascriptInterface
        public void showMore() {
            ComponentName cmn = new ComponentName(getApplicationContext(), "com.xxfc.rv.MainActivity");
            Intent intent = new Intent();
            intent.putExtra("to", "travel");
            intent.setComponent(cmn);
            startActivity(intent);
            finish();
        }
    }
}
