package com.wasu.cs.widget.mediacontrol;

/**
 * 通用定包dialog
 */

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.comp.wasuwebview.WasuWebView;
import com.wasu.compfactory.WasuCompFactory;
import com.wasu.cs.jsobject.WR;
import com.wasu.cs.jsobject.WR_Favorites;
import com.wasu.cs.jsobject.WR_History;
import com.wasu.cs.jsobject.WR_Term;
import com.wasu.cs.jsobject.WR_UserCenter;
import com.wasu.cs.jsobject.tv;
import com.wasu.cs.ui.MainRecomPageView;
import com.wasu.cs.widget.viplogin.WasuVipWebView;
import com.wasu.module.datafetch.ObjectBase;
import com.wasu.module.log.WLog;
import com.wasu.util.SystemUtils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import basic.BuilderTypeManager.BuildType;

public class DialogCommonPlanBuy extends Dialog {
    //使用方法 详见"http://con.wtvdev.com/pages/viewpage.action?pageId=4358374"
 /*   public static void main(String[] args) {
      
        Map<String,Object> parms = new HashMap<>();
        parms.put("planBizId","40414579811740000003902");
        parms.put("resourceName","飞狐专区月包");
        parms.put("price",18);//通过询价
        parms.put("thirdIndentId", "3260");
        parms.put("thirdChannel", "SOHU");

        DialogCommonPlanBuy dialog = new DialogCommonPlanBuy(mContext, BuildType.payTypeUrl, parms, new DialogCommonPlanBuy.PayStatusListener() {
            @Override
            public void onPay(int status, int code) {
                if(status == 0){
                    Toast.makeText(mContext,"支付成功",Toast.LENGTH_LONG).show();
                }else {
                  if(code==12){
                     Toast.makeText(mContext,"支付失败，请重新登录再支付！",Toast.LENGTH_LONG).show();
                  }else{
                     Toast.makeText(mContext,"支付失败",Toast.LENGTH_LONG).show();
                  }
                }
            }
        });
        dialog.show();
    }
*/


    private static final String tag = "DialogCommonPlanBuy";

    public static final int PAY_STATUS_OK = 0;
    public static final int PAY_STATUS_FAILED = 1;

    private WasuVipWebView mWebView;


    private String pageUrl;
    Map<String, Object> mParams = null;


    private PayStatusListener payStatusListener;

    public interface PayStatusListener {
        void onPay(int status, int code);
    }


    class JsImp {
        @JavascriptInterface
        public void callback_pay(final String tag, final String code) {
            mWebView.post(new Runnable() {
                public void run() {
                    if (payStatusListener != null && tag != null) {
                        try {
                            boolean retValue = Boolean.valueOf(tag);
                            payStatusListener.onPay(retValue ? PAY_STATUS_OK : PAY_STATUS_FAILED, 0);
                            payStatusListener = null;
                            dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }

        @JavascriptInterface
        public void showMsg(final String result) {
            WLog.d(tag, "showMsg: " + result);
        }

        /**
         * 返回主界面
         */
        @JavascriptInterface
        public void closePage() {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    if (payStatusListener != null) {
                        payStatusListener.onPay(PAY_STATUS_FAILED, 0);
                        payStatusListener = null;
                    }
                    dismiss();
                }
            });
        }

        @JavascriptInterface
        public String getTVID() {
            return AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID);
        }

        @JavascriptInterface
        public String getSoftAppVer() {
            try {
                return String.valueOf(getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0).versionName);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }

        @JavascriptInterface
        public String getSDKVersion() {
            return String.valueOf(Build.VERSION.SDK_INT);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////

    public DialogCommonPlanBuy(Context context, String pageUrl, Map<String, Object> params, PayStatusListener payStatusListener) {
        super(context);
        this.mWebView = new WasuVipWebView(context);
        this.pageUrl = pageUrl;
        this.mParams = params;
        this.payStatusListener = payStatusListener;
        init(context);
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void init(Context context) {
        if (mWebView == null) {
            return;
        }

        if (mWebView.getParent() != null) {
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        setContentView(mWebView);

        Rect screenRect = SystemUtils.getScreenSize(getContext());
        getWindow().setLayout(screenRect.width(), screenRect.height());

        mWebView.addJavascriptInterface(new WR(getContext(), mWebView), "WR");
        mWebView.addJavascriptInterface(new WR_Term(getContext()), "WR_Term");
        mWebView.addJavascriptInterface(new WR_History(getContext()), "WR_History");
        mWebView.addJavascriptInterface(new WR_Favorites(getContext()), "WR_Favorites");
        mWebView.addJavascriptInterface(new tv(getContext()), "tv");
        mWebView.addJavascriptInterface(new WR_UserCenter(getContext()), "WR_UserCenter");

        if (payStatusListener != null) {
            mWebView.addJavascriptInterface(new JsImp(), "WR_Term");
        }

        if (!TextUtils.isEmpty(pageUrl)) {
            pageUrl = getPageUrl();
        }

        setCancelable(true);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mWebView != null) {
            mWebView.loadUrl(TextUtils.isEmpty(pageUrl) ? "about:blank" : pageUrl);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mWebView != null) {
            mWebView.loadUrl("about:blank");
        }
    }


    public String getPageUrl() {
        if (mParams == null) {
            return pageUrl;
        }
        mParams.put("v",1);
        mParams.put("optType","PlanBuy");
        mParams.put("tvId", AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID));
        mParams.put("deviceId", AuthSDK.getInstance().getValue(IAuthInterface.KEY_DEVICEID));
        mParams.put("siteId", BuildType.SITE_ID);
        mParams.put("userKey", AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY));
        mParams.put("token", AuthSDK.getInstance().getValue(IAuthInterface.KEY_TOKEN));
        mParams.put("phone", AuthSDK.getInstance().getValue(IAuthInterface.KEY_PHONE));
        StringBuilder url = new StringBuilder();
        url.append(pageUrl);
        boolean first = true;
        Iterator<Map.Entry<String, Object>> ite = mParams.entrySet().iterator();
        while (ite.hasNext()) {
            Map.Entry<String, Object> me = ite.next();
            String key = me.getKey();
            Object value = me.getValue();

            if (first) {
                url.append("?").append(key).append("=").append(value);
                first = false;
            } else {
                url.append("&").append(key).append("=").append(value);
            }
        }
        return url.toString();
    }


}
