package com.unis.sxzcl.ui.home;

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

import com.bumptech.glide.Glide;
import com.unis.model.AnnounceModel;
import com.unis.model.BasicModel;
import com.unis.model.DataCallback;
import com.unis.model.NoticeModel;
import com.unis.model.ProcessModel;
import com.unis.model.UrlPath;
import com.unis.model.UserModel;
import com.unis.model.bean.AnnounceBean;
import com.unis.model.bean.MultiDepotBean;
import com.unis.model.bean.user.UserBean;
import com.unis.model.event.TodoEvent;
import com.unis.sxzcl.R;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.databinding.FragmentHomeBinding;
import com.unis.sxzcl.ui.company.CompanyStatsFragment;
import com.unis.sxzcl.widget.banner.BannerUtils;
import com.unis.sxzcl.widget.banner.TopLineAdapter;
import com.youth.banner.Banner;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 包名: com.unis.sxzcl.ui.home
 * 类名: HomeFragment
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/12/2 19:55
 * 更新人:
 * 更新时间: 2020/12/2 19:55
 * 更新说明:
 * 版本号: 1.0
 */
public class HomeFragment extends BaseFragment<FragmentHomeBinding> {

    private CompanyStatsFragment mCompanyStatsFragment;

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

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        mBinding.vStatus.setHeight(getStatusHeight());

        initRefreshView(mBinding.refreshLayout, () -> {
            // 刷新首页
            getData();

            // 刷新企业统计
            if (mCompanyStatsFragment != null)
                mCompanyStatsFragment.getStatus();
        });

        mBinding.ivNotice.setOnClickListener(v -> {
            // 通知
            navigation(R.id.noticeListFragment);
        });
        mBinding.ivTodo.setOnClickListener(v -> {
            // 待办
            Bundle bundle = new Bundle();
            bundle.putInt("tabIndex", 1);
            navigation(R.id.todoHomeFragment, bundle);
        });
        mBinding.ivUser.setOnClickListener(v -> {
            // 个人信息
            navigation(R.id.userFragment);
        });

        // 初始化轮播图
        initBanner();

        // 初始化企业统计
        initCompanyStats();

    }

    /**
     * 初始化企业统计
     */
    private void initCompanyStats() {
        // 将登录人的库传给 统计页 加入Fragment中
        UserBean user = UserModel.get().getUser();
        MultiDepotBean depotBean = new MultiDepotBean();
        depotBean.depotName = user.getDepotName();
        depotBean.depotCode = user.getDepotId();

        Bundle bundle = new Bundle();
        bundle.putString("depot", getGson().toJson(depotBean));
        mCompanyStatsFragment = new CompanyStatsFragment();
        mCompanyStatsFragment.setArguments(bundle);
        getChildFragmentManager().beginTransaction()
                .replace(R.id.layout_company_status, mCompanyStatsFragment)
                .commit();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onFirstShow() {

        getData();
    }


    // 获取数据
    private void getData() {

        // 获取字典缓存
        BasicModel.get().getDepotDic();
        BasicModel.get().getDepartmentDic();
        BasicModel.get().getHouseDic();
        BasicModel.get().getPersonDic();
        BasicModel.get().getEnumDic();

        // 待办信息
        getTodoCount();
        // 通知信息
        getNoticeCount();
        // 公告信息
        getAnnounceList();
        // 用户信息
        getUserInfo();
    }


    /**
     * 初始化轮播图
     */
    private void initBanner() {
        List<Integer> list = new ArrayList<>();
        list.add(R.drawable.ic_banner1);
        list.add(R.drawable.ic_banner1);
        list.add(R.drawable.ic_banner1);
        BannerUtils mBannerUtils = new BannerUtils(mBinding.banner);
        mBannerUtils.setImagesResId(list);
    }

    /**
     * 收到消息 刷新待办数量
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTodoEvent(TodoEvent event) {
        getTodoCount();
    }

    /**
     * 获取待办数量
     */
    private void getTodoCount() {
        ProcessModel.get().getTodoCount(new DataCallback<Integer>() {
            @Override
            public void onSuccess(Integer data) {
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);

                if ((int) data == 0) {
                    mBinding.tvTodoCount.setVisibility(View.GONE);
                    return;
                }
                mBinding.tvTodoCount.setVisibility(View.VISIBLE);
                if (data > 99)
                    mBinding.tvTodoCount.setText("99");
                else
                    mBinding.tvTodoCount.setText(data + "");
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * 获取通知数量
     */
    private void getNoticeCount() {
        NoticeModel.get().getNoticeCount(new DataCallback<Integer>() {
            @Override
            public void onSuccess(Integer data) {
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);

                if ((int) data == 0) {
                    mBinding.tvNoticeCount.setVisibility(View.GONE);
                    return;
                }
                mBinding.tvNoticeCount.setVisibility(View.VISIBLE);
                mBinding.tvNoticeCount.setText(data + "");
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * 获取公告列表
     * 获取第一页的公告进行轮播
     */
    private void getAnnounceList() {
        AnnounceModel.get().getList(1, new DataCallback<List<AnnounceBean>>() {
            @Override
            public void onSuccess(List<AnnounceBean> data) {
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);

                if (data.size() == 0) return;

                //  展示公告轮播
                mBinding.announceBanner.setAdapter(new TopLineAdapter(data))
                        .isAutoLoop(true)
                        .setOrientation(Banner.VERTICAL)
                        .setUserInputEnabled(false)
//                .setLoopTime(2000)
                        .setPageTransformer(new ZoomOutPageTransformer())
                        .setOnBannerListener((item, position) -> {
                            // 公告
                            navigation(R.id.announceListFragment);
                        })
                ;
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * 收到消息 刷新用户信息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserEvent(UserBean event) {
        getUserInfo();
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        UserModel.get().refreshUser(new DataCallback<UserBean>() {
            @Override
            public void onSuccess(UserBean user) {
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);

                Glide.with(getContext())
                        .load(UrlPath.image_host + user.getPheadPortrait())
                        .placeholder(R.drawable.ic_img_loading)
                        .error(R.drawable.ic_user_empty)
                        .into(mBinding.ivUser);
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);
            }
        });
    }


}
