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.google.gson.reflect.TypeToken;
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.detail.DetailItemBean;
import com.unis.model.bean.detail.DetailItemType;
import com.unis.model.bean.grain_check.GrainCheckBean;
import com.unis.model.bean.grain_check.GrainCheckDescribeBean;
import com.unis.model.bean.grain_check.GrainCheckDictionaryBean;
import com.unis.model.event.GrainCheckEvent;
import com.unis.sxzcl.base.BaseListFragment;
import com.unis.sxzcl.databinding.FragmentAddBinding;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名: com.unis.sxzcl.ui.grain_check
 * 类名: GrainCheckDetailFragment
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/12/11 9:55
 * 更新人:
 * 更新时间: 2020/12/11 9:55
 * 更新说明:
 * 版本号: 1.0
 */
public class GrainCheckDetailFragment extends BaseListFragment<FragmentAddBinding> implements GrainCheckDetailAdapter.ChangeCallback {


    private String mTab;
    private String mPageType;
    private GrainCheckDetailAdapter mAdapter;
    private GrainCheckBean mData;

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

    @Override
    protected void init() {
        Bundle bundle = getArguments();
        if (bundle == null) {
            ToastTool.showLong("没有参数");
            onBack();
            return;
        }
        mTab = bundle.getString("tab");
        if (mTab == null) {
            ToastTool.showLong("没有参数");
            onBack();
            return;
        }
        mBinding.bar.setTitle(mTab);
        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;
        }
        // 获取字典表数据
        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<GrainCheckDictionaryBean> data) {
        // 增加选项
        for (int i = 0; i < data.size(); i++) {
            GrainCheckDictionaryBean bean = data.get(i);
            DetailItemBean item = new DetailItemBean(DetailItemType.radio)//项类型
                    .setFlowId("1")                 // 流程
                    .setId(bean.getFieldValue())    // 字典key
                    .setTitle(bean.getFieldDetail())// 名称
                    .setIndex(i + 1)                // 序号
                    .setOption(bean.getOptions().split(","));// 选项数组
            // 加入列表中
            mAdapter.addData(item);
        }

        // 增加虫害情况 输入框
        DetailItemBean bean = getItemById("pest_abnormal");
        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("water_abnormal");
        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("grain_abnormal");
        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;

        // 取出选中详情信息
        Map<String, Map<String, String>> checkDescribe = getGson().fromJson(mData.checkDescribe,
                new TypeToken<Map<String, Map<String, String>>>() {
                }.getType());
        if (checkDescribe != null) {
            // 遍历选中项
            for (String key : checkDescribe.keySet()) {
                // 取出 选中值,时间
                Map<String, String> map = checkDescribe.get(key);
                String selectIndex = map.get("choose");
                String time = map.get("time");
                if (selectIndex == null)
                    continue;
                String[] childIds = null;

                // 遍历列表
                for (DetailItemBean item : mAdapter.getData()) {
                    String id = item.getId();
                    // 找到对应项
                    if (id != null && id.equals(key)) {
                        // 设置选中值,时间
                        item.setSelectIndex(selectIndex);
                        item.setTime(time);

                        // 选项0(是)  取出关联项
                        if (item.getChildIds() != null && selectIndex.equals("0")) {
                            childIds = item.getChildIds();
                        }
                        break;
                    }
                }

                // 处理关联项 是否显示
                if (childIds != null)
                    // 遍历关联项
                    for (String cId : childIds) {
                        // 遍历列表
                        for (DetailItemBean item : mAdapter.getData()) {
                            // 找到对应项
                            if (item.getId().equals(cId)) {
                                // 显示并刷新
                                item.setShow(true);
                                mAdapter.notifyItemChanged(mAdapter.getItemPosition(item));
                                break;
                            }
                        }
                    }
            }

        }

        GrainCheckDescribeBean describe = mData.grainAbnormalDescribe;
        if (describe == null)
            return;
        // 设置异常描述
        for (DetailItemBean item : mAdapter.getData()) {
            if (item.getTitle().equals("虫害密度")) {
                item.setInputData(describe.pestDensity);
                continue;
            }
            if (item.getTitle().equals("发生部位")) {
                item.setInputData(describe.occurPosition);
                continue;
            }
            if (item.getTitle().equals("虫害面积")) {
                item.setInputData(describe.occurArea);
                continue;
            }
            if (item.getTitle().equals("虫害种类")) {
                item.setInputData(describe.pestType);
                continue;
            }
            if (item.getTitle().equals("水分异常描述")) {
                item.setInputData(describe.abnormalWater);
                continue;
            }
            if (item.getTitle().equals("异常粮情描述")) {
                item.setInputData(describe.abnormalGrain);
                continue;
            }
        }

        // 设置状态
//        String recordStatus = mData.recordStatus;
//        if (recordStatus != null && recordStatus.equals("1")) {
//            // 1已完成
//            mBinding.tvSave.setVisibility(View.GONE);
//            mBinding.tvSubmit.setVisibility(View.GONE);
//        } else {
//            // 0进行中
//            mBinding.tvSave.setVisibility(View.VISIBLE);
//            mBinding.tvSubmit.setVisibility(View.GONE);
//        }

    }


    @Override
    public void onChangeListener(DetailItemBean item) {
        if (mData == null) {
            mData = new GrainCheckBean();
        }
        if (item.getId().equals("pest_abnormal")) {
            mData.pestAbnormal = item.getSelectIndex();
        }
        if (item.getId().equals("water_abnormal")) {
            mData.waterAbnormal = item.getSelectIndex();

        }
        if (item.getId().equals("grain_abnormal")) {
            mData.grainAbnormal = item.getSelectIndex();
        }
        GrainCheckDescribeBean describe = mData.grainAbnormalDescribe;
        if (item.getTitle().equals("虫害密度")) {
            describe.pestDensity = item.getInputData();
        }
        if (item.getTitle().equals("发生部位")) {
            describe.occurPosition = item.getInputData();
        }
        if (item.getTitle().equals("虫害面积")) {
            describe.occurArea = item.getInputData();
        }
        if (item.getTitle().equals("虫害种类")) {
            describe.pestType = item.getInputData();
        }
        if (item.getTitle().equals("水分异常描述")) {
            describe.abnormalWater = item.getInputData();
        }
        if (item.getTitle().equals("异常粮情描述")) {
            describe.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();

        mData.uid = UserModel.get().getUser().getUid();
        String depotCode = DepotModel.get().getSelectDepot().depotCode;
        mData.depotId = depotCode != null ? Integer.parseInt(depotCode) : null;
        String houseCode = HouseModel.get().getSelectHouse().houseCode;
        mData.houseId = houseCode != null ? Integer.valueOf(houseCode) : null;

        // 时间
        mData.checkTime = DateTool.formatDate(new Date(), DateTool.YTDTD_DATE);
        // 类型
        mData.checkPerson = mTab;
        // 有无异常
        if (mData.pestAbnormal != null && mData.pestAbnormal.equals("0"))
            mData.anomalousStatus = "0";
        if (mData.waterAbnormal != null && mData.waterAbnormal.equals("0"))
            mData.anomalousStatus = "0";
        if (mData.grainAbnormal != null && mData.grainAbnormal.equals("0"))
            mData.anomalousStatus = "0";

        // 选中项
        Map<String, Map<String, String>> map = new HashMap<>();
        for (DetailItemBean item : mAdapter.getData()) {
            if (item.getId() != null) {
                if (item.getSelectIndex() == null)
                    continue;
                Map<String, String> data = new HashMap<>();
                data.put("choose", item.getSelectIndex());
                data.put("time", item.getTime());
                map.put(item.getId(), data);
            }
        }
        mData.checkDescribe = getGson().toJson(map);

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

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

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

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

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

}
