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.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.core.content.res.ResourcesCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
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.service.UpdateLocationService;
import com.casic.dcms.utils.AuthenticationHelper;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.callback.ISelectorListener;
import com.casic.dcms.view.ChangePasswordActivity;
import com.casic.dcms.view.HelpfulActivity;
import com.casic.dcms.view.LoginActivity;
import com.casic.dcms.vm.UploadViewModel;
import com.casic.dcms.vm.UserViewModel;
import com.casic.dcms.vm.VersionViewModel;
import com.luck.picture.lib.entity.LocalMedia;
import com.pengxh.androidx.lite.base.AndroidxBaseFragment;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.ActivityStackManager;
import com.pengxh.androidx.lite.utils.FileDownloadManager;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.widget.dialog.AlertControlDialog;

import java.io.File;
import java.util.ArrayList;

public class MinePageFragment extends AndroidxBaseFragment<FragmentMineBinding> {

    private UserBean.DataBean user;
    private ClipboardManager clipboardManager;
    private UserViewModel userViewModel;
    private VersionViewModel versionViewModel;
    private UploadViewModel uploadViewModel;
    private ProgressDialog progressDialog;

    @Override
    protected void setupTopBarLayout() {

    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        userViewModel.userDataResult.observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean it) {
                if (it.getCode() == 200) {
                    user = it.getData();

                    getBinding().userNameView.setText(user.getName());
                    getBinding().userPhoneView.setText("电话：" + user.getPhone());
                    getBinding().userDeptView.setText("部门：" + user.getDeptName());
                }
            }
        });
        userViewModel.loginOutResult.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean actionResultBean) {
                requireActivity().stopService(new Intent(requireContext(), UpdateLocationService.class));
                AuthenticationHelper.removeToken();
                ContextKit.navigatePageTo(requireContext(), LoginActivity.class);
                ActivityStackManager.finishAllActivity();
            }
        });

        versionViewModel = new ViewModelProvider(this).get(VersionViewModel.class);
        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)) {
                        StringKit.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();
                    }
                }
            }
        });

        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    //更新用户信息表
                    userViewModel.updateUserInfo(requireContext(), user.getId(), user.getAccount(), user.getName(), user.getDeptId(), StringHelper.reformatURL(user.getRoleList()), resultBean.getData(), "", "", "");

                    Glide.with(requireContext()).load(StringHelper.appendCompleteURL(resultBean.getData())).apply(RequestOptions.circleCropTransform()).into(getBinding().userImageView);
                }
            }
        });

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

        getBinding().deviceIdView.setText(ContextKit.getSimCardSerialNumber(requireContext()));
        getBinding().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() {
        getBinding().updateUserButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userViewModel.getUserData(requireContext());
            }
        });

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

        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    StringKit.show(requireActivity(), "上传中，请稍后...");
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        getBinding().userImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelectorHelper.selectPicture(requireContext(), 1, new ISelectorListener() {
                    @Override
                    public void onSuccess(ArrayList<LocalMedia> result) {
                        uploadViewModel.uploadImage(requireContext(), new File(result.get(0).getRealPath()));
                    }
                });
            }
        });

        getBinding().passwordLayout.setOnClickListener(v -> startActivity(new Intent(requireContext(), ChangePasswordActivity.class)));
        getBinding().helpfulLayout.setOnClickListener(v -> startActivity(new Intent(requireContext(), HelpfulActivity.class)));
        getBinding().copyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipData clipData = ClipData.newPlainText("deviceId", getBinding().deviceIdView.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                StringKit.show(requireContext(), "复制成功");
            }
        });
        getBinding().updateVersionView.setOnClickListener(v -> versionViewModel.update(requireContext()));

        getBinding().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(requireContext());
                    }

                    @Override
                    public void onCancelClick() {

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

    @Override
    public void onResume() {
        super.onResume();
        userViewModel.getUserData(requireContext());
    }

    //下载apk
    private void downloadApk(String url) {
        new FileDownloadManager.Builder().setDownloadFileSource(url).setFileSuffix("apk").setFileSaveDirectory(ContextKit.createDownloadFileDir(requireContext())).setOnFileDownloadListener(new FileDownloadManager.OnFileDownloadListener() {
            @Override
            public void onProgressChanged(long progress) {
                progressDialog.setProgress((int) progress);
            }

            @Override
            public void onDownloadEnd(File file) {
                progressDialog.setProgress(0); //防止下载完成却卡住的情况
                progressDialog.dismiss();
                installApk(file);
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        }).build().start();
    }

    //安装apk文件
    private void installApk(File apk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        // 通过FileProvider创建一个content类型的Uri
        data = FileProvider.getUriForFile(requireContext(), LocaleConstant.APP_AUTHORITY, apk);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 给目标应用一个临时授权
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        requireContext().startActivity(intent);
    }
}