package com.unis.sxzcl.ui.user;

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

import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.android.material.snackbar.Snackbar;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.unis.model.DataCallback;
import com.unis.model.UserModel;
import com.unis.model.bean.UserBean;
import com.unis.model.event.LoginOutEvent;
import com.unis.sxzcl.R;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.databinding.FragmentUserBinding;
import com.unis.sxzcl.util.MyCompressHelper;
import com.xyxsbj.mylibrary.tool.ToastTool;
import com.xyxsbj.mylibrary.tool.VersionTool;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.api.widget.Widget;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.unis.model.UrlPath.image_host;

/**
 * 包名: com.unis.sxzcl.ui.user
 * 类名: UserFragment
 * 作用描述: 个人信息
 * 创建人: mQ
 * 创建时间: 2020/11/24 19:31
 * 更新人:
 * 更新时间: 2020/11/24 19:31
 * 更新说明:
 * 版本号: 1.0
 */
public class UserFragment extends BaseFragment<FragmentUserBinding> {

    private UserBean mUser;

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

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

        mBinding.layoutHead.setOnClickListener(v -> {
            // 头像
            addUserImg();
        });
//        mBinding.layoutName.setOnClickListener(v -> {
//            //姓名
//        });
        mBinding.layoutVersion.setOnClickListener(v -> {
            Beta.checkUpgrade(true, false);
            // 获取升级信息
            UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
            if (upgradeInfo == null) {
                Snackbar.make(mBinding.layoutVersion, "已是最新版本", Snackbar.LENGTH_LONG)
                        .setAction("确定", v1 -> {
                        })
                        .show();
            }
        });
        mBinding.btnLoginOut.setOnClickListener(v -> {
            //退出登录
            logout();
        });
        mBinding.layoutTextSize.setOnClickListener(v -> {
            //字体大小设置
            navigation(R.id.textSizeFragment);
        });
    }

    @Override
    protected void onFirstShow() {
        loadUpdate();

        //展示用户信息
        mUser = UserModel.get().getUser();
        if (mUser == null) return;
        Glide.with(getContext())
                .load(image_host + mUser.getPheadPortrait())
                .placeholder(R.drawable.ic_img_loading)
                .error(R.drawable.ic_user_empty)
                .into(mBinding.ivHead);
        mBinding.tvLoginName.setText(mUser.getUname());
        mBinding.tvName.setText(mUser.getPersonnelName());
        mBinding.tvCompany.setText(mUser.getCompanyName());
        mBinding.tvDepartment.setText(mUser.getDepotName());
        mBinding.tvPost.setText(mUser.getPpost());
    }

    /**
     * 获取升级信息
     */
    private void loadUpdate() {
        // 展示本地版本名称
        String versionName = VersionTool.getVersionName(getContext());
        mBinding.tvVersion.setText("v" + versionName);

        // 获取升级信息
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
        if (upgradeInfo == null) {
            mBinding.versionFlag.setVisibility(View.GONE);
            return;
        }
//        StringBuilder info = new StringBuilder();
//        info.append("id: ").append(upgradeInfo.id).append("\n");
//        info.append("标题: ").append(upgradeInfo.title).append("\n");
//        info.append("升级说明: ").append(upgradeInfo.newFeature).append("\n");
//        info.append("versionCode: ").append(upgradeInfo.versionCode).append("\n");
//        info.append("versionName: ").append(upgradeInfo.versionName).append("\n");
//        info.append("发布时间: ").append(upgradeInfo.publishTime).append("\n");
//        info.append("安装包Md5: ").append(upgradeInfo.apkMd5).append("\n");
//        info.append("安装包下载地址: ").append(upgradeInfo.apkUrl).append("\n");
//        info.append("安装包大小: ").append(upgradeInfo.fileSize).append("\n");
//        info.append("弹窗间隔（ms）: ").append(upgradeInfo.popInterval).append("\n");
//        info.append("弹窗次数: ").append(upgradeInfo.popTimes).append("\n");
//        info.append("发布类型（0:测试 1:正式）: ").append(upgradeInfo.publishType).append("\n");
//        info.append("弹窗类型（1:建议 2:强制 3:手工）: ").append(upgradeInfo.upgradeType).append("\n");
//        info.append("图片地址：").append(upgradeInfo.imageUrl);

        mBinding.versionFlag.setVisibility(View.VISIBLE);
    }

    private void addUserImg() {
        Widget widget = Widget.newDarkBuilder(getContext())
                .title("选择头像")
                .toolBarColor(ContextCompat.getColor(getContext(), R.color.colorTheme))
                .statusBarColor(ContextCompat.getColor(getContext(), R.color.colorTheme))
                .build();
        Album.image(this)
                .multipleChoice()
                .camera(true)
                .columnCount(2)
                .selectCount(1)
                .widget(widget)
                .onResult(result -> {
                    Glide.with(getContext())
                            .load(result.get(0).getThumbPath())
                            .centerCrop()
                            .placeholder(R.drawable.ic_img_loading)
                            .error(R.drawable.ic_user_empty)
                            .into(mBinding.ivHead);
                    //图片压缩
                    File newHead = MyCompressHelper.get(getContext()).compressToFile(new File(result.get(0).getPath()));
                    uploadImage(newHead);
                }).start();
    }

    /**
     * 退出登录
     */
    private void logout() {
        if (!isActive()) return;

        showProgress("正在退出登录...", false);
        UserModel.get().logout(new DataCallback<String>() {
            @Override
            public void onSuccess(String data) {
                // 通知首页退出登录
                EventBus.getDefault().post(new LoginOutEvent());

                if (!isActive()) return;
                hideProgress();
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                // 通知首页退出登录
                EventBus.getDefault().post(new LoginOutEvent());

                if (!isActive()) return;
                hideProgress();
            }
        });
    }

    /**
     * 上传图片
     */
    public void uploadImage(File file) {
        if (file == null) return;
        showProgress("正在上传图片...", false);
        UserModel.get().uploadFile(file, new DataCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (!isActive()) return;
                if (data != null) {
                    update(data);
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                hideProgress();
            }
        });
    }

    /**
     * 修改头像
     */
    public void update(String headImg) {
        Map<String, Object> map = new HashMap<>();
        map.put("pheadPortrait", headImg);
        map.put("pid", mUser.getPersonnelId());
        showProgress("正在修改信息...", false);
        UserModel.get().update(map, new DataCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (!isActive()) return;
                hideProgress();
                ToastTool.showLong("头像修改成功!");
                EventBus.getDefault().post(new UserBean());
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                hideProgress();
            }
        });
    }


}
