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.unis.model.DataCallback;
import com.unis.model.UserModel;
import com.unis.model.bean.user.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.unis.sxzcl.util.VersionCheckTool;
import com.unis.sxzcl.widget.dialog.SystemDialog;
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;
    private VersionCheckTool mVersionCheckTool;
    private SystemDialog mNewestDialog;

    @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 -> {
            // 跳转版本信息页面
            navigation(R.id.versionFragment);
        });
        mBinding.btnLoginOut.setOnClickListener(v -> {
            //退出登录
            new SystemDialog(getContext()).setMsg("是否退出登录？")
                    .setHideTitle()
                    .setHideClose()
                    .setLeftButton("取消", null)
                    .setRightButton("退出", dialog -> {
                        dialog.dismiss();
                        logout();
                    }).show();
        });
        mBinding.layoutTextSize.setOnClickListener(v -> {
            //字体大小设置
            navigation(R.id.textSizeFragment);
        });
    }

    @Override
    protected void onFirstShow() {
        // 加载本地版本 小红点提示版本更新
        loadVersion();

        //展示用户信息
        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.getDepotName());
        mBinding.tvDepartment.setText(mUser.getDepartmentName());
        mBinding.tvPost.setText(mUser.getPpost());
    }

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

        // 检测版本更新
        mVersionCheckTool = new VersionCheckTool(getContext())
                .setUpdateCallback((data, newest) -> {
                    // 需要版本更新时显示小红点
                    mBinding.versionFlag.setVisibility(newest ? View.GONE : View.VISIBLE);
                }).start();
    }

    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() {
        showProgress("正在退出登录...", false);
        UserModel.get().logout(new DataCallback<String>() {
            @Override
            public void onSuccess(String data) {
                // 通知首页退出登录
                if (isActive()) {
                    hideProgress();
                }
                EventBus.getDefault().post(new LoginOutEvent());
            }

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

    /**
     * 上传图片
     */
    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();
            }
        });
    }


}
