package com.casic.dcms.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 androidx.core.content.FileProvider;
import androidx.core.content.res.ResourcesCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.BuildConfig;
import com.casic.dcms.R;
import com.casic.dcms.databinding.FragmentMineBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.NewVersionBean;
import com.casic.dcms.model.UserBean;
import com.casic.dcms.utils.AuthenticationHelper;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.view.ChangePasswordActivity;
import com.casic.dcms.view.HelpfulActivity;
import com.casic.dcms.view.LoginActivity;
import com.casic.dcms.vm.UserViewModel;
import com.casic.dcms.vm.VersionViewModel;
import com.pengxh.androidx.lite.base.AndroidxBaseFragment;
import com.pengxh.androidx.lite.callback.OnDownloadListener;
import com.pengxh.androidx.lite.hub.ContextHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.PageNavigationManager;
import com.pengxh.androidx.lite.vm.LoadState;
import com.pengxh.androidx.lite.widget.dialog.AlertControlDialog;

import java.io.File;

public class MinePageFragment extends AndroidxBaseFragment<FragmentMineBinding> {

    private UserBean.DataBean userData;
    private ClipboardManager clipboardManager;
    private UserViewModel userViewModel;
    private VersionViewModel versionViewModel;
    private ProgressDialog progressDialog;

    @Override
    protected void setupTopBarLayout() {

    }

    @Override
    protected void initData() {
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        versionViewModel = new ViewModelProvider(this).get(VersionViewModel.class);

        clipboardManager = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE);

        viewBinding.deviceIdView.setText(ContextHub.getSimCardSerialNumber(requireContext()));
        viewBinding.versionCodeView.setText(BuildConfig.VERSION_NAME);

        //下载进度条
        progressDialog = new ProgressDialog(requireContext());
        progressDialog.setMessage("下载新版本中...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgressDrawable(ResourcesCompat.getDrawable(requireContext().getResources(), R.drawable.bg_progress, null));
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    protected void initEvent() {
        viewBinding.updateUserButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogHelper.showLoadingDialog(requireActivity(), "同步中，请稍后...");
                userViewModel.getUserData();
            }
        });
        userViewModel.userDataResult.observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean it) {
                if (it.getCode() == 200) {
                    DialogHelper.dismissLoadingDialog();
                    StringHub.show(requireContext(), "同步完成");
                    userData = it.getData();
                    updateUserInfo();
                }
            }
        });

        viewBinding.passwordLayout.setOnClickListener(v -> startActivity(new Intent(requireContext(), ChangePasswordActivity.class)));
        viewBinding.helpfulLayout.setOnClickListener(v -> startActivity(new Intent(requireContext(), HelpfulActivity.class)));
        viewBinding.copyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipData clipData = ClipData.newPlainText("deviceId", viewBinding.deviceIdView.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                StringHub.show(requireContext(), "复制成功");
            }
        });
        viewBinding.updateVersionView.setOnClickListener(v -> versionViewModel.update());
        versionViewModel.versionModel.observe(this, new Observer<NewVersionBean>() {
            @Override
            public void onChanged(NewVersionBean resultBean) {
                if (resultBean.getCode() == 200) {
                    NewVersionBean.DataBean data = resultBean.getData();
                    String version = data.getVersion();
                    if (BuildConfig.VERSION_NAME.equals(version)) {
                        StringHub.show(requireContext(), "暂无新版本，无需更新");
                    } else {
                        String downloadUrl = StringHelper.appendDownloadUrl(data.getDownloadUrl());
                        //http://111.198.10.15:11409/static/app/v1.1.0.0.apk
                        new AlertControlDialog.Builder()
                                .setContext(requireContext())
                                .setTitle("版本更新")
                                .setMessage("确定下载新版本吗？")
                                .setNegativeButton("取消")
                                .setPositiveButton("确定")
                                .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                                    @Override
                                    public void onConfirmClick() {
                                        //下载新版本
                                        progressDialog.show();
                                        downloadApk(downloadUrl);
                                    }

                                    @Override
                                    public void onCancelClick() {

                                    }
                                }).build().show();
                    }
                }
            }
        });
        versionViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(requireContext(), "请求中，请稍后");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

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

                            @Override
                            public void onCancelClick() {

                            }
                        }).build().show();
            }
        });
        userViewModel.loginOutResult.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean actionResultBean) {
                AuthenticationHelper.removeToken();
                ContextHub.navigatePageTo(requireContext(), LoginActivity.class);
                PageNavigationManager.finishAllActivity();
            }
        });
    }

    @Override
    public void onResume() {
        userData = StringHelper.getUserBean();
        updateUserInfo();
        super.onResume();
    }

    private void updateUserInfo() {
        //设置头像，圆形，暂时是默认的
//        val roundDrawable =
//            BitmapFactory.decodeResource(requireContext().resources, R.mipmap.login_casic)
//                .createRoundDrawable(
//                    requireContext(),
//                    3f.dp2px(requireContext()),
//                    R.color.mainThemeColor.convertColor(requireContext())
//                )
//        userImageView.setImageDrawable(roundDrawable)
        viewBinding.userNameView.setText(userData.getName());
        viewBinding.userPhoneView.setText("电话：" + userData.getPhone());
        viewBinding.userDeptView.setText("部门：" + userData.getDeptName());
    }

    //下载apk
    private void downloadApk(String url) {
        StringHub.downloadFile(url, ContextHub.createDownloadFileDir(requireContext()).toString(), new OnDownloadListener() {
            @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(requireContext(), LocaleConstant.APP_AUTHORITY, 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);
    }
}