package com.danding.yang800;

import android.Manifest;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.danding.yang800.Presenter.SetActivityPresenter;
import com.danding.yang800.Service.LoginKeepService;
import com.danding.yang800.Update.AppUpdateUtils;
import com.danding.yang800.Update.DownloadService;
import com.danding.yang800.Update.NumberProgressBar;
import com.danding.yang800.Update.OkGoUpdateHttpUtil;
import com.danding.yang800.Update.UpdateAppBean;
import com.danding.yang800.Update.UpdateAppManager;
import com.danding.yang800.Update.UpdateCallback;
import com.danding.yang800.Util.CacheManageUtil;
import com.danding.yang800.Util.GeneralUtil;
import com.danding.yang800.Util.LogUtil;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.StringUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.MyDialog;
import com.danding.yang800.View.NetworkProgressDialog;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.ProductDetail;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFUserInfo;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.yanzhenjie.sofia.Sofia;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SetActivity extends BaseActivity {
    @BindView(R.id.set_backTv)
    TextView set_backTv;
    @BindView(R.id.set_cacheSizeTv)
    TextView set_cacheSizeTv;
    @BindView(R.id.set_takePassLayout)
    RelativeLayout set_takePassLayout;
    @BindView(R.id.set_changePhoneLayout)
    RelativeLayout set_changePhoneLayout;
    @BindView(R.id.set_clearCacheLayout)
    RelativeLayout set_clearCacheLayout;
    @BindView(R.id.set_versionNameTv)
    TextView set_versionNameTv;
    @BindView(R.id.set_loginOutTv)
    TextView set_loginOutTv;
    @BindView(R.id.set_shopIdTv)
    TextView set_shopIdTv;
    @BindView(R.id.set_phoneNumberTv)
    TextView set_phoneNumberTv;
    @BindView(R.id.set_qiyuLayout)
    RelativeLayout set_qiyuLayout;
    @BindView(R.id.set_aboutLayout)
    RelativeLayout set_aboutLayout;
    @BindView(R.id.set_versionIv)
    ImageView set_versionIv;
    SharedPreferences sp;
    private NetworkProgressDialog pd;
    SetActivityPresenter presenter;
    @BindView(R.id.set_versionLayout)
    RelativeLayout set_versionLayout;
    @BindView(R.id.set_realNameLayout)
    RelativeLayout set_realNameLayout;
    @BindView(R.id.set_realNameTv)
    TextView set_realNameTv;
    private PopupWindow popupWindow;
    boolean hasV;
    boolean update = false;
    boolean mustUpdate = false;
    boolean permisson = false;
    private static final int MY_PERMISSIONS_WRITE_CONTACTS = 2;
    boolean realName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        int type = StatusColorUtil.StatusBarLightMode(this);
//        if (type > 0) {
//            StatusColorUtil.setStatusBarColor(this, R.color.white);
//            StatusColorUtil.StatusBarLightMode(this, type);
//        }
        setContentView(R.layout.activity_set);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        ButterKnife.bind(this);
        initData();
        getWritePermission();
        presenter = new SetActivityPresenter(this);
        presenter.getInfo(sp.getInt("userId", 0) + "");
        set_shopIdTv.setText(sp.getString("storeId", ""));
    }

    private void initData() {
        set_versionNameTv.setText(GeneralUtil.getVersionName(this));
        try {
            String cacheSize = CacheManageUtil.getTotalCacheSize(this);
            if (cacheSize.equals("0K")) {
                set_cacheSizeTv.setText("0.0M");
            } else {
                set_cacheSizeTv.setText(cacheSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    UMWeb web;

    @OnClick({R.id.set_backTv, R.id.set_takePassLayout, R.id.set_changePhoneLayout, R.id.set_clearCacheLayout
            , R.id.set_loginOutTv, R.id.set_qiyuLayout, R.id.set_aboutLayout, R.id.set_versionLayout
            , R.id.set_realNameLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set_backTv:
                finish();
                break;
            case R.id.set_takePassLayout:
                Intent intent = new Intent(SetActivity.this, CheckPhoneActivity.class);
                intent.putExtra("profit", false);
                startActivityForResult(intent, 0);
                break;
            case R.id.set_changePhoneLayout:
                Intent intentProve = new Intent(SetActivity.this, ProvePhoneActivity.class);
                startActivityForResult(intentProve, 0);
                break;
            case R.id.set_clearCacheLayout:
                final MyDialog okCancelDialog = MyDialog.createBuilder(SetActivity.this).setAlertTitle("清除缓存").
                        setMsg("是否确认清除缓存？");
                okCancelDialog.setOKOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        okCancelDialog.dismiss();
                        CacheManageUtil.clearAllCache(SetActivity.this);
                        try {
                            String cacheSize = CacheManageUtil.getTotalCacheSize(SetActivity.this);
                            if (cacheSize.equals("0K")) {
                                set_cacheSizeTv.setText("0.0M");
                                ToastUtil.show(SetActivity.this, "清除成功");
                            } else {
                                set_cacheSizeTv.setText(cacheSize);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                okCancelDialog.setOnCancelListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        okCancelDialog.dismiss();
                    }
                });
                okCancelDialog.show();


                break;
            case R.id.set_loginOutTv:
                final MyDialog loginOutDialog = MyDialog.createBuilder(SetActivity.this).setAlertTitle("退出登录").
                        setMsg("是否确认退出当前账户？");
                loginOutDialog.setOKOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        loginOutDialog.dismiss();
                        sp.edit().putString("Cookie", "").commit();
                        sp.edit().putInt("userId", 0).commit();
                        sp.edit().putString("token", "").commit();
                        sp.edit().putString("storeId", "").commit();
                        sp.edit().putBoolean("login", false).commit();
                        if (isWorked("com.danding.yang800.Service.LoginKeepService")) {
                            Intent stopIntent = new Intent(SetActivity.this, LoginKeepService.class);
                            stopService(stopIntent);
                        }
                        startActivity(LoginActivity.class);
                        overridePendingTransition(0, 0);
//                        finishAll();
                    }
                });
                loginOutDialog.setOnCancelListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        loginOutDialog.dismiss();
                    }
                });
                loginOutDialog.show();
                break;
            case R.id.set_qiyuLayout:
                String title = "洋800客服";
                ConsultSource source = new ConsultSource("", "首页", "custom information string");
                ProductDetail.Builder pb = new ProductDetail.Builder();
                source.productDetail = pb.create();
//                YSFUserInfo userInfo = new YSFUserInfo();
//                userInfo.userId = "uid";
//                userInfo.authToken = "auth-token-from-user-server";
//                userInfo.data = "[ {'key':'real_name', 'value':'张三'}, {'key':'mobile_phone', 'hidden':true}, {'key':'email', 'value':'13800040000@163.com'}, {'key':'avatar', 'value': 'https://qiyukf.com/def_avatar.png'}, {'index':0, 'key':'account', 'label':'账号', 'value':'zhangsan' , 'href':'http://example.domain/user/zhangsan'}, {'index':1, 'key':'sex', 'label':'性别', 'value':'先生'}, {'index':5, 'key':'reg_date', 'label':'注册日期', 'value':'2015-11-16'}, {'index':6, 'key':'last_login', 'label':'上次登录时间', 'value':'2015-12-22 15:38:54'} ]";
//                Unicorn.setUserInfo(userInfo);
                Unicorn.openServiceActivity(this, title, source);
                break;
            case R.id.set_aboutLayout:
                startActivity(AboutActivity.class);
                break;
            case R.id.set_versionLayout:
                updateDiy();
                break;
            case R.id.set_realNameLayout:
                if (!realName) {
                    Intent intentR = new Intent(SetActivity.this, RealNameActivity.class);
                    startActivityForResult(intentR, 0);
                }
                break;


        }
    }


    private boolean isWorked(String className) {
        ActivityManager myManager = (ActivityManager) this
                .getApplicationContext().getSystemService(
                        this.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(300);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(className)) {
                return true;
            }
        }
        return false;
    }

    public void initDialog() {
        if (pd == null) {
            pd = NetworkProgressDialog.createDialog(this);
            if (!pd.isShowing()) {
                pd.show();
            }
        }
    }

    public void dismissDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
            NetworkProgressDialog.clear();
        }
    }

    public void initData(String mobile, boolean realNameSet, String realname) {
        set_phoneNumberTv.setText(mobile);
        realName = realNameSet;
        if (realNameSet) {
            set_realNameTv.setText(realname);
        } else {
            set_realNameTv.setText("未实名");
        }
    }

    private void getWritePermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_CONTACTS);
            } else {
                permisson = true;
            }
        } else {
            permisson = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_WRITE_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                permisson = true;
            } else {

            }

            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            presenter.getInfo(sp.getInt("userId", 0) + "");
        }
    }

    public void hasNewVersion(boolean hasVer) {
        hasV = hasVer;
        if (hasVer) {
            set_versionIv.setVisibility(View.VISIBLE);
        } else {
            set_versionIv.setVisibility(View.GONE);
        }
    }

    UpdateAppBean updateApp;

    public void updateDiy() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        AppUpdateUtils.deleteFolderFile(path + File.separator + "app");
        new UpdateAppManager
                .Builder()
                .setActivity(this)
                .setHttpManager(new OkGoUpdateHttpUtil())
                .setUpdateUrl("appApk.getUpdateInfo")
                .setPost(false)
                .setTargetPath(path)
                .build()
                .checkNewApp(new UpdateCallback() {
                    @Override
                    protected UpdateAppBean parseJson(UpdateAppBean updateAppBean) {

                        return updateAppBean;
                    }

                    @Override
                    public void hasNewApp(UpdateAppBean update, UpdateAppManager updateAppManager, String update_log, String update_must) {
                        updateApp = update;
                        showWindow(update_log, update_must);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp() {
                    }
                });
    }

    NumberProgressBar progressBar;
    Button btn_ok;

    public void showWindow(String update_log, final String update_must) {
        if (update_must.equals("1")) {
            update = true;
        }
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.lib_update_app_dialog, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        btn_ok = (Button) contentView.findViewById(R.id.btn_ok);
        progressBar = (NumberProgressBar) contentView.findViewById(R.id.progressBar);
        TextView tv_update_info = (TextView) contentView.findViewById(R.id.tv_update_info);
        tv_update_info.setText(update_log);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (permisson) {
                    if (update_must.equals("0")) {
//                        updateAppManager.download();
                        popupWindow.dismiss();
                        mustUpdate = false;
                        DownloadService.bindService(SetActivity.this, conn);
                    } else {
                        mustUpdate = true;
                        btn_ok.setVisibility(View.GONE);
                        progressBar.setVisibility(View.VISIBLE);
                        DownloadService.bindService(SetActivity.this, conn);
                    }
                } else {
                    Toast.makeText(SetActivity.this, "没有读取存储权限", Toast.LENGTH_SHORT).show();
                }

            }

        });
        ImageView iv_close = (ImageView) contentView.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (update_must.equals("0")) {
                    popupWindow.dismiss();
                } else {
                    finish();
                }

            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            startDownloadApp((DownloadService.DownloadBinder) service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private void startDownloadApp(DownloadService.DownloadBinder binder) {
        // 开始下载，监听下载进度，可以用对话框显示
        if (updateApp != null) {

            binder.start(updateApp, new DownloadService.DownloadCallback() {
                @Override
                public void onStart() {
                    progressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onProgress(float progress, long totalSize) {
                    if (mustUpdate) {
                        progressBar.setProgress(Math.round(progress * 100));
                        progressBar.setMax(100);
                    }
                }

                @Override
                public void setMax(long total) {

                }

                @Override
                public boolean onFinish(File file) {
                    if (mustUpdate)
                        popupWindow.dismiss();
                    return true;
                }

                @Override
                public void onError(String msg) {
                    if (mustUpdate)
                        popupWindow.dismiss();
                }
            });
        }
    }
}
