package com.unis.sxzcl.ui.grain_check;

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

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.unis.model.BasicModel;
import com.unis.model.DataCallback;
import com.unis.model.DepotModel;
import com.unis.model.GrainCheckModel;
import com.unis.model.HouseModel;
import com.unis.model.PermitConst;
import com.unis.model.ProcessModel;
import com.unis.model.UserModel;
import com.unis.model.bean.EnumBean;
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.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 {


    private List<String> mTabs;
    private List<Fragment> mFragments;
    private SystemDialog mSystemDialog;

    private SelectHouseDialog mHouseDialog;
    private List<EnumBean> mEnumList;

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

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


    }

    private void initFragment() {
        mTabs = new ArrayList<>();
        mFragments = new ArrayList<>();

        for (EnumBean bean : mEnumList) {
            mTabs.add(bean.getEnumName());
            mFragments.add(GrainCheckListFragment.newFragment(getGson().toJson(bean)));
        }
    }

    @Override
    protected void onFirstShow() {

        mEnumList = BasicModel.get().getEnumList("18");
        if (mEnumList == null) {
            ToastTool.showLong("没有粮情检查类型");
            return;
        }

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

        // 有新增权限
        mBinding.bar.setRightVisible(UserModel.get().containPermit(PermitConst.grain_check_add_bgy));

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

    }

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

    /**
     * 新增
     */
    private void goAdd() {
        int currentItem = mBinding.viewPager.getCurrentItem();
        EnumBean enumBean = mEnumList.get(currentItem);
        if (enumBean.getEnumId().equals("19")) {
            // 保管员新增
            Bundle bundle = new Bundle();
            bundle.putString("enumBean", getGson().toJson(enumBean));
            bundle.putString("pageType", "add");
            navigation(R.id.grainCheckDetailFragment, bundle);
        } else {
            showAddDialog(enumBean);
        }
    }

    private void showAddDialog(EnumBean enumBean) {
        if (mSystemDialog == null)
            mSystemDialog = new SystemDialog(getContext())
                    .setCancelable(false)
                    .setLeftButton("取消", null);
        mSystemDialog
                .setTitle("新增")
                .setMsg("新增" + enumBean.getEnumName() + "？")
                .setRightButton("确定", dialog -> {
                    dialog.dismiss();
                    showProgress("正在新增...", false);
                    GrainCheckBean bean = new GrainCheckBean();
                    bean.anomalousStatus = "0";// 异常状态(0无异常，1有异常)
                    bean.checkPerson = UserModel.get().getUser().getUid();// 用户id(检查人)
                    bean.checkYearWeek = DateTool.getWeekOfYear(new Date());// 检查所在年第几周(一周:周一0:00至周日24:00)
                    bean.depotId = DepotModel.get().getSelectDepot().depotCode;// 库id
                    bean.enumId = enumBean.getEnumId();// 检查类型
                    bean.enumOrder = enumBean.getEnumOrder();// 用于同公共枚举同步顺序
                    bean.houseId = HouseModel.get().getSelectHouse().houseCode;// 仓房id
                    bean.operationTime = DateTool.formatDate(new Date(), DateTool.FULL_DATE);// 时间
                    bean.recordStatus = "1";// 记录状态(0进行中，1完成)

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

                        }

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

                    // 处理待办状态
                    ProcessModel.get().setTodo(bean.houseId, enumBean.getEnumId(), "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) {

        /**
         * 登录人是否可以新增
         * 每个页面所需角色不同
         * 页面角色和登录角色一致时 才可以新增
         */
        boolean isShow = false;
        switch (position) {
            case 0:
                // 保管员
                isShow = UserModel.get().containPermit(PermitConst.grain_check_add_bgy);
                break;
            case 1:
                //主管科长
                isShow = UserModel.get().containPermit(PermitConst.grain_check_add_zgkz);
                break;
            case 2:
                //分管副总
                isShow = UserModel.get().containPermit(PermitConst.grain_check_add_fgfz);
                break;
            case 3:
                //总经理
                isShow = UserModel.get().containPermit(PermitConst.grain_check_add_zjl);
                break;
        }
        mBinding.bar.setRightVisible(isShow);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    // 获取角色所在页面
    public int getRoleCurrentPage() {
        if (UserModel.get().isUserRole(RoleType.R_BGY))
            return 0;
        if (UserModel.get().isUserRole(RoleType.R_KZ))
            return 1;
        if (UserModel.get().isUserRole(RoleType.R_FZJL))
            return 2;
        if (UserModel.get().isUserRole(RoleType.R_ZJL))
            return 3;
        return 0;
    }
}