package com.unis.sxzcl.ui.grain_check;

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

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.ProcessModel;
import com.unis.model.UserModel;
import com.unis.model.bean.EnumBean;
import com.unis.model.bean.detail.DetailItemBean;
import com.unis.model.bean.detail.DetailItemType;
import com.unis.model.bean.grain_check.GrainCheckBean;
import com.unis.model.bean.grain_check.GrainCheckChildBean;
import com.unis.model.bean.grain_check.GrainCheckDescribeBean;
import com.unis.model.event.GrainCheckEvent;
import com.unis.sxzcl.base.BaseListFragment;
import com.unis.sxzcl.databinding.FragmentGrainCheckAddBinding;
import com.xyxsbj.mylibrary.tool.DPTool;
import com.xyxsbj.mylibrary.tool.DateTool;
import com.xyxsbj.mylibrary.tool.LogTool;
import com.xyxsbj.mylibrary.tool.StringTool;
import com.xyxsbj.mylibrary.tool.ToastTool;

import org.greenrobot.eventbus.EventBus;

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

/**
 * 粮情检查 详情
 * 创建人: mQ
 * 时间: 2021/2/2 15:12
 */
public class GrainCheckDetailFragment extends BaseListFragment<FragmentGrainCheckAddBinding> implements GrainCheckDetailAdapter.ChangeCallback {


    private String mPageType;
    private GrainCheckDetailAdapter mAdapter;
    private GrainCheckBean mData;
    private List<GrainCheckChildBean> mChildList = new ArrayList<>();
    private GrainCheckDescribeBean mDescribeBean = new GrainCheckDescribeBean();
    private EnumBean mEnumBean;

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

    @Override
    protected void init() {
        Bundle bundle = getArguments();
        if (bundle == null) {
            ToastTool.showLong("没有参数");
            onBack();
            return;
        }
        String enumJson = bundle.getString("enumBean");
        mEnumBean = getGson().fromJson(enumJson, EnumBean.class);
        if (mEnumBean == null) {
            ToastTool.showLong("没有参数");
            onBack();
            return;
        }
        mBinding.bar.setTitle(mEnumBean.getEnumName());
        mBinding.bar.setLeftClickListener(v -> onBack());

        mPageType = bundle.getString("pageType", "add");
//        switch (mPageType) {
//            case "add":
//                // 新增
//                break;
//            case "edit":
//                // 修改
//                break;
//            case "detail":
//                // 详情
//                break;
//        }

        String dataJson = bundle.getString("data");
        mData = getGson().fromJson(dataJson, GrainCheckBean.class);

        mAdapter = new GrainCheckDetailAdapter();
        mAdapter.setPageType(mPageType);
        TextView view = new TextView(getContext());
        view.setHeight(DPTool.dp2px(getContext(), 200));
        mAdapter.setFooterView(view);
        mAdapter.setCallback(this);
        initBaseListView(mBinding.refreshLayout, mBinding.recyclerView, mAdapter, false);


        mBinding.tvSave.setVisibility(View.GONE);
        mBinding.tvSubmit.setVisibility(View.GONE);

        mBinding.tvSave.setOnClickListener(v -> {
            onSave();
        });
        mBinding.tvSubmit.setOnClickListener(v -> {
            onSave();
        });
    }

    @Override
    protected void onFirstShow() {

        onRefresh();

    }


    private DetailItemBean getItemById(String id) {
        for (DetailItemBean item : mAdapter.getData()) {
            if (item.getId() != null && item.getId().equals(id))
                return item;
        }
        return null;
    }

    @Override
    public void onRefreshData() {
        if (mAdapter.getData().size() > 0) {
            loadComplete();
            return;
        }

        if (mPageType.equals("add")) {
            // 新增从枚举拿到所有选项
            List<EnumBean> enumList = BasicModel.get().getEnumList("19");
            // 生成选项列表
            initData(enumList);
            loadComplete();
        } else {
            // 修改/详情 调用详情接口数据 生成列表
            showData();
        }


//        // 获取字典表数据
//        GrainCheckModel.get().getDictionaryList(new DataCallback<List<GrainCheckDictionaryBean>>() {
//            @Override
//            public void onSuccess(List<GrainCheckDictionaryBean> data) {
//                if (!isActive()) return;
//
//                //初始化所有选项
//                initData(data);
//
//                //回显详情数据
//                showData();
//
//                loadComplete();
//            }
//
//            @Override
//            public void onError(String error) {
//                super.onError(error);
//                if (!isActive()) return;
//                loadError();
//            }
//        });
    }

    /**
     * 初始化数据列表
     */
    private void initData(List<EnumBean> enumList) {
        // 增加选项
        for (int i = 0; i < enumList.size(); i++) {
            EnumBean bean = enumList.get(i);
            DetailItemBean item = new DetailItemBean(DetailItemType.radio)//项类型
                    .setFlowId(null)                 // 流程
                    .setId(bean.getEnumId())        // 枚举id
                    .setTitle(bean.getEnumName())   // 名称
                    .setIndex(i + 1)                // 序号
                    .setOption(new String[]{"是", "否"});// 选项数组
            // 加入列表中
            mAdapter.addData(item);
        }

        // 虫害情况 输入框
        DetailItemBean bean = getItemById("189");
        if (bean != null) {
            // 给虫害选项 绑定 输入框id
            bean.setChildIds(new String[]{"1", "2", "3", "4"});
            List<DetailItemBean> list = new ArrayList<>();
            list.add(new DetailItemBean(DetailItemType.input, "1", "1", "虫害密度").setShow(false).setMust(false));
            list.add(new DetailItemBean(DetailItemType.input, "2", "1", "发生部位").setShow(false).setMust(false));
            list.add(new DetailItemBean(DetailItemType.input, "3", "1", "虫害面积").setShow(false).setMust(false));
            list.add(new DetailItemBean(DetailItemType.input, "4", "1", "虫害种类").setShow(false).setMust(false));
            mAdapter.addData(mAdapter.getItemPosition(bean) + 1, list);
        }

        // 水检测是否正常
        bean = getItemById("190");
        if (bean != null) {
            bean.setChildIds(new String[]{"5"});
            DetailItemBean item = new DetailItemBean(DetailItemType.input, "5", "1", "水分异常描述")
                    .setShow(false)
                    .setMust(false);
            mAdapter.addData(mAdapter.getItemPosition(bean) + 1, item);
        }

        // 异常粮情
        bean = getItemById("191");
        if (bean != null) {
            bean.setChildIds(new String[]{"6"});
            DetailItemBean item = new DetailItemBean(DetailItemType.input, "6", "1", "异常粮情描述")
                    .setShow(false)
                    .setMust(false);
            mAdapter.addData(mAdapter.getItemPosition(bean) + 1, item);
        }
    }

    /**
     * 显示信息
     */
    private void showData() {
        if (mData == null)
            return;
        GrainCheckModel.get().getDetail(mData.id, new DataCallback<List<GrainCheckChildBean>>() {
            @Override
            public void onSuccess(List<GrainCheckChildBean> data) {
                for (int i = 0; i < data.size(); i++) {
                    GrainCheckChildBean childBean = data.get(i);
                    String select = null;
                    if (childBean.anomalousStatus != null)
                        select = childBean.anomalousStatus.equals("0") ? "1" : "0";

                    DetailItemBean item = new DetailItemBean(DetailItemType.radio)//项类型
                            .setFlowId(childBean.id)        // 流程
                            .setId(childBean.enumId)        // 枚举id
                            .setTitle(BasicModel.get().getEnumName(childBean.enumId))   // 名称
                            .setIndex(i + 1)                // 序号
                            .setSelectIndex(select)         // 选中项
                            .setTime(childBean.operationTime)// 选中时间
                            .setOption(new String[]{"是", "否"});// 选项数组
                    // 加入列表中
                    mAdapter.addData(item);
                    String errorDescribed = childBean.errorDescribed;
                    if (errorDescribed != null) {
                        mDescribeBean = getGson().fromJson(errorDescribed, GrainCheckDescribeBean.class);
                    }
                }

                // 虫害情况 输入框
                DetailItemBean bean = getItemById("189");
                if (bean != null) {
                    boolean show = bean.getSelectIndex() != null && bean.getSelectIndex().equals("0");
                    // 给虫害选项 绑定 输入框id
                    bean.setChildIds(new String[]{"1", "2", "3", "4"});
                    List<DetailItemBean> list = new ArrayList<>();
                    list.add(new DetailItemBean(DetailItemType.input, "1", "1", "虫害密度")
                            .setInputData(mDescribeBean.pestDensity)
                            .setShow(show)
                            .setMust(false));
                    list.add(new DetailItemBean(DetailItemType.input, "2", "1", "发生部位")
                            .setInputData(mDescribeBean.occurPosition)
                            .setShow(show)
                            .setMust(false));
                    list.add(new DetailItemBean(DetailItemType.input, "3", "1", "虫害面积")
                            .setInputData(mDescribeBean.occurArea)
                            .setShow(show)
                            .setMust(false));
                    list.add(new DetailItemBean(DetailItemType.input, "4", "1", "虫害种类")
                            .setInputData(mDescribeBean.pestType)
                            .setShow(show)
                            .setMust(false));
                    mAdapter.addData(mAdapter.getItemPosition(bean) + 1, list);
                }

                // 水检测是否正常
                bean = getItemById("190");
                if (bean != null) {
                    boolean show = bean.getSelectIndex() != null && bean.getSelectIndex().equals("0");
                    bean.setChildIds(new String[]{"5"});
                    DetailItemBean item = new DetailItemBean(DetailItemType.input, "5", "1", "水分异常描述")
                            .setInputData(mDescribeBean.abnormalWater)
                            .setShow(show)
                            .setMust(false);
                    mAdapter.addData(mAdapter.getItemPosition(bean) + 1, item);
                }

                // 异常粮情
                bean = getItemById("191");
                if (bean != null) {
                    boolean show = bean.getSelectIndex() != null && bean.getSelectIndex().equals("0");
                    bean.setChildIds(new String[]{"6"});
                    DetailItemBean item = new DetailItemBean(DetailItemType.input, "6", "1", "异常粮情描述")
                            .setInputData(mDescribeBean.abnormalGrain)
                            .setShow(show)
                            .setMust(false);
                    mAdapter.addData(mAdapter.getItemPosition(bean) + 1, item);
                }

                loadComplete();
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                loadError();
            }
        });

    }


    @Override
    public void onChangeListener(DetailItemBean item) {
        if (mData == null) {
            mData = new GrainCheckBean();
        }
        if (item.getId().equals("189")) {
            if (item.getSelectIndex().equals("0"))
                mData.insectPestError = "189";
            else
                mData.insectPestError = null;
        }
        if (item.getId().equals("190")) {
            if (item.getSelectIndex().equals("0"))
                mData.wetCheckError = "190";
            else
                mData.wetCheckError = null;
        }
        if (item.getId().equals("191")) {
            if (item.getSelectIndex().equals("0"))
                mData.grainError = "191";
            else
                mData.grainError = null;
        }

        if (item.getTitle().equals("虫害密度")) {
            mDescribeBean.pestDensity = item.getInputData();
        }
        if (item.getTitle().equals("发生部位")) {
            mDescribeBean.occurPosition = item.getInputData();
        }
        if (item.getTitle().equals("虫害面积")) {
            mDescribeBean.occurArea = item.getInputData();
        }
        if (item.getTitle().equals("虫害种类")) {
            mDescribeBean.pestType = item.getInputData();
        }
        if (item.getTitle().equals("水分异常描述")) {
            mDescribeBean.abnormalWater = item.getInputData();
        }
        if (item.getTitle().equals("异常粮情描述")) {
            mDescribeBean.abnormalGrain = item.getInputData();
        }


        // 判断 暂存 还是 提交
        mData.recordStatus = "1";
        for (DetailItemBean bean : mAdapter.getData()) {
            // 不显示 不处理
            if (!bean.isShow()) continue;
            // 非必填 不处理
            if (!bean.isMust()) continue;

            if (DetailItemType.input == bean.getItemType()) {
                // 输入内容为空时 是暂存
                if (StringTool.isEmpty(bean.getInputData())) {
                    mData.recordStatus = "0";
                    break;
                }
            }

            if (DetailItemType.radio == bean.getItemType()) {
                // 选中项为空时 是暂存
                String selectIndex = bean.getSelectIndex();
                if (selectIndex == null || selectIndex.equals("-1")) {
                    mData.recordStatus = "0";
                    break;
                }
            }
        }

        if (mData.recordStatus.equals("1")) {
            // 显示提交
            mBinding.tvSave.setVisibility(View.GONE);
            mBinding.tvSubmit.setVisibility(View.VISIBLE);
        } else {
            // 显示暂存
            mBinding.tvSave.setVisibility(View.VISIBLE);
            mBinding.tvSubmit.setVisibility(View.GONE);
        }
    }

    private void onSave() {
        if (mData == null)
            mData = new GrainCheckBean();
        mChildList.clear();
        // 异常信息Json
        String describeJson = getGson().toJson(mDescribeBean);

        mData.checkPerson = UserModel.get().getUser().getUid();// 用户id(检查人)
        mData.checkYear = "0";
        mData.checkYearWeek = DateTool.getWeekOfYear(new Date());// 检查所在年第几周(一周:周一0:00至周日24:00)
        mData.depotId = DepotModel.get().getSelectDepot().depotCode;// 库id
        mData.enumId = mEnumBean.getEnumId();// 检查类型
        mData.enumOrder = mEnumBean.getEnumOrder();// 用于同公共枚举同步顺序
        mData.houseId = HouseModel.get().getSelectHouse().houseCode;// 仓房id
        mData.operationTime = DateTool.formatDate(new Date(), DateTool.FULL_DATE);// 时间

        mData.anomalousStatus = "0";
        // 有无异常
        if (mData.insectPestError != null)
            mData.anomalousStatus = "1";
        if (mData.wetCheckError != null)
            mData.anomalousStatus = "1";
        if (mData.grainError != null)
            mData.anomalousStatus = "1";

        // 选中项
        for (DetailItemBean item : mAdapter.getData()) {
            if (item.getItemType() == DetailItemType.radio) {
                GrainCheckChildBean childBean = new GrainCheckChildBean();
                // 枚举id
                childBean.enumId = item.getId();
                // 选中项
                String select = item.getSelectIndex();
                childBean.anomalousStatus = select == null ? null
                        : select.equals("0") ? "1" : "0";// 0(否)  1(是)
                // 选中时间
                childBean.operationTime = item.getTime();
                // 选项id
                childBean.id = item.getFlowId();
                // 异常内容
                if (item.getId().equals("189") || item.getId().equals("190") || item.getId().equals("191")) {
                    // 已选中异常项 则添加异常内容
                    if (select != null && select.equals("0"))
                        childBean.errorDescribed = describeJson;
                }

                mChildList.add(childBean);
            }
        }

        LogTool.i("数据:" + getGson().toJson(mData));
        LogTool.i("选项数据:" + getGson().toJson(mChildList));

        // 发起请求
        showProgress("正在保存...", false);
        if (mPageType.equals("add"))
            GrainCheckModel.get().add(mData, mChildList, mDataCallback);
        else
            GrainCheckModel.get().update(mData, mChildList, mDataCallback);

        if (mData.recordStatus.equals("1")) {
            // 处理待办状态
            ProcessModel.get().setTodo(mData.houseId, mEnumBean.getEnumId(), "4");
        }
    }

    DataCallback<String> mDataCallback = new DataCallback<String>() {
        @Override
        public void onSuccess(String data) {
            if (!isActive()) return;
            hideProgress();
            ToastTool.showLong("保存成功");
            // 通知列表刷新
            EventBus.getDefault().post(new GrainCheckEvent(mEnumBean.getEnumName()));
            // 关闭页面
            onBack();
        }

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

}
