package com.casic.dcms.ui.fragment;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.casic.dcms.BuildConfig;
import com.casic.dcms.R;
import com.casic.dcms.base.BaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.NewVersionBean;
import com.casic.dcms.mvp.presenter.LoginOutPresenterImpl;
import com.casic.dcms.mvp.presenter.UpdatePresenterImpl;
import com.casic.dcms.mvp.view.ILoginOutView;
import com.casic.dcms.mvp.view.IUpdateVersionView;
import com.casic.dcms.ui.ChangePasswordActivity;
import com.casic.dcms.ui.HelpfulActivity;
import com.casic.dcms.ui.MainActivity;
import com.casic.dcms.ui.UserInfoActivity;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.SaveKeyValues;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.utils.callback.IDownloadListener;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class MinePageFragment extends BaseFragment implements View.OnClickListener, IUpdateVersionView, ILoginOutView {

    private static final String TAG = "MinePageFragment";
    @BindView(R.id.deviceIdView)
    TextView deviceIdView;
    @BindView(R.id.versionCodeView)
    TextView versionCodeView;
    @BindView(R.id.autoLoginSwitch)
    Switch autoLoginSwitch;
    @BindView(R.id.backWorkSwitch)
    Switch backWorkSwitch;
    @BindView(R.id.loginOutButton)
    QMUIRoundButton loginOutButton;

    private Context context;
    private LoginOutPresenterImpl loginOutPresenter;
    private QMUITipDialog loadingDialog;
    private UpdatePresenterImpl updatePresenter;
    private ProgressDialog progressDialog;
    private ClipboardManager clipboardManager;

    @Override
    protected int initLayoutView() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void setupTopBarLayout() {
        context = getContext();
    }

    @Override
    protected void initData() {
        deviceIdView.setText(OtherUtils.obtainSimCardSerialNumber(context));
        versionCodeView.setText(BuildConfig.VERSION_NAME);
        loginOutPresenter = new LoginOutPresenterImpl(this);
        boolean isAutoLogin = (boolean) SaveKeyValues.getValue("autoLogin", false);
        autoLoginSwitch.setChecked(isAutoLogin);
        loadingDialog = new QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("请求中，请稍后")
                .create();
        updatePresenter = new UpdatePresenterImpl(this);
        clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);

        //下载进度条
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgressDrawable(context.getResources().getDrawable(R.drawable.bg_progress));
        progressDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    protected void initEvent() {
        loginOutButton.setChangeAlphaWhenPress(true);
        autoLoginSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SaveKeyValues.putValue("autoLogin", isChecked);
            }
        });
        backWorkSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    new QMUIDialog.MessageDialogBuilder(context)
                            .setTitle("要允许应用运行在后台吗？")
                            .setMessage("允许[移动城管]运行在后台可能会缩短电池续航时间" + "\r\n您以后可以在手机[设置]中更改此设置")
                            .setCanceledOnTouchOutside(true)
                            .addAction("取消", (dialog, index) -> dialog.dismiss())
                            .addAction("确定", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                    //根据不同手机打开设置界面
                                }
                            })
                            .create().show();
                } else {
                    Log.d(TAG, "onCheckedChanged: 关闭低电量运行");
                }
            }
        });
    }

    private void startSettingsActivity(@NonNull String packageName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        startActivity(intent);
    }

    private void startSettingsActivity(@NonNull String packageName, @NonNull String activityDir) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(packageName, activityDir));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @OnClick({R.id.userNameLayout, R.id.passwordLayout, R.id.helpfulLayout, R.id.copyView, R.id.updateVersionView, R.id.loginOutButton})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.userNameLayout:
                startActivity(new Intent(context, UserInfoActivity.class));
                break;
            case R.id.passwordLayout:
                startActivity(new Intent(context, ChangePasswordActivity.class));
                break;
            case R.id.helpfulLayout:
                startActivity(new Intent(context, HelpfulActivity.class));
                break;
            case R.id.copyView:
                ClipData clipData = ClipData.newPlainText("deviceId", deviceIdView.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                ToastHelper.showToast("复制成功", ToastHelper.SUCCESS);
                break;
            case R.id.updateVersionView:
                updatePresenter.onReadyRetrofitRequest();
                break;
            case R.id.loginOutButton:
                //退出登录对话框
                new QMUIDialog.MessageDialogBuilder(context)
                        .setTitle("退出登录")
                        .setMessage("确定要退出吗？")
                        .setCanceledOnTouchOutside(false)
                        .addAction("取消", (dialog, index) -> dialog.dismiss())
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                loginOutPresenter.onReadyRetrofitRequest();
                            }
                        }).create().show();
                break;
            default:
                break;
        }
    }

    @Override
    public void obtainLoginOutResult(ActionResultBean resultBean) {
        MainActivity.sendEmptyMessage(Constant.LOGIN_OUT);
    }

    @Override
    public void showProgress() {
        loadingDialog.show();
    }

    @Override
    public void hideProgress() {
        loadingDialog.dismiss();
    }

    @Override
    public void obtainVersionResult(NewVersionBean resultBean) {
//        Log.d(TAG, "obtainVersionResult: " + new Gson().toJson(resultBean));
        if (resultBean.isSuccess()) {
            NewVersionBean.DataBean data = resultBean.getData();
            String version = data.getVersion();
            if (BuildConfig.VERSION_NAME.equals(version)) {
                ToastHelper.showToast("暂无新版本，无需更新", ToastHelper.INFO);
            } else {
                String downloadUrl = StringHelper.appendDownloadUrl(data.getDownloadUrl());
                //http://111.198.10.15:11409/static/app/v1.1.0.0.apk
                new QMUIDialog.MessageDialogBuilder(context)
                        .setTitle("版本更新")
                        .setMessage("确定下载新版本吗？")
                        .setCanceledOnTouchOutside(false)
                        .addAction("取消", (dialog, index) -> dialog.dismiss())
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                                //下载新版本
                                progressDialog.setMessage("下载新版本中...");
                                progressDialog.show();
                                downloadApk(downloadUrl);
                            }
                        }).create().show();
            }
        }
    }

    //下载apk
    private void downloadApk(String url) {
        OtherUtils.downloadFile(url, new IDownloadListener() {
            @Override
            public void onDownloadStart(long totalBytes) {
                progressDialog.setMax((int) totalBytes);
                progressDialog.show();
            }

            @Override
            public void onProgressChanged(long sumBytes) {
                progressDialog.setProgress((int) sumBytes);
            }

            @Override
            public void onDownloadEnd(File file) {
                progressDialog.dismiss();
                installApk(file);
            }
        });
    }

    //安装apk文件
    private void installApk(File apk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
            // 通过FileProvider创建一个content类型的Uri
            data = FileProvider.getUriForFile(context, "com.casic.dcms.install.fileProvider", apk);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
        } else {
            data = Uri.fromFile(apk);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (loginOutPresenter != null) {
            loginOutPresenter.disposeRetrofitRequest();
        }
        if (updatePresenter != null) {
            updatePresenter.disposeRetrofitRequest();
        }
    }
}
