package com.casic.dcms.ui.fragment;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.CompoundButton;

import androidx.core.content.FileProvider;

import com.casic.dcms.BuildConfig;
import com.casic.dcms.R;
import com.casic.dcms.base.AndroidxBaseFragment;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.NewVersionBean;
import com.casic.dcms.databinding.FragmentMineBinding;
import com.casic.dcms.mvp.presenter.impl.LoginOutPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.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.FileUtils;
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.casic.dcms.widgets.AlertControlDialog;

import java.io.File;

public class MinePageFragment extends AndroidxBaseFragment<FragmentMineBinding> implements IUpdateVersionView, ILoginOutView {

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

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

    @Override
    protected void initData() {
        viewBinding.deviceIdView.setText(OtherUtils.obtainSimCardSerialNumber(context));
        viewBinding.versionCodeView.setText(BuildConfig.VERSION_NAME);
        loginOutPresenter = new LoginOutPresenterImpl(this);
        boolean isAutoLogin = (boolean) SaveKeyValues.getValue("autoLogin", false);
        viewBinding.autoLoginSwitch.setChecked(isAutoLogin);
        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() {
        viewBinding.userNameLayout.setOnClickListener(v -> startActivity(new Intent(context, UserInfoActivity.class)));
        viewBinding.passwordLayout.setOnClickListener(v -> startActivity(new Intent(context, ChangePasswordActivity.class)));
        viewBinding.helpfulLayout.setOnClickListener(v -> startActivity(new Intent(context, HelpfulActivity.class)));
        viewBinding.autoLoginSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                SaveKeyValues.putValue("autoLogin", isChecked);
            }
        });
        viewBinding.copyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipData clipData = ClipData.newPlainText("deviceId", viewBinding.deviceIdView.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                ToastHelper.showToast("复制成功", ToastHelper.SUCCESS);
            }
        });
        viewBinding.updateVersionView.setOnClickListener(v -> updatePresenter.onReadyRetrofitRequest());

        viewBinding.loginOutButton.setChangeAlphaWhenPress(true);
        viewBinding.loginOutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertControlDialog.Builder()
                        .setContext(context)
                        .setTitle("退出登录")
                        .setMessage("确定要退出吗？")
                        .setNegativeButton("取消")
                        .setPositiveButton("确定")
                        .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                            @Override
                            public void onConfirmClick() {
                                loginOutPresenter.onReadyRetrofitRequest();
                            }

                            @Override
                            public void onCancelClick() {

                            }
                        }).build().show();
            }
        });
    }

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

    @Override
    public void showProgress() {
        OtherUtils.showLoadingDialog(context, "请求中，请稍后");
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    @Override
    public void obtainVersionResult(NewVersionBean resultBean) {
//        Log.d(TAG, "obtainVersionResult: " + new Gson().toJson(resultBean));
        if (resultBean.getCode() == 200) {
            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 AlertControlDialog.Builder()
                        .setContext(context)
                        .setTitle("版本更新")
                        .setMessage("确定下载新版本吗？")
                        .setNegativeButton("取消")
                        .setPositiveButton("确定")
                        .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                            @Override
                            public void onConfirmClick() {
                                //下载新版本
                                progressDialog.setMessage("下载新版本中...");
                                progressDialog.show();
                                if (progressDialog.getProgress() != 0) {
                                    progressDialog.setProgress(0);//防止下载到中途却卡住无法再进行下载
                                    return;
                                }
                                downloadApk(downloadUrl);
                            }

                            @Override
                            public void onCancelClick() {

                            }
                        }).build().show();
            }
        }
    }

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

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

            @Override
            public void onDownloadEnd(File file) {
                progressDialog.setProgress(0); //防止下载完成却卡住的情况
                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");
        requireContext().startActivity(intent);
    }

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

    @Override
    public void onDestroyView() {
        loginOutPresenter.disposeRetrofitRequest();
        updatePresenter.disposeRetrofitRequest();
        super.onDestroyView();
    }
}