package com.rv.rvmine.traveler;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.frame.base.bus.LoginSuccessfulEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.RxBus;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.other.TagAliasOperatorHelper;
import com.ruiwenliu.wrapper.util.AppUtils;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.rv.home.rv.module.ui.login.RegisteredActivity;
import com.rv.rvmine.R;
import com.rv.rvmine.R2;
import com.rv.version.DownListenerManager;
import com.rv.version.bean.VersionCheckBean;
import com.rv.version.util.UpdateAppUtils;
import com.yuyife.okgo.OkGoUtil;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.ruiwenliu.wrapper.other.TagAliasOperatorHelper.ACTION_DELETE;
import static com.ruiwenliu.wrapper.other.TagAliasOperatorHelper.sequence;

/**
 * 设置
 */

public class SettingActivity extends BaseStatusActivity<CommonPresenter> implements DownListenerManager.DownListener {

    @BindView(R2.id.tv_version)
    TextView tvVersion;
    @BindView(R2.id.tv_out_sign)
    TextView tvOutSign;
    private UpdateAppUtils updateAppUtils;
    private VersionCheckBean versionCheckBean = null;

    private String versionName;

    @Override
    protected int setLayout() {
        return R.layout.activity_setting;
    }


    public static Intent getIntent(Context context) {
        return new Intent(context, SettingActivity.class);
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(getString(R.string.setting_title));
        isShowLoadingError = false;
        initRxBus();

        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            tvOutSign.setText("立即登录");
//            tvOutSign.setBackgroundResource(R.drawable.shape_rv_bg_shallow_dark_yellow_circle);
        } else {
            tvOutSign.setText("退出登录");
//            tvOutSign.setBackgroundResource(R.drawable.shape_rv_button_light_gray);
        }

        DownListenerManager.getInstance().addDownListener(this);

        versionName = UpdateAppUtils.getAppVersionName(this);
        if (DownListenerManager.getInstance().isDown()) {
            tvVersion.setText("下载中_" + DownListenerManager.getInstance().getProgress() + "%");
        } else {
            tvVersion.setText("当前版本 V" + versionName);
        }
    }

    private void initRxBus() {
        RxBus.tObservable(LoginSuccessfulEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(LoginSuccessfulEvent event) {
                        tvOutSign.setText("退出登录");
//                        tvOutSign.setBackgroundResource(R.drawable.shape_rv_button_light_gray);
                    }
                });
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        checkVersion();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                versionCheckBean = (VersionCheckBean) result;
                if (versionCheckBean == null || versionCheckBean.isRel() == true) {
                    if (tvVersion != null) {
                        tvVersion.setText("已是最新版本V" + UpdateAppUtils.getAppVersionName(this));
                    }
                }

                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        if (updateAppUtils == null) {
            updateAppUtils = UpdateAppUtils.from(SettingActivity.this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DownListenerManager.getInstance().removeDownListener(this);
    }

    @OnClick({R2.id.rl_item_account_safe, R2.id.ll_item_app_push, R2.id.rl_item_clear_cache, R2.id.rl_item_check_for_updates, R2.id.rl_item_about_us, R2.id.tv_out_sign})

    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_item_account_safe) {
            //修改密码
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                startActivity(LoginRvActivity.getIntent(mActivity, 0));
                return;
            }

            startActivity(new Intent(mActivity, AccountSafeActivity.class));

//            startActivity(RegisteredActivity.getIntent(mActivity, 1, 0));

        } else if (id == R.id.ll_item_app_push) {
            //App推送消息
            showToast("亲，该功能还在开发中。。。");
        } else if (id == R.id.rl_item_clear_cache) {
            //清除缓存
            deleteDir(Environment.getExternalStorageDirectory() + "/photo/camera");
            deleteDir(Environment.getExternalStorageDirectory() + "/photo/crop");
            showToast("清理成功！");


        } else if (id == R.id.rl_item_check_for_updates) {

            if (!DownListenerManager.getInstance().isDown())
                //检查更新
                if (versionCheckBean != null && versionCheckBean.isRel() == false) {

                    if (versionCheckBean != null && !TextUtils.isEmpty(versionCheckBean.getData().getDownloadUrl())) {
                        updateAppUtils.serverVersionCode(versionCheckBean.getData().getWeigh())
                                .serverVersionName(versionCheckBean.getData().getVersionName())
                                .apkPath(versionCheckBean.getData().getDownloadUrl())
                                .updateInfo(versionCheckBean.getData().getContent())
                                .apkSize(versionCheckBean.getData().getPackagesize())
                                .isForce(versionCheckBean.getData().getIsCompel() == 0 ? false : true)
                                .isShowToast(true)
                                .update();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "当前已是最新版本", Toast.LENGTH_SHORT).show();
                }

        } else if (id == R.id.rl_item_about_us) {
            //关于我们
            startActivity(AboutUsActivity.getIntent(mActivity));

        } else if (id == R.id.tv_out_sign) {
            //退出登录

            //登录
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                startActivity(LoginRvActivity.getIntent(mActivity, 0));
                return;
            }

            boolean isAliasAction = true;
            TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
            tagAliasBean.action = ACTION_DELETE;
            sequence++;
//            if (isAliasAction) {
//                tagAliasBean.alias = registeredBean.getData().getUserId();
//            } else {
//                tagAliasBean.tags = null;
//            }
            tagAliasBean.isAliasAction = isAliasAction;
            TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);

            AppUtils.logout(getApplicationContext());
            setResult(201);
            showToast("退出成功！");
            finish();
        }
    }

    /****
     * 检测版本
     */
    private void checkVersion() {

        Map<String, Object> headMap = new LinkedHashMap<>();
        if (!TextUtils.isEmpty(versionName)) {
            mPresenter.getData(0, String.format(ApiConfig.HTTP_URL_VERSION_CHECK, versionName), VersionCheckBean.class, headMap, false);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1001:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    updateAppUtils.download();
                } else {
                    Toast.makeText(getApplicationContext(), "授权失败,无法下载最新App", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


    public static boolean deleteDir(String path) {
        File file = new File(path);
        if (!file.exists()) {//判断是否待删除目录是否存在
            return false;
        }

        String[] content = file.list();//取得当前目录下所有文件和文件夹
        if (content != null && content.length > 0) {
            for (String name : content) {
                File temp = new File(path, name);
                if (temp.isDirectory()) {//判断是否是目录
                    if (temp != null && temp.exists() && temp.getAbsolutePath() != null && !temp.getAbsolutePath().isEmpty()) {
                        deleteDir(temp.getAbsolutePath());//递归调用，删除目录里的内容
                        temp.delete();//删除空目录
                    }
                } else {
                    if (!temp.delete()) {//直接删除文件
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void pending() {
        tvVersion.setText("下载准备中...");
    }

    @Override
    public void paused() {
        tvVersion.setText("下载暂停");
    }

    @Override
    public void progress(int progerss) {
        tvVersion.setText("下载中_" + progerss + "%");
    }

    @Override
    public void completed() {
        tvVersion.setText("下载完成");
    }

    @Override
    public void error() {
        tvVersion.setText("下载异常");
    }
}
