package com.unis.sxzcl.ui.template;

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

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.base.FactoryActivity;
import com.unis.sxzcl.databinding.FragmentDetailTemplateBinding;
import com.xyxsbj.mylibrary.tool.LogTool;
import com.xyxsbj.mylibrary.tool.StringTool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名: com.unis.sxzcl.ui.template
 * 类名: DetailTemplateFragment
 * 作用描述: 模版-详情页
 * 创建人: mQ
 * 创建时间: 2020/11/20 15:08
 * 更新人:
 * 更新时间: 2020/11/20 15:08
 * 更新说明:
 * 版本号: 1.0
 */
public class DetailTemplateFragment extends BaseFragment<FragmentDetailTemplateBinding>
        implements DetailTemplateAdapter.Callback {

    private DetailTemplateAdapter mAdapter;

    private TemplateListBean mBean;
    private List<DetailTemplateBean> mList;
    private String mPageType;


    public static void startPage(Context context, String pageType, TemplateListBean bean) {
        Bundle bundle = new Bundle();
        bundle.putString("pageType", pageType);
        if (bean != null)
            bundle.putString("data", new Gson().toJson(bean));
        FactoryActivity.startPage(context, DetailTemplateFragment.class, bundle);
    }

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

    @Override
    protected void init() {
        Bundle bundle = getArguments();
        String data = bundle.getString("data");
        LogTool.i("data数据:" + data);
        if (StringTool.notEmpty(data)) {
            mBean = new Gson().fromJson(data, TemplateListBean.class);
        }

        mPageType = bundle.getString("pageType");

        mBinding.bar.setLeftClickListener(v -> finish());
        mBinding.bar.setTitle(mPageType);
        mBinding.bar.setRightVisible(true);
        mBinding.bar.setRightText("提交");
        mBinding.bar.setRightClickListener(v -> {
            next();
        });

        mAdapter = new DetailTemplateAdapter();
        mBinding.recyclerView.setAdapter(mAdapter);
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter.setCallback(this);
    }

    @Override
    protected void onFirstShow() {
        mList = new ArrayList<>();

        mList.add(new DetailTemplateBean(1, "2020-11-18 12:00:00",
                "仓房主体是否完好",
                new String[]{"是", "否"}, "key",
                1));
        mList.add(new DetailTemplateBean(2, "2020-11-18 12:00:00",
                "门窗是否完好",
                new String[]{"是", "否"}, "key",
                1));
        mList.add(new DetailTemplateBean(3, "2020-11-18 12:00:00",
                "屋面防水是否完好",
                new String[]{"是", "否"}, "key",
                1));
        mList.add(new DetailTemplateBean(4, "2020-11-18 12:00:00",
                "屋面隔热是否完好",
                new String[]{"是", "否"}, "key",
                2));
        mList.add(new DetailTemplateBean(5, "2020-11-18 12:00:00",
                "仓内吊顶是否完好",
                new String[]{"是", "否"}, "key",
                2));
        mList.add(new DetailTemplateBean(6, "2020-11-18 12:00:00",
                "爬梯是否完好",
                new String[]{"是", "否"}, "key",
                2));
        mList.add(new DetailTemplateBean(7, "2020-11-18 12:00:00",
                "挡粮门是否完好",
                new String[]{"是", "否"}, "key",
                3));
        mList.add(new DetailTemplateBean(8, "2020-11-18 12:00:00",
                "粮情测温是否完好",
                new String[]{"是", "否"}, "key",
                3));
        mList.add(new DetailTemplateBean(9, "2020-11-18 12:00:00",
                "远程监控设施是否完好",
                new String[]{"是", "否"}, "key",
                4));
        mList.add(new DetailTemplateBean(10, "2020-11-18 12:00:00",
                "通风设施（轴流风机、内环流系统）是否完好",
                new String[]{"是", "否"}, "key",
                4));

        flowControl(1);

        mAdapter.setList(mList);

        showData();

    }

    /**
     * 流程控制
     * 小于等于当前流程的按钮打开
     */
    private void flowControl(int flowNow) {
        for (DetailTemplateBean bean : mList) {
            //按钮项小于等于当前流程 打开按钮
            bean.enable = bean.flowNow <= flowNow;
        }
    }

    /**
     * 显示所选项
     */
    private void showData() {
        if (mBean == null) return;

        // 1_0_1,2_1_2 (id_选项_流程) 根据 , 拆分所选数据
        String[] selectItems = mBean.tableStr.split(",");
        //key=id value=选项
        Map<Long, Integer> map = new HashMap<>();
        // 遍历所选数据
        for (String text : selectItems) {
            if (StringTool.isEmpty(text))
                continue;
            //1_0_1 (id_选项_流程)
            String[] split = text.split("_");
            //插入id和选项
            map.put(Long.parseLong(split[0]),
                    Integer.parseInt(split[1]));
        }
        // 遍历UI数据源
        for (DetailTemplateBean bean : mList) {
            // 通过id查找选项
            Integer select = map.get(bean.id);
            bean.selectIndex = select != null ? select : -1;
        }
        //控制按钮开关
        flowControl(mBean.flowNow);

        //刷新列表UI
        mAdapter.notifyDataSetChanged();
    }

    private void next() {
        Map<String, Object> map = new HashMap<>();
        if (mBean != null)
            map.put("id", mBean.id);

        StringBuilder sb = new StringBuilder();
        for (DetailTemplateBean item : mList) {
            sb.append(item.id)
                    .append("_")
                    .append(item.selectIndex)
                    .append("_")
                    .append(item.flowNow)
                    .append(",");
        }
        String string = sb.toString();
        map.put("tableStr", string.split(","))
        ;
        new AlertDialog.Builder(getContext())
                .setTitle("提交数据")
                .setMessage(new Gson().toJson(map))
                .setCancelable(false)
                .setPositiveButton("关闭", null)
                .show();
    }

    /**
     * 列表选中项事件监听
     *
     * @param item        项数据源
     * @param changeIndex 所选下标
     */
    @Override
    public void onChangesListener(DetailTemplateBean item, int changeIndex) {
        //将所选下标 复制给数据源
        item.selectIndex = changeIndex;

        //控制流程
        int flow = 1;//可控制最大流程
        if (mBean != null)
            flow = mBean.flowNow;

        //大于已有流程时  控制按钮开关(小于当前流程无需管理开关,因为初始化时已打开)
        if (item.flowNow >= flow && changeIndex > -1) {
            boolean flag = true;//是否全部选择
            for (DetailTemplateBean bean : mList) {
                if (item.flowNow == bean.flowNow) {
                    LogTool.i(item.flowNow + "匹配所选项:" + item.toString());
                    if (bean.selectIndex == -1) {
                        //-1 代表未选择
                        flag = false;
                        break;
                    }
                }
            }

            //所选流程全部选择时 下个流程按钮全部打开
            if (flag) {
                for (int i = 0; i < mList.size(); i++) {
                    DetailTemplateBean bean = mList.get(i);
                    if ((item.flowNow + 1) == bean.flowNow) {
                        LogTool.i("打开按钮:" + i);
                        bean.enable = true;
                    }
                }
                mAdapter.notifyDataSetChanged();
            }


        }
    }

}
