package com.sunzee.ui.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sunzee.R;
import com.sunzee.base.BaseFragment;
import com.sunzee.base.MvpActivity;
import com.sunzee.model.Heartbeat;
import com.sunzee.model.domain.ApkInfoBean;
import com.sunzee.model.domain.Name;
import com.sunzee.model.message.ApiMessageEvent;
import com.sunzee.model.message.DownLoadMessageEvent;
import com.sunzee.mvp.home.HomePresenter;
import com.sunzee.mvp.home.HomeView;
import com.sunzee.service.DownPresenter;
import com.sunzee.service.MyService;
import com.sunzee.ui.dialog.ManagementSystemDialog;
import com.sunzee.ui.dialog.NormalDialog;
import com.sunzee.ui.dialog.ShutdownDialog;
import com.sunzee.utils.FileUtil;
import com.sunzee.utils.HomePagerSimpleFactory;
import com.sunzee.utils.SharedPreferencesUtils;
import com.sunzee.utils.ToastUtil;
import com.sunzee.utils.UiUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

/**
 * 后台首页 activity
 */
public class HomeActivity extends MvpActivity<HomePresenter> implements HomeView, View.OnClickListener, DownPresenter.ProgressUpdate {

    private NavigationView mNavigationView;
    private FragmentManager mFragmentManager;

    private TextView mTvConnectionSystem;
    private String systemId;
    private TextView mTvSystemId;
    private ManagementSystemDialog mManagementSystemDialog;
    private static final String TAG = "HomeActivity";
    private TextView mTvVersion;
    private TextView mTvUpdataAPK;
    private LinearLayout mLlBlack;
    private ImageView mIvShutownLogo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initView();
        initEvent();
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    private void initView() {
        mNavigationView = findViewById(R.id.bnv_main_navigationbar);
        mTvVersion = findViewById(R.id.tv_version);
        mTvUpdataAPK = findViewById(R.id.tv_updatapk);
        mLlBlack = findViewById(R.id.ll_black);
        mIvShutownLogo = findViewById(R.id.iv_shutown_logo);
        mNavigationView.setItemIconTintList(null);
        mIvShutownLogo.setOnClickListener(this);
        mFragmentManager = getSupportFragmentManager();
        mTvConnectionSystem = findViewById(R.id.connection_system);
        mTvSystemId = findViewById(R.id.tv_system_id);
        String managerId = (String) SharedPreferencesUtils.getParam(Name.SYSTEM_ID, "");
        if (managerId != null && !TextUtils.isEmpty(managerId)) {
            cheeckConnectState(false);
        }
        DownPresenter downPresenter = DownPresenter.getInstance();
        downPresenter.setProgressUpdate(this);
    }


    private void initEvent() {
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //根据id切换页面
                BaseFragment baseFragment = switchPage(item);
                if (baseFragment != null) {
                    switchFragment(baseFragment);
                }
                return true;
            }
        });
        mTvConnectionSystem.setOnClickListener(this);
        mTvUpdataAPK.setOnClickListener(this);
        mLlBlack.setOnClickListener(this);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.connection_system:
                //连接服务器
                connectToServer();
                break;
            case R.id.tv_updatapk:
                //检查更新
                mvpPresenter.updataapk();
                break;
            case R.id.ll_black:
                gotoAdvertisingActivity();
                break;
            case R.id.iv_shutown_logo:
                showGuanjiDialog();
                break;
        }
    }

    private void gotoAdvertisingActivity() {
        startActivity(new Intent(HomeActivity.this, AdvertisingActivity.class));
        finish();
    }

    /**
     * 连接服务器
     */
    private void connectToServer() {
        if (mManagementSystemDialog == null) {
            mManagementSystemDialog = new ManagementSystemDialog(HomeActivity.this);
        }
        mManagementSystemDialog.setCanceledOnTouchOutside(true);
        mManagementSystemDialog.setListener(new ManagementSystemDialog.DialogClickListener() {

            @Override
            public void onClickListener(int type, String text) {
                switch (type) {
                    case R.id.btn_apply:
                        if (Heartbeat.clientId == null || Heartbeat.clientId.equals("")) {
                            ToastUtil.showToast(UiUtil.getStringRes(R.string.idsb));
                            return;
                        }
                        systemId = text;
                        mvpPresenter.connectionSystem(text);
                        SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 1);
                        mTvSystemId.setText("连接申请中");
                        mTvConnectionSystem.setVisibility(View.GONE);
                        ToastUtil.showToast("连接申请中，请稍后！");
                        break;
                }
            }
        });
        mManagementSystemDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(ApiMessageEvent messageEvent) {
        switch (messageEvent.getName()) {
            case "statusType":
                //刷新界面:心跳
                cheeckConnectState(true);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(DownLoadMessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case downloadApkSuccess:
                //下载成功安装
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/apk/" + "mht.apk");
                intent.setDataAndType(Uri.fromFile(new File(file.getAbsolutePath())),
                        "application/vnd.android.package-archive");
                startActivity(intent);
                if (updateDialog != null) {
                    updateDialog.dismiss();
                }
                break;
            case downloadApkProcess:
                //下载apk进度更新
                break;
            default:
                break;
        }
    }


    /**
     * 检查连接状态并更新界面
     *
     * @param isFrist 是否第一次初始化
     */
    private void cheeckConnectState(boolean isFrist) {
        int connectState = (int) SharedPreferencesUtils.getParam(Name.CONNECT_STATE, -1);
        if (connectState == 2) {
            String param = (String) SharedPreferencesUtils.getParam(Name.SYSTEM_ID, "");
            if (param != null && !TextUtils.isEmpty(param)) {
                mTvSystemId.setVisibility(View.VISIBLE);
                mTvSystemId.setText("已连接：" + param);
                mTvConnectionSystem.setVisibility(View.GONE);
                ToastUtil.showToast("连接成功");
            }
            SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 2);
            Heartbeat.deviceId = FileUtil.getDeviceId();
            Log.d(TAG, "cheeckConnectState: " + isFrist);
            if (isFrist) {
                //开始心跳
                Intent intent = new Intent(HomeActivity.this, MyService.class);
                Bundle bundle = new Bundle();
                bundle.putInt("heartbeat", 3);
                intent.putExtras(bundle);
                startService(intent);
            }
        } else if (connectState == 1) {
            mTvSystemId.setText("连接申请中！！！");
            mTvConnectionSystem.setVisibility(View.GONE);
        } else if (connectState == 0) {
            mTvConnectionSystem.setVisibility(View.VISIBLE);
            mTvSystemId.setVisibility(View.GONE);
        }
    }

    private BaseFragment switchPage(MenuItem item) {
        //1.一直频繁来回切换的。2.那么对象不能创建太多。单例。3.每个页面都是一个新的对象。
        BaseFragment fragment = HomePagerSimpleFactory.getFragment(item.getItemId());
        return fragment;
    }

    private void switchFragment(BaseFragment fragment) {
        FragmentTransaction ftransaction = mFragmentManager.beginTransaction();
        ftransaction.replace(R.id.fl_home_content, fragment);
        ftransaction.commit();
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initSuccess(String result) {
        if (result.equals("设备申请中，请耐心等待")) {
            ToastUtil.showToast(UiUtil.getStringRes(R.string.connecting1));
            SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 1);
            cheeckConnectState(false);
        } else if (result.equals("该设备已经初始化")) {
            //连接成功
            //在service进行同步
            EventBus.getDefault().post(new ApiMessageEvent("statusType" + "1", null));
            SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 2);
            Log.e(TAG, "statusType: 申请通过");
            SharedPreferencesUtils.setParam(Name.SYSTEM_ID, Heartbeat.managerId);
            cheeckConnectState(false);
            Heartbeat.deviceId = FileUtil.getDeviceId();
        } else if (result.equals("找不到商家")) {
            SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 0);
        } else if (result.equals("设备商家类型错误")) {
            SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 0);
        } else {
            SharedPreferencesUtils.setParam(Name.CONNECT_STATE, 0);
        }
    }

    // 是否要更新
    private boolean isUpdate;

    @Override
    public void updataSuccess(ApkInfoBean apkInfoBean) {
        //当前版本号
        int versionCode = getVersionCode();
        //下载的版本号
        int version = apkInfoBean.getVersion();
        if (version > versionCode) {
            //更新
            isUpdate = true;
            showUpdateDialog(apkInfoBean.getVersionName(), isUpdate, version, apkInfoBean.getDownloadUrl(), apkInfoBean.getVersionInfo());
        } else {
            //不更新
            isUpdate = false;
            showUpdateDialog(apkInfoBean.getVersionName(), isUpdate, version, apkInfoBean.getDownloadUrl(), apkInfoBean.getVersionInfo());
        }
    }

    /*
     * 获取当前程序的版本号
     */
    private int getVersionCode() {
        //获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packInfo.versionCode;
    }

    //检查更新
    private NormalDialog updateDialog;

    /**
     * 检查更新弹窗
     *
     * @param versionName 版本号
     * @param isUpdate    是否要更新
     * @param version     版本号
     * @param url         下载地址
     * @param versionInfo 更新内容
     */
    private void showUpdateDialog(String versionName, final boolean isUpdate, final int version, final String url, String versionInfo) {
        if (updateDialog == null) {
            updateDialog = new NormalDialog(HomeActivity.this);
        }
        updateDialog.setListener(new NormalDialog.DialogClickListener() {
            @Override
            public void onClickListener(int type) {
                switch (type) {
                    case R.id.btn_confirm:
                        if (isUpdate) {
                            //更新 下载
                            mvpPresenter.downloadApk(url, version);
                        } else {
                            //不更新
                            updateDialog.dismiss();
                        }
                        break;
                    case R.id.btn_cancel:
                        ToastUtil.showToast("取消");
                        updateDialog.dismiss();
                        break;
                }
            }
        });
        updateDialog.setUpdateContent(R.string.check_update, versionName, isUpdate, versionInfo);
        updateDialog.show();
    }

    @Override
    public void onProgressUpdate(double mDownload_so_far, double mDownload_all) {
        if (updateDialog != null) {
            updateDialog.setContent((int) ((mDownload_so_far / mDownload_all) * 100D));
        }
    }

    private ShutdownDialog shutdownDialog;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void showGuanjiDialog() {

        if (shutdownDialog == null) {
            shutdownDialog = new ShutdownDialog(HomeActivity.this);
        }
        shutdownDialog.setCanceledOnTouchOutside(true);
        shutdownDialog.setListener(new ShutdownDialog.DialogClickListener() {
            @Override
            public void onClickListener(int type) {
            }
        });
        shutdownDialog.setBtnText(R.string.guang_ji, R.string.guang_ji1, R.string.guan_ji_now, R.string.open_now);
        shutdownDialog.show();
    }
}
