package com.unis.sxzcl.ui.todo;

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

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.event.TodoEvent;
import com.unis.sxzcl.base.BaseListFragment;
import com.unis.sxzcl.databinding.FragmentTodoDetailBinding;
import com.unis.sxzcl.widget.dialog.SystemDialog;
import com.xyxsbj.mylibrary.tool.ToastTool;

import org.greenrobot.eventbus.EventBus;

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

/**
 * 包名: com.unis.sxzcl.ui.todo
 * 类名: TodoDetailFragment
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/12/21 16:12
 * 更新人:
 * 更新时间: 2020/12/21 16:12
 * 更新说明:
 * 版本号: 1.0
 */
public class TodoDetailFragment extends BaseListFragment<FragmentTodoDetailBinding> implements TodoDetailAdapter.AuditCallback {

    private AerationBean mBean;
    private TodoDetailAdapter mAdapter;
    private SystemDialog mSystemDialog;
    private int mOngoingStep;

    @Override
    public void onRefreshData() {

        ProcessModel.get().getDetail(mBean.getProcessId(), new DataCallback<ProcessDetailBean>() {
            @Override
            public void onSuccess(ProcessDetailBean data) {
                if (!isActive()) return;
                // 获取当前审批流程数据
                String flowId = data.process.get(0).step.id;
                approveMap.put(flowId, data.audit);

                // 选项列表 和 流程
                initListData(data.process);

                // 只显示当前流程
                mAdapter.setFlowId(flowId);

                mAdapter.setPageType("detail");

                // 给选项赋值
                for (AerationBean bean : data.data) {
                    for (DetailItemBean item : mAdapter.getData()) {
                        if (bean.getSubId() != null && bean.getSubId().equals(item.getId())) {
                            item.setSelectIndex(bean.getSubData());
                            mAdapter.notifyItemChanged(mAdapter.getItemPosition(item));
                        }
                    }
                }

                loadComplete();
            }

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

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

    @Override
    protected void init() {
        mBinding.bar.setTitle("详情")
                .setLeftClickListener(v -> onBack());
        mAdapter = new TodoDetailAdapter();
        mAdapter.setAuditCallback(this);
        initBaseListView(mBinding.refreshLayout, mBinding.recyclerView, mAdapter, false);
    }

    @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);
        mOngoingStep = mBean.getOngoingStep() == null ? 0 : Integer.parseInt(mBean.getOngoingStep());
        showTop();

        onRefresh();
    }

    Map<String, List<DetailApproveBean>> approveMap = new HashMap<>();

    /**
     * 初始化选项列表
     */
    private void initListData(List<ProcessListBean> data) {
        List<DetailItemBean> list = new ArrayList<>();
        int count = 0;
        for (ProcessListBean bean : data) {
            // 遍历流程下的选项集合
            for (ProcessItemBean item : bean.list) {
                // 增加所有选项数据
                count++;
                // 单选
                DetailItemBean itemBean = new DetailItemBean(DetailItemType.radio)
                        .setTitle(item.title)       // 标题
                        .setId(item.id + "")        // id
                        .setIndex(count)            // 序号
                        .setFlowId(item.zid + "")   // 流程id
                        .setOption(item.details.split(",")); // 选项
                list.add(itemBean);
            }

            // 添加审批流程
            List<DetailApproveBean> approveList = approveMap.get(bean.step.id);
            if (approveList != null) {
                approveList.get(0).setTitle("发起申请");
                approveList.remove(approveList.size() - 1);
                DetailItemBean itemBean = new DetailItemBean(DetailItemType.approve);
                itemBean.setApproves(approveList);
                itemBean.setTitle("流程(机械通风审批)");
                itemBean.setFlowId(bean.step.id);
                list.add(itemBean);
            }
        }
        mAdapter.setList(list);
    }

    /**
     * 显示业务简介
     */
    public void showTop() {
        if (mBean == null)
            return;
        mBinding.tvWarnTime.setVisibility(View.GONE);
        mBinding.tvTimeout.setVisibility(View.GONE);
        // 业务类型
        mBinding.tvTitle.setText(mBean.getWorkName());
        // 业务内容
        // 仓号: 1号仓\n申请人: 王全德\n申请部门: 仓储部\n公司: xxx公司
        StringBuilder sb = new StringBuilder();
        sb.append("仓号: ")
                .append(mBean.getHouseName())
                .append("\n")
                .append("申请人: ")
                .append(mBean.getApplyName())
                .append("\n")
                .append("申请部门: ")
                .append(mBean.getDepartmentName())
                .append("\n")
                .append("公司: ")
                .append(mBean.getCompanyName())
                .append("\n")
        ;
        mBinding.tvContent.setText(sb.toString());
    }

    /**
     * 点击审批回调监听
     * 弹出对话框询问是否审批
     *
     * @param mainId 当前审批流程id
     * @param pass   是否审批通过
     * @param index  审批人索引
     */
    @Override
    public void onAuditListener(String mainId, boolean pass, int index) {
        if (mSystemDialog == null)
            mSystemDialog = new SystemDialog(getContext())
                    .setHideTitle();
        if (pass) {
            mSystemDialog.setMsg("确定审批通过？");
        } else {
            mSystemDialog.setMsg("确定审批不通过？");
        }
        mSystemDialog.setLeftButton("取消", null);
        mSystemDialog.setRightButton("确定", dialog -> {
            mSystemDialog.dismiss();
            audit(mainId, pass, index);
        });
        mSystemDialog.show();
    }


    /**
     * 提交审批
     * 1.审批状态auditState: 1=通过 2=不通过 3=审批通过进行中
     * 当最后一个人审批通过时 应传 3=审批通过进行中;
     * 2.当前流程索引ongoingStep: 0 1 2 3 4 ....
     * 当最后一个人审批通过时, 本流程结束,流程+1
     *
     * @param mainId 流程id
     * @param pass   是否审批通过
     * @param index  审批人索引
     */
    public void audit(String mainId, boolean pass, int index) {
        showProgress("正在审批...", false);

        String ongoingStep = String.valueOf(mOngoingStep);
        String auditState = pass ? "1" : "2";// 1=通过 2=不通过

        // 获取审批流程集合
        List<DetailApproveBean> auditList = approveMap.get(mainId);
        //  判断 最后一个人审批通过
        if (index == auditList.size() - 1 && pass) {
            // 3=审批通过进行中
            auditState = "3";
            // 进行下一个流程
            ongoingStep = String.valueOf(mOngoingStep + 1);
        }
        // 提交审批
        ProcessModel.get().audit(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();
            }

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

}
