package com.efounder.chat.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.http.SslError;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.graphics.drawable.DrawableCompat;
import android.view.View;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.utils.DialogUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.ResStringUtil;
import com.pansoft.library.utils.LogUtils;
import com.pansoft.xmlparse.OptionParser;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Hashtable;
import java.util.Map;

import static com.efounder.frame.utils.Constants.KEY_WORK_CARD_BASE_URL;

public class ZYWorkCardActivity extends com.efounder.ui.BaseActivity implements RadioGroup.OnCheckedChangeListener {
    private SmartRefreshLayout refreshLayout;
    private String userId;
    private String nickName;
    private String userName;
    private String passWord;
    private String avatar;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

        }
    };
    private final String WORK_CARD_BASE_URL = EnvironmentVariable.getProperty(KEY_WORK_CARD_BASE_URL
            , "https://espace.solarsource.cn/client/");
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private String groupName;
    private String groupId;
    private TextView title;
    private TextView mTitle;
    private String punchCardUrl = WORK_CARD_BASE_URL + "EF_GroupPunchCard.html";
    private String cardRecordUrl = WORK_CARD_BASE_URL + "EF_CardRecord.html";
    private SmartRefreshLayout recordRefreshLayout;
    private boolean isFirst = true;
    private ProgressBar pb;
    private Intent intent;
    private WifiManager wifiManager;
    private WebView mwv;
    private WebView wvRecord;
    private RadioButton rb_main;
    private RadioButton rb_list;
    private boolean isPullUp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_pgwrok_card);
        initView();
        getInformation();
        initAMap();
        initWebView(mwv, punchCardUrl);
//        initWebView(wvRecord, cardRecordUrl);
        judgeState();
    }

    private void judgeState() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        boolean isopenGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean netWork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!isopenGPS && wifiManager.isWifiEnabled()) {
            DialogUtil.showDialog(this, ResStringUtil.getString(R.string.wrchatview_gps), ResStringUtil.getString(R.string.wrchatview_open_gps), getResources().getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 2920);
                }
            }, getResources().getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

        } else if (isopenGPS && !wifiManager.isWifiEnabled()) {
            DialogUtil.showDialog(this, ResStringUtil.getString(R.string.wrchatview_wifi), ResStringUtil.getString(R.string.wrchatview_open_wifi),getResources().getString(R.string.common_text_confirm) , new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    wifiManager.setWifiEnabled(true);
                }
            }, getResources().getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
        } else if (!isopenGPS && !wifiManager.isWifiEnabled()) {
            DialogUtil.showDialog(this, ResStringUtil.getString(R.string.wrchatview_wifi_gps), ResStringUtil.getString(R.string.wrchatview_open_wifi_gps), getResources().getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 2920);
                    wifiManager.setWifiEnabled(true);
                }
            }, getResources().getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2920) {
            intent = new Intent(this, ZYWorkCardActivity.class);
            finish();
            startActivity(intent);
            this.overridePendingTransition(0, 0);
        }
    }

    private void initView() {

        Map<String, String> defaultDaka = OptionParser.getInstance()
                .getElementById("defaultDaka");
        groupId = defaultDaka.get("defaultID");
        groupName = defaultDaka.get("defaultName");


        if (groupName == null) {
            Bundle bundle = getIntent().getExtras();
            StubObject stubObject = (StubObject) bundle.getSerializable("stubObject");
            Hashtable stubTable = stubObject.getStubTable();
            groupId = (String) stubTable.get("groupId");
            groupName = (String) stubTable.get("groupName");
        }

        mwv = (WebView) findViewById(R.id.wv);
        wvRecord = (WebView) findViewById(R.id.wv_record);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        recordRefreshLayout = (SmartRefreshLayout) findViewById(R.id.record_refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        recordRefreshLayout.setEnableLoadMore(false);


//        title = (TextView) findViewById(R.id.tv_m_title);
//        View vLine = findViewById(R.id.view_temp);
//        TextView lTitle = (TextView) findViewById(R.id.tv_l_title);
//        mTitle = (TextView) findViewById(R.id.fragmenttitle);
        RadioGroup rg = (RadioGroup) findViewById(R.id.rg_punchcard_navigation);
        rb_main = (RadioButton) findViewById(R.id.rb_card_main);
        rb_list = (RadioButton) findViewById(R.id.rb_card_list);
//        LinearLayout ll_titlebar_back = (LinearLayout) findViewById(R.id.leftbacklayout);
        ImageView btnBack = (ImageView) findViewById(R.id.backButton);
        pb = (ProgressBar) findViewById(R.id.pb_card);
//        ll_titlebar_back.setVisibility(View.VISIBLE);
        selectCard();
        rg.setOnCheckedChangeListener(this);
//        vLine.setVisibility(View.VISIBLE);
//        lTitle.setText(groupName);



        ImageView iv_back = (ImageView) findViewById(R.id.iv_back);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(R.string.wrchatview_daka);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private Drawable tintDrawable(Drawable drawable, int color) {
        Drawable mutate = DrawableCompat.wrap(drawable).mutate();
        DrawableCompat.setTint(mutate, color);
        return mutate;
    }

    private void initWebView(WebView mv, String url) {
        mv.clearCache(true);
        mv.setWebViewClient(new WebViewClient() {//对https支持
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });

        //允许JavaScript执行
        WebSettings settings = mv.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheMaxSize(10 * 1024 * 1024);
        if (Build.VERSION.SDK_INT >= 21) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //webview定位相关设置  
        settings.setGeolocationEnabled(true);
        settings.setDomStorageEnabled(true);
        mv.setVerticalScrollBarEnabled(false);//垂直不显示滚动条   
        mv.addJavascriptInterface(new ZYWorkCardActivity.JavaScriptInterface(), "OSPPlugin");
        mv.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (0 == newProgress)
                    pb.setVisibility(View.VISIBLE);
                if (100 == newProgress) {
                    //        关闭进度
                    pb.setVisibility(View.GONE);
//                    if (View.VISIBLE == mWebViewRecord.getVisibility()) {
                    if (rb_list.isChecked()) {
                        recordRefreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                    if (isPullUp) {
                        Toast.makeText(ZYWorkCardActivity.this, R.string.wrchatview_no_more_data, Toast.LENGTH_LONG).show();
                        isPullUp = false;
                    }
                }
            }
//            }

        });

        mv.loadUrl(url);
//        mWebView.setMode(PullToRefreshBase.Mode.BOTH);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initWebView(mwv, punchCardUrl);
            }
        });

        recordRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initWebView(wvRecord, cardRecordUrl);
            }
        });

    }

    private void initAMap() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //开启 SDK 辅助H5定位功能
        mLocationClient.startAssistantLocation();
        //启动定位
        mLocationClient.startLocation();
    }

    private void getInformation() {
        //132
        userId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        nickName = EnvironmentVariable.getProperty(Constants.KEY_NICK_NAME);
        userName = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        passWord = EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD);
        User user = WeChatDBManager.getInstance().getOneUserById(Integer.parseInt(userId));
        avatar = user.getAvatar();
//        Toast.makeText(getActivity(), userId+nickName+userName+passWord, Toast.LENGTH_SHORT).show();
        LogUtils.e("groupId:" + groupId + ",userId:" + userId + ",passWord=" + passWord);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rb_card_main) {
            selectCard();
            mTitle.setText("打卡");
            if (null != mwv && null != wvRecord ) {
                refreshLayout.setVisibility(View.VISIBLE);
                recordRefreshLayout.setVisibility(View.GONE);
//                initWebView(mWebView, punchCardUrl);
            }
        } else if (checkedId == R.id.rb_card_list) {
            selectList();
//            mWebView.clearFormData();//这个api仅仅清除自动完成填充的表单数据，并不会清除WebView存储到本地的数据。
//            mWebView.clearHistory();//清除当前webview访问的历史记录，只会webview访问历史记录里的所有记录除了当前访问记录.
//            mWebView.clearMatches();//清除网页查找的高亮匹配字符
//            mWebView.clearCache(true);//清除网页访问留下的缓存，由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.
            mTitle.setText(R.string.wrchatview_run_water);
            if (null != mwv && null != wvRecord) {
//                mWebView.loadUrl(cardRecordUrl);
                refreshLayout.setVisibility(View.GONE);
                recordRefreshLayout.setVisibility(View.VISIBLE);
                if (isFirst) {
                    int visibility = wvRecord.getVisibility();
                    LogUtils.e("====" + visibility);
                    int visibility1 = wvRecord.getVisibility();
                    LogUtils.e("==1==" + visibility1);
                    initWebView(wvRecord, cardRecordUrl);
                    isFirst = false;
                }
            }
        }
    }

    private void selectCard() {
        Drawable topList = getResources().getDrawable(R.drawable.tab_turnover_normal);
        rb_list.setCompoundDrawablesWithIntrinsicBounds(null, topList, null, null);

        Drawable topMain = getResources().getDrawable(R.drawable.tab_punchcard_checked);
        Drawable mainDrawableTop = tintDrawable(topMain, getResources().getColor(R.color.chat_red));
        rb_main.setCompoundDrawablesWithIntrinsicBounds(null, mainDrawableTop, null, null);

        rb_main.setTextColor(getResources().getColor(R.color.chat_red));
        rb_list.setTextColor(getResources().getColor(R.color.gray_normal));
    }

    private void selectList() {
        Drawable topMain = getResources().getDrawable(R.drawable.tab_punchcard_normal);
        rb_main.setCompoundDrawablesWithIntrinsicBounds(null, topMain, null, null);

        Drawable topList = getResources().getDrawable(R.drawable.tab_turnover_checked);
        Drawable recordDrawableTop = tintDrawable(topList, getResources().getColor(R.color.chat_red));
        rb_list.setCompoundDrawablesWithIntrinsicBounds(null, recordDrawableTop, null, null);

        rb_list.setTextColor(getResources().getColor(R.color.chat_red));
        rb_main.setTextColor(getResources().getColor(R.color.gray_normal));
    }

    public class JavaScriptInterface {

        public JavaScriptInterface() {

        }

        @JavascriptInterface
        public String getUserInfo() throws JSONException {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", userName);
            jsonObject.put("passWord", passWord);
            jsonObject.put("IMUserName", userId);
            jsonObject.put("IMPassWord", passWord);
            jsonObject.put("nickName", nickName);
            jsonObject.put("groupId", groupId + "");
            jsonObject.put("groupName", groupName);
            jsonObject.put("headImage", avatar);
            return jsonObject.toString();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mwv.clearCache(true);
        wvRecord.clearCache(true);
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }
}
