package com.unis.sxzcl.ui.todo;

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

import androidx.fragment.app.FragmentTransaction;

import com.unis.model.BasicModel;
import com.unis.model.DataCallback;
import com.unis.model.ProcessModel;
import com.unis.model.bean.aeration.AerationBean;
import com.unis.model.bean.detail.DetailApproveBean;
import com.unis.model.bean.detail.DetailItemBean;
import com.unis.model.bean.detail.DetailItemType;
import com.unis.model.bean.process.ProcessDetailBean;
import com.unis.model.bean.process.ProcessItemBean;
import com.unis.model.bean.process.ProcessListBean;
import com.unis.model.bean.todo.WorkType;
import com.unis.model.event.TodoEvent;
import com.unis.sxzcl.R;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.databinding.FragmentTodoApproveBinding;
import com.unis.sxzcl.ui.allround.ProcessApproveAdapter;
import com.unis.sxzcl.ui.allround.ProcessDetailFragment;
import com.xyxsbj.mylibrary.tool.LogTool;
import com.xyxsbj.mylibrary.tool.ToastTool;

import org.greenrobot.eventbus.EventBus;

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

/**
 * 待办审批 Fragment
 * 创建人: mQ
 * 创建时间: 2021/1/29 15:17
 */
public class TodoApproveFragment extends BaseFragment<FragmentTodoApproveBinding> {

    private AerationBean mBean;

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

    @Override
    protected void init() {
        mBinding.bar.setTitle("详情")
                .setLeftClickListener(v -> onBack());
        mBinding.layoutEmpty.getRoot().setOnClickListener(v -> getData());
        mBinding.layoutError.getRoot().setOnClickListener(v -> getData());
    }

    @Override
    protected void onFirstShow() {
        Bundle bundle = getArguments();
        String data = bundle.getString("data", null);
        if (data == null) {
            ToastTool.showLong("没有参数");
            onBack();
        }
        mBean = getGson().fromJson(data, AerationBean.class);
        showTop();

        getData();
    }

    /**
     * 显示业务简介
     */
    public void showTop() {
        mBinding.tvWarnTime.setVisibility(View.GONE);
        mBinding.tvTimeout.setVisibility(View.GONE);
        // 业务类型
        mBinding.tvTitle.setText(mBean.getWorkName());
        // 业务内容
        mBinding.tvContent.setText(mBean.getContent());
    }

    private int optionCount;


    /**
     * 获取数据
     */
    private void getData() {
        showLoading();
        ProcessModel.get().getDetail(mBean.getProcessId(), new DataCallback<ProcessDetailBean>() {
            @Override
            public void onSuccess(ProcessDetailBean data) {
                if (!isActive()) return;
                hideLoading();
                if (data == null || data.process == null || data.process.size() == 0) {
                    showEmpty();
                    return;
                }
                // 当前执行节点索引
                int ongoingStep = getOngoingStep();
                if (mBean.getType().equals(WorkType.xzjh)) {
                    // 熏蒸计划只取第0个节点审批
                    ongoingStep = 0;
                }

                // 审批人列表(默认为首节点)
                List<DetailApproveBean> approveList = data.audit;
                // 选项列表(默认为首节点)
                List<ProcessItemBean> processList = data.process.get(0).list;

                // 多流程审批时 获取最新一次节点信息
                if (approveList == null) {
                    for (int i = 0; i < data.process.size(); i++) {
                        ProcessListBean bean = data.process.get(i);
                        // 小于或等于当前执行节点
                        if (i <= ongoingStep) {
                            // 有审批. 则获取 选项列表和审批人列表
                            if (bean.step.getExistProcess().equals("0")) {
                                processList = bean.list;
                                approveList = bean.audit;
                            }
                        } else break;
                    }
                }
                // 最后一个审批人是保管员 就移除掉
                if (approveList != null && approveList.get(approveList.size() - 1).getContent().equals("0"))
                    approveList.remove(approveList.size() - 1);


                FragmentTransaction bt = getChildFragmentManager().beginTransaction();

                // 创建选项数据
                List<DetailItemBean> optionList = null;
                optionCount = 0;
                if (processList != null && processList.size() > 0) {
                    optionList = new ArrayList<>();
                    for (ProcessItemBean item : processList) {
                        optionCount++;// 定义序号自增
                        // 单选
                        DetailItemBean itemBean = new DetailItemBean(DetailItemType.radio)
                                .setTitle(item.title)           // 标题
                                .setId(item.id + "")            // id
                                .setIndex(optionCount)          // 序号
                                .setFlowId(item.zid + "")       // 流程id
                                .setSelectIndex(item.subData)   // 选中项
                                .setTime(item.operationTime)    // 操作时间
                                .setOption(item.details.split(",")) // 选项
                                .setAuditId(item.auditId);      // 主键id

                        optionList.add(itemBean);
                    }
                }

                // 创建页面
                ProcessDetailFragment fragment;
                fragment = ProcessDetailFragment.newFragment(
                        0,                              // 页面位置
                        true,                           //是否最后一页
                        "approve",                      // 页面类型
                        BasicModel.get().getWorkTypeName(mBean.getType()),// 业务名称
                        optionList,                     // 选项数据
                        approveList);                   // 审批数据
                // 设置审批按钮事件回调
                fragment.setApproveCallback(mAuditCallback);

                bt.add(R.id.container_layout, fragment);

                bt.commit();
            }

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


    /**
     * 审批按钮事件回调
     * 当最后一个人审批通过时, 审批状态改为3(进行中), 页面位置改为下一页
     */
    ProcessApproveAdapter.AuditCallback mAuditCallback = (item, pass, index, isEnd) -> {
        showProgress("正在审批...", false);

        // 页面位置
        int ongoingStep = getOngoingStep();
        // 审批状态
        String auditState = pass ? "1" : "2";

        LogTool.i("审批信息---ongoingStep:" + ongoingStep + "---auditState:" + auditState + "");
        //  最后一个人审批通过
        if (isEnd && pass) {
            // 审批状态改为3(进行中)
            auditState = "3";
            // 页面位置改为+1(下一个页面)
            ongoingStep += 1;
        }

        // 提交审批
        ProcessModel.get().audit(mBean.getType(), mBean.getId(), auditState, ongoingStep + "", new DataCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (!isActive()) return;
                hideProgress();
                EventBus.getDefault().post(new TodoEvent());
                ToastTool.showLong("审批完成");
//                onBack();
                mBinding.containerLayout.removeAllViews();
                getData();
            }

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

    public void showLoading() {
        mBinding.layoutLoading.getRoot().setVisibility(View.VISIBLE);
        mBinding.layoutEmpty.getRoot().setVisibility(View.GONE);
        mBinding.layoutError.getRoot().setVisibility(View.GONE);
    }

    public void hideLoading() {
        mBinding.layoutLoading.getRoot().setVisibility(View.GONE);
        mBinding.layoutEmpty.getRoot().setVisibility(View.GONE);
        mBinding.layoutError.getRoot().setVisibility(View.GONE);
    }

    public void showEmpty() {
        mBinding.layoutLoading.getRoot().setVisibility(View.GONE);
        mBinding.layoutEmpty.getRoot().setVisibility(View.VISIBLE);
        mBinding.layoutError.getRoot().setVisibility(View.GONE);
    }

    public void showError() {
        mBinding.layoutLoading.getRoot().setVisibility(View.GONE);
        mBinding.layoutEmpty.getRoot().setVisibility(View.GONE);
        mBinding.layoutError.getRoot().setVisibility(View.VISIBLE);
    }

    public int getOngoingStep() {
        if (mBean == null || mBean.getOngoingStep() == null)
            return 0;
        return Integer.parseInt(mBean.getOngoingStep());
    }
}
