package com.unis.sxzcl.ui.home;

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

import com.bumptech.glide.Glide;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieEntry;
import com.unis.model.AnnounceModel;
import com.unis.model.DataCallback;
import com.unis.model.DepotModel;
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.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.widget.MyBarChart;
import com.unis.sxzcl.widget.MyPieChart;
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.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 包名: 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 MyPieChart mPieChartHouseStatus;
    private MyBarChart mBarChartFoodType;
    private MyPieChart mPieChartStorageStatus;

    @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, this::getData);

        mBinding.ivNotice.setOnClickListener(v -> {
            // 通知
            navigation(R.id.noticeListFragment);
        });
        mBinding.ivTodo.setOnClickListener(v -> {
            // 待办
            navigation(R.id.todoHomeFragment);
        });
        mBinding.ivUser.setOnClickListener(v -> {
            // 个人信息
            navigation(R.id.userFragment);
        });
//        mBinding.tvDepotCount.setOnClickListener(v -> {
//            // 库列表
//            navigation(R.id.companyListFragment);
//        });
//        mBinding.tvHouseCount.setOnClickListener(v -> {
//            // 仓列表
//            Bundle bundle = new Bundle();
//            bundle.putBoolean("showTitle", true);
//            navigation(R.id.houseListFragment, bundle);
//        });
//        mBinding.tvPersonCount.setOnClickListener(v -> {
//            // 人员列表
//            Bundle bundle = new Bundle();
//            bundle.putBoolean("showTitle", true);
//            navigation(R.id.personListFragment, bundle);
//        });

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

    }

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

    @Override
    protected void onFirstShow() {
        if (mPieChartHouseStatus == null) {
            mPieChartHouseStatus = new MyPieChart(mBinding.pieHouseStatus);
        }

        if (mBarChartFoodType == null) {
            mBarChartFoodType = new MyBarChart(mBinding.barFoodType);
        }

        if (mPieChartStorageStatus == null) {
            mPieChartStorageStatus = new MyPieChart(mBinding.pieStorageStatus);
        }

        getData();
    }


    // 获取数据
    private void getData() {
        getHouseStatus();
        getFoodType();
        getStorageStatus();

        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);
    }

    /**
     * 仓房状态饼图
     */
    private void getHouseStatus() {

        UserBean user = UserModel.get().getUser();
        if (user == null) return;
        String depotId = user.getDepotId();
        if (depotId == null) return;
        // 请求后台接口
        DepotModel.get().getWarehouseStatus(Integer.parseInt(depotId), new DataCallback<List<Map<String, Object>>>() {
            @Override
            public void onSuccess(List<Map<String, Object>> data) {
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);

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

                // 将数据源 转为 饼图数据
                List<PieEntry> pieEntries = new ArrayList<>();
                for (Map<String, Object> item : data) {
                    String count = (String) item.get("count");
                    String status = (String) item.get("warehouseStatus");
                    if (count == null) count = "0";
                    if (status == null) status = "";
                    pieEntries.add(new PieEntry(Float.parseFloat(count), status));
                }
                List<Integer> list = Arrays.asList(
                        Color.parseColor("#FFA100"),
                        Color.parseColor("#1FA2EB"),
                        Color.parseColor("#F3DE38"),
                        Color.parseColor("#89BF6B"));
                // 显示饼图
                mPieChartHouseStatus.showChart(pieEntries, "仓房状态", list);
            }

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

    /**
     * 粮食品种柱状图
     */
    private void getFoodType() {
        UserBean user = UserModel.get().getUser();
        if (user == null) return;
        String depotId = user.getDepotId();
        if (depotId == null) return;
        DepotModel.get().getFoodTypeCount(Integer.parseInt(depotId), new DataCallback<List<Map<String, Object>>>() {
            @Override
            public void onSuccess(List<Map<String, Object>> data) {
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);

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

                // 将数据源 转为 饼图数据
                List<String> labelList = new ArrayList<>();
                ArrayList<BarEntry> valueList = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    Map<String, Object> item = data.get(i);

                    String label = (String) item.get("grainVarieties");
                    if (label == null) label = "";
                    labelList.add(label);

                    String count = (String) item.get("count");
                    if (count == null) count = "0";
                    valueList.add(new BarEntry(i, Float.parseFloat(count)));

                }
                mBarChartFoodType.showChart(labelList, valueList);
            }

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

    }

    /**
     * 存储状态饼图
     */
    private void getStorageStatus() {

        UserBean user = UserModel.get().getUser();
        if (user == null) return;
        String depotId = user.getDepotId();
        if (depotId == null) return;
        // 请求后台接口
        DepotModel.get().getStorageStatus(Integer.parseInt(depotId), new DataCallback<List<Map<String, Object>>>() {
            @Override
            public void onSuccess(List<Map<String, Object>> data) {
                if (!isActive()) return;
                mBinding.refreshLayout.setRefreshing(false);

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

                // 将数据源 转为 饼图数据
                List<PieEntry> pieEntries = new ArrayList<>();
                for (Map<String, Object> item : data) {
                    String count = (String) item.get("count");
                    String status = (String) item.get("storageStatus");
                    if (count == null) count = "0";
                    if (status == null) status = "";
                    pieEntries.add(new PieEntry(Float.parseFloat(count), status));
                }
                List<Integer> list = Arrays.asList(
                        Color.parseColor("#057B43"),
                        Color.parseColor("#8ABF6B"),
                        Color.parseColor("#F3DE38"));
                // 显示饼图
                mPieChartStorageStatus.showChart(pieEntries, "储存状态", list);
            }

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


    /**
     * 收到消息 刷新待办数量
     *
     * @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);
                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);

                mBinding.tvCompany.setText(user.getDepotName());
                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);
            }
        });
    }


}
