package com.unis.sxzcl.ui.grain_check;

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

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.unis.model.DataCallback;
import com.unis.model.DepotModel;
import com.unis.model.GrainCheckModel;
import com.unis.model.HouseModel;
import com.unis.model.ProcessModel;
import com.unis.model.UserModel;
import com.unis.model.bean.HouseListBean;
import com.unis.model.bean.MultiDepotBean;
import com.unis.model.bean.grain_check.GrainCheckBean;
import com.unis.model.bean.user.RoleType;
import com.unis.model.event.GrainCheckEvent;
import com.unis.sxzcl.R;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.databinding.FragmentBaseTabPagerBinding;
import com.unis.sxzcl.ui.house.SelectHouseDialog;
import com.unis.sxzcl.widget.TabFragmentPagerAdapter;
import com.unis.sxzcl.widget.dialog.SystemDialog;
import com.xyxsbj.mylibrary.tool.DateTool;
import com.xyxsbj.mylibrary.tool.ToastTool;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 包名: com.unis.sxzcl.ui.grain_check
 * 类名: GrainCheckFragment
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/12/10 17:52
 * 更新人:
 * 更新时间: 2020/12/10 17:52
 * 更新说明:
 * 版本号: 1.0
 */
public class GrainCheckHomeFragment extends BaseFragment<FragmentBaseTabPagerBinding> implements ViewPager.OnPageChangeListener {

    public static final String BGY = "保管员每周检查粮情";
    public static final String KZ = "主管科长每2周检查粮情";
    public static final String FZJL = "分管副总每月检查粮情";
    public static final String ZJL = "总经理每季检查粮情";

    private List<String> mTabs = Arrays.asList(BGY, KZ, FZJL, ZJL);
    private List<Fragment> mFragments;
    private SystemDialog mSystemDialog;

    private SelectHouseDialog mHouseDialog;
    private String mRoleIds;

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

    @Override
    protected void init() {
        HouseListBean house = HouseModel.get().getSelectHouse();
        if (house == null) {
            ToastTool.showLong("未选择仓房");
            onBack();
            return;
        }
        // 获取登录人角色
        if (mRoleIds == null)
            mRoleIds = UserModel.get().getUser().getRoleIds();

        mBinding.bar.setTitle("粮情检查(" + house.houseName + ")")
                .setTitleRightDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_down_white))
                .setTitleClickListener(v -> {
                    // 点击标题选择仓房
                    showHouseSelect();
                })
                .setLeftClickListener(v -> onBack())
                .setRightText("新增").setRightClickListener(v -> goAdd());

        initFragment();
        mBinding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mBinding.tabLayout.setupWithViewPager(mBinding.viewPager);
        TabFragmentPagerAdapter adapter = new TabFragmentPagerAdapter(
                getChildFragmentManager(), mTabs, mFragments);
        mBinding.viewPager.setAdapter(adapter);
        mBinding.viewPager.setOffscreenPageLimit(mFragments.size());
        mBinding.viewPager.addOnPageChangeListener(this);
    }

    private void initFragment() {
        mFragments = new ArrayList<>();
        for (String tab : mTabs) {
            mFragments.add(GrainCheckListFragment.newFragment(tab));
        }
    }

    @Override
    protected void onFirstShow() {

        // 保管员显示新增
        if (mRoleIds == null) mRoleIds = UserModel.get().getUser().getRoleIds();
        mBinding.bar.setRightVisible(mRoleIds.equals(RoleType.R_BGY));

        // 切换到用户角色所在的页面
        mBinding.viewPager.setCurrentItem(getRoleCurrentPage());

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ProcessModel.get().removeSelectTodo();
    }

    /**
     * 新增
     */
    private void goAdd() {
        String tab = mTabs.get(mBinding.viewPager.getCurrentItem());
        if (tab.equals(BGY)) {
            // 保管员新增
            Bundle bundle = new Bundle();
            bundle.putString("tab", tab);
            bundle.putString("pageType", "add");
            navigation(R.id.grainCheckDetailFragment, bundle);
        } else {
            showAddDialog(tab);
        }
    }

    private void showAddDialog(String tab) {
        if (mSystemDialog == null)
            mSystemDialog = new SystemDialog(getContext())
                    .setCancelable(false)
                    .setLeftButton("取消", null);
        mSystemDialog
                .setTitle("新增")
                .setMsg("新增" + tab + "？")
                .setRightButton("确定", dialog -> {
                    dialog.dismiss();
                    showProgress("正在新增...", false);
                    GrainCheckBean bean = new GrainCheckBean();
                    bean.recordStatus = "1";
                    bean.checkPerson = tab;
                    bean.checkTime = DateTool.formatDate(new Date(), DateTool.YTDTD_DATE);
                    bean.grainAbnormalDescribe = null;
                    bean.uid = UserModel.get().getUser().getUid();
                    String depotCode = DepotModel.get().getSelectDepot().depotCode;
                    bean.depotId = depotCode != null ? Integer.valueOf(depotCode) : null;
                    String houseCode = HouseModel.get().getSelectHouse().houseCode;
                    bean.houseId = houseCode != null ? Integer.valueOf(houseCode) : null;

                    GrainCheckModel.get().add(bean, new DataCallback<String>() {
                        @Override
                        public void onSuccess(String data) {
                            if (!isActive()) return;
                            hideProgress();
                            ToastTool.showLong("新增完成");
                            EventBus.getDefault().post(new GrainCheckEvent(tab));

                        }

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

                    // 处理待办状态
                    ProcessModel.get().setTodo(houseCode, tab, "4");
                }).show();
    }

    /**
     * 选择仓房
     */
    private void showHouseSelect() {
        MultiDepotBean depot = DepotModel.get().getSelectDepot();
        if (mHouseDialog == null)
            mHouseDialog = new SelectHouseDialog(getContext());
        // 监听仓房选择结果
        mHouseDialog.setCallback(bean -> {
            if (bean == null)
                return;
            mBinding.bar.setTitle("粮情检查(" + bean.houseName + ")");
            EventBus.getDefault().post(new GrainCheckEvent(null));
        });
        // 弹出仓房选择对话框
        mHouseDialog.show(depot.depotCode, -1);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        switch (position) {
            case 0:
                // 保管员
                mBinding.bar.setRightVisible(mRoleIds.equals(RoleType.R_BGY));
                break;
            case 1:
                //科长
                mBinding.bar.setRightVisible(mRoleIds.equals(RoleType.R_KZ));
                break;
            case 2:
                //副总经理
                mBinding.bar.setRightVisible(mRoleIds.equals(RoleType.R_FZJL));
                break;
            case 3:
                //总经理
                mBinding.bar.setRightVisible(mRoleIds.equals(RoleType.R_ZJL));
                break;
        }
        mBinding.bar.setRightVisible(isAdd(position));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 登录人是否可以新增
     * 每个页面所需角色不同
     * 页面角色和登录角色一致时 才可以新增
     */
    public boolean isAdd(int index) {
        if (mRoleIds == null)
            return false;

        boolean add = false;
        switch (index) {
            case 0:
                // 保管员
                add = mRoleIds.equals(RoleType.R_BGY);
                break;
            case 1:
                //科长
                add = mRoleIds.equals(RoleType.R_KZ);
                break;
            case 2:
                //副总经理
                add = mRoleIds.equals(RoleType.R_FZJL);
                break;
            case 3:
                //总经理
                add = mRoleIds.equals(RoleType.R_ZJL);
                break;
        }
        return add;
    }

    // 获取角色所在页面
    public int getRoleCurrentPage() {
        if (mRoleIds == null)
            return 0;

        switch (mRoleIds) {
            case RoleType.R_BGY:
                return 0;
            case RoleType.R_KZ:
                return 1;
            case RoleType.R_FZJL:
                return 2;
            case RoleType.R_ZJL:
                return 3;
        }
        return 0;
    }
}