package com.unis.sxzcl.ui.user;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.unis.sxzcl.R;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.databinding.FragmentVersionBinding;
import com.unis.sxzcl.util.VersionCheckTool;
import com.unis.sxzcl.widget.dialog.SystemDialog;
import com.xyxsbj.mylibrary.tool.VersionTool;

/**
 * 版本页面
 * 创建人: mQ
 * 创建时间: 2021/1/12 11:06
 */
public class VersionFragment extends BaseFragment<FragmentVersionBinding> {


    private VersionCheckTool mVersionCheckTool;
    private SystemDialog mNewestDialog;

    @Override
    protected FragmentVersionBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentVersionBinding.inflate(inflater, container, false);
    }

    @Override
    protected void init() {
        mBinding.bar.setLeftClickListener(v -> onBack());

        mBinding.tvRecord.setOnClickListener(v -> {
            // 查看版本记录
            navigation(R.id.versionRecordFragment);
        });
        mBinding.btnCheck.setOnClickListener(v -> {
            // 检查版本更新
            checkVersion();
        });
    }

    @Override
    protected void onFirstShow() {
        // 展示本地版本名称
        String versionName = VersionTool.getVersionName(getContext());
        mBinding.tvVersionName.setText("v" + versionName);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mVersionCheckTool != null)
            mVersionCheckTool.destroy();
        mVersionCheckTool = null;
    }

    /**
     * 检查版本更新
     */
    private void checkVersion() {
        showProgress("正在检查更新...", false);
        if (mVersionCheckTool == null)
            mVersionCheckTool = new VersionCheckTool(getContext());
        mVersionCheckTool.setUpdateCallback((data, newest) -> {
            if (!isActive()) return;
            hideProgress();
            if (!newest) {
                // 需要更新
                mVersionCheckTool.showUpdateDialog(data.get(0));
            } else {
                // 已是最新版本
                if (mNewestDialog == null)
                    mNewestDialog = new SystemDialog(getContext())
                            .setTitle("v" + data.get(0).getVersionName())
                            .setMsg("当前已是最新版本")
                            .setLeftButton("取消", null)
                            .setRightButton("确认", null);
                mNewestDialog.show();
            }
        }).setError(error -> {
            if (!isActive()) return;
            hideProgress();
        }).start();
    }


}
