package com.zztrapp.zztrapp.ui.mine;

import static com.zztrapp.zztrapp.ui.MainActivity.mainActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.allenliu.versionchecklib.core.http.HttpHeaders;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.google.gson.Gson;
import com.zztrapp.zztrapp.R;
import com.zztrapp.zztrapp.bean.UpGradePackageBean;
import com.zztrapp.zztrapp.databinding.FragmentMineBinding;
import com.zztrapp.zztrapp.http.HttpApi;
import com.zztrapp.zztrapp.ui.mine.activity.AboutUsActivity;
import com.zztrapp.zztrapp.ui.mine.activity.LoginActivity;
import com.zztrapp.zztrapp.utilcode.util.AppUtils;
import com.zztrapp.zztrapp.utilcode.util.SPUtils;
import com.zztrapp.zztrapp.utilcode.util.ToastUtils;


/**
 * Describe 我的
 * Created by Bby on 2022/6/21
 * Email bby0856@163.com
 */
public class MineFragment extends Fragment {


    private FragmentMineBinding binding;
    private boolean isShowDialog = true;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    public MineFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMineBinding.inflate(inflater, container, false);
        init();
        initOnClick();
        return binding.getRoot();
    }

    private void init() {
        binding.username.setText(SPUtils.getInstance().getString("userName"));
        binding.parcelName.setText(SPUtils.getInstance().getString("realname"));
        binding.address.setText(SPUtils.getInstance().getString("address"));
        String appVersion = "V" + AppUtils.getAppVersionName();
        binding.appVersion.setText(appVersion);
    }

    private void initOnClick() {
        binding.signOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                logout();

                AlertDialog.Builder alertdialogbuilder = new AlertDialog.Builder(getActivity());
                alertdialogbuilder.setMessage("是否退出");
                alertdialogbuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        SPUtils.getInstance().clear();
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
                alertdialogbuilder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                final AlertDialog alertdialog1 = alertdialogbuilder.create();
                alertdialog1.show();
            }
        });
        binding.versionInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadVersionCheck();
            }
        });
        binding.aboutUs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
            }
        });
    }

    //检测版本升级
    public void loadVersionCheck() {
        HttpHeaders httpHeaders = new HttpHeaders();

        String authorization = SPUtils.getInstance().getString("authorization", "");
        httpHeaders.put("X-Access-Token", authorization);
        DownloadBuilder downloadBuilder = AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setHttpHeaders(httpHeaders)
                .setRequestUrl(HttpApi.BASE_URL + HttpApi.GET_APP_VERSION)
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(DownloadBuilder downloadBuilder, String result) {
                        if (!TextUtils.isEmpty(result)) {
                            Gson gson = new Gson();
                            UpGradePackageBean upGradePackageBean = gson.fromJson(result, UpGradePackageBean.class);
                            if (upGradePackageBean.getCode() == 200 && null != upGradePackageBean.getResult() && upGradePackageBean.getResult().getVersionCode() > AppUtils.getAppVersionCode()) {
                                if (upGradePackageBean.getResult().getUpType() == 2) {//升级类型（1普通升级，2强制升级）
                                    //动态在此设置是否强制更新等
                                    downloadBuilder.setForceUpdateListener(() -> {
                                        forceUpdate();
                                    });
                                }
                                //设置当前服务器最新的版本号，供库判断是否使用缓存
//                                downloadBuilder.setNewestVersionCode(upGradePackageBean.getData().getVersionCode());
                                UIData uiData = UIData.create();
                                uiData.setTitle(upGradePackageBean.getResult().getVersionName());
                                uiData.setDownloadUrl(upGradePackageBean.getResult().getDownloadUrl());
                                uiData.setContent(upGradePackageBean.getResult().getContent());
                                return uiData;
                            }
                            if (upGradePackageBean.getCode() == 200 && null != upGradePackageBean.getResult()) {
                                if (upGradePackageBean.getResult().getVersionCode() <= AppUtils.getAppVersionCode()) {
                                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(R.string.version_toast);
                                }
                            } else {
                                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(upGradePackageBean.getMessage());
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                });
        //下载忽略本地缓存
        downloadBuilder.setForceRedownload(true);
        downloadBuilder.executeMission(getContext());
    }

    /**
     * 强制更新操作
     * 通常关闭整个activity所有界面，这里方便测试直接关闭当前activity
     */
    private void forceUpdate() {
        mainActivity.finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}