package com.danding.yang800;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.danding.yang800.General.Yang800App;
import com.danding.yang800.Presenter.LoginActivityPresenter;
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.LogUtil;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.Util.UpdateUtil;
import com.danding.yang800.View.AuthCodeCountDown;
import com.danding.yang800.View.NetworkProgressDialog;
import com.qiyukf.unicorn.api.Unicorn;
import com.umeng.analytics.MobclickAgent;


import java.io.File;
import java.util.UUID;

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


public class LoginActivity extends BaseActivity {
    @BindView(R.id.login_button)
    TextView login_button;
    @BindView(R.id.login_codeNoTv)
    TextView login_codeNoTv;
    @BindView(R.id.login_codeTv)
    TextView login_codeTv;
    @BindView(R.id.login_NameEdit)
    EditText login_NameEdit;
    @BindView(R.id.login_CodeEdit)
    EditText login_CodeEdit;
    @BindView(R.id.login_weixinLayout)
    LinearLayout login_weixinLayout;
    LoginActivityPresenter presenter;
    SharedPreferences sp;
    private NetworkProgressDialog pd;
    private PopupWindow popupWindow;
    String epCode = "";
    private long mkeyTime;
    //    boolean permisson = false;
    boolean mustUpdate = false;
    private static final int MY_PERMISSIONS_WRITE_CONTACTS = 2;

    @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_login);
        ButterKnife.bind(this);
        Unicorn.toggleNotification(false);
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        Yang800App.iflogin = false;
        presenter = new LoginActivityPresenter(this);
        presenter.getUploadImgUrl();
        getWritePermission();

        if (sp.getString("epCode", "").equals("")) {
            epCode = UUID.randomUUID().toString();
            sp.edit().putString("epCode", epCode).commit();
        } else {
            epCode = sp.getString("epCode", "");
        }
        sp.edit().putString("Cookie", "").commit();
        sp.edit().putInt("userId", 0).commit();
        sp.edit().putString("token", "").commit();
        sp.edit().putString("storeId", "").commit();
        updateDiy();
//        mustUpdate = new UpdateUtil(this).updateDiy(permisson);
//        ToastUtil.show(this, mustUpdate + "");
    }

    @OnClick({R.id.login_button, R.id.login_codeNoTv, R.id.login_weixinLayout, R.id.login_codeTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_button:
                String name = login_NameEdit.getText().toString().trim();
                String code = login_CodeEdit.getText().toString().trim();
                presenter.login(name, code, epCode);
//                Intent intent = new Intent(LoginActivity.this, MarketActivity.class);
//                startActivity(intent);
//                finish();
                break;
            case R.id.login_codeNoTv:
//                Intent intent1=new Intent(LoginActivity.this,InviteNoteActivity.class);
//                startActivity(intent1);
                showWindow();
//                presenter.buyCheck();
                break;

            case R.id.login_weixinLayout:
                if ((System.currentTimeMillis() - mkeyTime) > 2000) {
                    mkeyTime = System.currentTimeMillis();
                    presenter.wxLogin();
                } else {
                    ToastUtil.show(this, "正在打开微信授权页");
                }
                //startActivity(PictureCheckActivity.class);
                break;
            case R.id.login_codeTv:
                presenter.smsSend(login_NameEdit.getText().toString().trim());
                break;
        }
    }

    public void showWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_popupwindows_smscode, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    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 sendSuccess() {
        AuthCodeCountDown mAuthCodeDown = new AuthCodeCountDown(60 * 1000 + 1100, login_codeTv);
        mAuthCodeDown.start();
        login_codeTv.setEnabled(false);
    }


    @Override
    protected void onResume() {

        super.onResume();
        Yang800App.iflogin = false;
        if (!sp.getString("WXcode", "").equals("")) {
            LogUtil.d(sp.getString("WXcode", ""));
//            if (!Yang800App.tmDevice.equals("") && !Yang800App.tmDevice.equals("null") && Yang800App.tmDevice != null) {
            presenter.weixinLogin(sp.getString("WXcode", ""), epCode);
            sp.edit().putString("WXcode", "").commit();
            //ToastUtil.show(this, sp.getString("WXcode", ""));
//            } else {
//                ToastUtil.show(LoginActivity.this, "没有读取手机信息权限");
//            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sp.edit().putBoolean("WXlogin", false).commit();
        sp.edit().putString("WXcode", "").commit();
    }


    public void loginSuccess(boolean login, boolean referral) {
//        if (status.equals("99")) {
//            if (!isWorked("com.danding.yang800.Service.LoginKeepService")) {
//                Intent startIntent = new Intent(
//                        this,
//                        LoginKeepService.class);
//                startService(startIntent);
//            }
        if (login) {
            sp.edit().putBoolean("login", true).commit();
            String cookie = sp.getString("Cookie", "") + ";S_INFO=" + (100000000 + sp.getInt("userId", 999999999))
                    + ";D_INFO=" + (100000000 + sp.getInt("userId", 999999999));
            sp.edit().putString("Cookie", cookie).commit();
            MobclickAgent.onProfileSignIn(sp.getInt("userId", 999999999) + "");
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        } else {
            if (referral) {
                Intent intent = new Intent(LoginActivity.this, HintActivity.class);
                startActivity(intent);
            } else {
                //TODO买礼包
            }
        }

//            finish();
//        } else if (status.equals("3")) {
//            ToastUtil.show(this, "微信截图审核未通过");
//            startActivity(PictureCheckActivity.class);
//        } else if (status.equals("2")) {
//            ToastUtil.show(this, "微信截图审核中");
//        } else {
////            presenter.sendImgUrl("11");
//            startActivity(PictureCheckActivity.class);
//        }
    }

    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 if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                builder.setTitle("获取存储权限被禁用")
                        .setMessage("请在 设置-应用管理-" + "洋800" + "-权限管理 (将存储权限打开)")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finishAll();
                            }
                        })
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + LoginActivity.this.getPackageName()));
                                LoginActivity.this.startActivityForResult(intent, 10);
                            }
                        }).setCancelable(false).setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                            return true;
                        } else {
                            return false; //默认返回 false
                        }
                    }
                }).show();

            } else {
                getWritePermission();
            }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            getWritePermission();
        }
    }

    public void wxSuccess(boolean login, String nickName, boolean referral) {
//        if (bingPhone && status.equals("99")) {
//            if (!isWorked("com.danding.yang800.Service.LoginKeepService")) {
//                Intent startIntent = new Intent(
//                        this,
//                        LoginKeepService.class);
//                startService(startIntent);
//            }
//            sp.edit().putBoolean("login", true).commit();
//            startActivity(MainActivity.class);
//            finish();
//        } else if (bingPhone && status.equals("3")) {
//            ToastUtil.show(this, "微信截图审核未通过");
//            startActivity(PictureCheckActivity.class);
//        } else if (bingPhone && status.equals("2")) {
//            ToastUtil.show(this, "微信截图审核中");
//        } else if (bingPhone && status.equals("1")) {
//            startActivity(PictureCheckActivity.class);
//        } else if (!bingPhone) {
//            startActivity(BindPhoneActivity.class);
//        }

        if (!login) {
            if (!referral) {
                Intent intent = new Intent(LoginActivity.this, BindPhoneActivity.class);
                intent.putExtra("nickName", nickName);
                startActivity(intent);
            } else {
                Intent intent = new Intent(LoginActivity.this, HintActivity.class);
                startActivity(intent);
            }
        } else {
//            if (status.equals("99")) {
//                if (!isWorked("com.danding.yang800.Service.LoginKeepService")) {
//                    Intent startIntent = new Intent(
//                            this,
//                            LoginKeepService.class);
//                    startService(startIntent);
//                }

            sp.edit().putBoolean("login", true).commit();
            String cookie = sp.getString("Cookie", "") + ";S_INFO=" + (100000000 + sp.getInt("userId", 999999999))
                    + ";D_INFO=" + (100000000 + sp.getInt("userId", 999999999));
            sp.edit().putString("Cookie", cookie).commit();
            MobclickAgent.onProfileSignIn(sp.getInt("userId", 999999999) + "");
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
//            } else if (status.equals("3")) {
//                ToastUtil.show(this, "微信截图审核未通过");
//                startActivity(PictureCheckActivity.class);
//            } else if (status.equals("2")) {
//                ToastUtil.show(this, "微信截图审核中");
//            } else if (status.equals("1")) {
//                startActivity(PictureCheckActivity.class);
//            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && mustUpdate == true) {
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && mustUpdate != true) {
            finishAll();
        }
        return false;
    }

    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")) {
            mustUpdate = 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(LoginActivity.this, conn);
                } else {
                    mustUpdate = true;
                    btn_ok.setVisibility(View.GONE);
                    progressBar.setVisibility(View.VISIBLE);
                    DownloadService.bindService(LoginActivity.this, conn);
                }
//                } else {
//                    Toast.makeText(LoginActivity.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();
                }
            });
        }
    }

    public void toMain() {
        MobclickAgent.onProfileSignIn(sp.getInt("userId", 999999999) + "");
        startActivity(MainActivity.class);
    }

    public void toGifitInfo(String storeSkuSn) {
        Intent intent = new Intent(LoginActivity.this, GiftInfoActivity.class);
        intent.putExtra("storeSkuSn", storeSkuSn);
        startActivity(intent);
    }

    public void toGiftList() {
        startActivity(GiftListActivity.class);
    }
}
