package com.unis.sxzcl.ui.allround;

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

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.unis.model.bean.detail.DetailApproveBean;
import com.unis.model.bean.detail.DetailItemBean;
import com.unis.sxzcl.base.BaseFragment;
import com.unis.sxzcl.databinding.FragmentProcessDetailBinding;
import com.unis.sxzcl.widget.dialog.SystemDialog;
import com.xyxsbj.mylibrary.tool.LogTool;

import java.util.List;

/**
 * 流程详情 Fragment
 * 创建人: mQ
 * 创建时间: 2021/1/26 17:26
 */
public class ProcessDetailFragment extends BaseFragment<FragmentProcessDetailBinding>
        implements ProcessOptionAdapter.ChangeCallback {

    // 页面位置
    private int mIndex;
    // 是否是最后一个
    public boolean mIsEnd;
    // 页面类型
    private String mPageType;

    // 选项列表
    private List<DetailItemBean> mOptionList;
    // 审批列表
    private List<DetailApproveBean> mApproveList;
    // 审批适配器
    private ProcessApproveAdapter mApproveAdapter;
    // 选项适配器
    private ProcessOptionAdapter mOptionAdapter;

    // 保存接口回调
    private SaveCallback mSaveCallback;

    // 审批接口回调
    private ProcessApproveAdapter.AuditCallback mAuditCallback;

    /**
     * 实例化方法
     *
     * @param index       页面位置
     * @param isEnd       是否最后一页
     * @param pageType    页面类型 add edit detail approve
     * @param approveName 审批流程名称
     * @param optionList  选项列表
     * @param approveList 审批列表
     * @return
     */
    public static ProcessDetailFragment newFragment(int index,
                                                    boolean isEnd,
                                                    String pageType,
                                                    String approveName,
                                                    List<DetailItemBean> optionList,
                                                    List<DetailApproveBean> approveList) {
        Gson gson = new Gson();
        Bundle bundle = new Bundle();
        bundle.putInt("index", index);
        bundle.putBoolean("end", isEnd);
        bundle.putString("pageType", pageType);
        bundle.putString("approveName", approveName);
        if (optionList != null)
            bundle.putString("optionList", gson.toJson(optionList));
        if (approveList != null)
            bundle.putString("approveList", gson.toJson(approveList));

        ProcessDetailFragment fragment = new ProcessDetailFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


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

    @Override
    protected void init() {
        Bundle bundle = getArguments();
        if (bundle == null) return;

        mIndex = bundle.getInt("index", 0);
        mIsEnd = bundle.getBoolean("end", false);
        mPageType = bundle.getString("pageType", "add");

        // 获取选项列表数据
        String optionListJson = getArguments().getString("optionList");
        if (optionListJson != null) {
            mOptionList = getGson().fromJson(optionListJson,
                    new TypeToken<List<DetailItemBean>>() {
                    }.getType());
        }
        LogTool.i("页面" + mIndex + "的选项数据:" + optionListJson);

        // 获取审批列表数据
        String approveListJson = getArguments().getString("approveList");
        if (approveListJson != null) {
            mApproveList = getGson().fromJson(approveListJson,
                    new TypeToken<List<DetailApproveBean>>() {
                    }.getType());
        }


        // 修改 且 有审批数据时  只读
        mPageType = mPageType.equals("edit") && mApproveList != null ? "detail" : mPageType;
        LogTool.i("类型:" + mPageType);

        // 审批流程名称
        String approveName = bundle.getString("approveName");
        mBinding.tvApproveName.setText("流程(" + approveName + "审批)");

        // 初始化选项列表
        initOption();

        // 初始化审批列表
        initApprove();

        // 默认隐藏操作按钮
        mBinding.layoutBottom.setVisibility(View.GONE);
        // 返回按钮监听
        mBinding.btnBack.setOnClickListener(v ->
                new SystemDialog(getContext())
                        .setMsg("页面数据未保存,是否关闭页面?")
                        .setHideTitle()
                        .setHideClose()
                        .setLeftButton("取消", null)
                        .setRightButton("关闭", dialog -> {
                            dialog.dismiss();
                            onBack();
                        }).show());
        // 暂存/保存/完成/保存并提交审批 按钮监听
        mBinding.btnSave.setOnClickListener(v -> save());

    }

    /**
     * 初始化选项列表
     */
    private void initOption() {
        if (mOptionList == null) {
            return;
        }
        // 初始化选项列表适配器
        mOptionAdapter = new ProcessOptionAdapter();
        mOptionAdapter.setDetail(mPageType.equals("detail") || mPageType.equals("approve"));
        mOptionAdapter.setCallback(this);
        mBinding.recyclerViewOption.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerViewOption.setAdapter(mOptionAdapter);

        // 填充数据
        mOptionAdapter.addData(mOptionList);
        mBinding.recyclerViewOption.scheduleLayoutAnimation();
        LogTool.i(mIndex + "填充选项数据");
    }

    /**
     * 初始化审批列表
     */
    private void initApprove() {
        if (mApproveList == null) {
            // 没有审批数据 隐藏审批列表
            mBinding.approveLayout.setVisibility(View.GONE);
            return;
        }
        if (!mApproveList.isEmpty()) {
            // 第一项是发起申请
            mApproveList.get(0).setTitle("发起申请");
            // 最后一个审批人是保管员 就移除掉
            String people = mApproveList.get(mApproveList.size() - 1).getContent();
            if (people != null && people.equals("0"))
                mApproveList.remove(mApproveList.size() - 1);
        }

        // 初始化审批列表适配器
        mApproveAdapter = new ProcessApproveAdapter();
        mApproveAdapter.setPageType(mPageType);
        mBinding.recyclerViewApprove.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerViewApprove.setAdapter(mApproveAdapter);
        mApproveAdapter.setAuditCallback(mAuditCallback);

        // 填充数据
        mApproveAdapter.addData(mApproveList);
        mBinding.recyclerViewOption.scheduleLayoutAnimation();
    }

    @Override
    protected void onFirstShow() {

    }

    /**
     * 选项监听事件
     *
     * @param item
     */
    @Override
    public void onChangeListener(DetailItemBean item) {
        mBinding.layoutBottom.setVisibility(View.VISIBLE);

        if (mApproveList != null) {
            // 审批
            mBinding.btnSave.setText("保存并提交审批");
        } else if (!isSelectFinish()) {
            // 有未选项
            mBinding.btnSave.setText("暂存");
        } else {
            // 全部已选
            if (mIsEnd) {
                // 最后一页
                mBinding.btnSave.setText("完成");
            } else {
                // 非最后一页
                mBinding.btnSave.setText("保存");
            }
        }
    }


    /**
     * 是否已全部选中
     *
     * @return true=已全部选中   false=有未选中项
     */
    public boolean isSelectFinish() {
        // 判断流程是否完成
        for (DetailItemBean item : mOptionAdapter.getData()) {
            // 流程选项
            if (item.getSelectIndex() == null)
                // 有未选中项
                return false;
        }
        // 全部选中
        return true;
    }

    /**
     * 是否全部选择的第一选项
     *
     * @return true=已全部选中第一选项   false=未全部选中第一选项
     */
    public boolean isSelectFirstFinish() {
        // 判断流程是否完成
        for (DetailItemBean item : mOptionAdapter.getData()) {
            // 流程选项
            if (item.getSelectIndex() == null || !item.getSelectIndex().equals("0"))
                // 有未选 或 选中非第一选项
                return false;
        }
        // 全部选中第一选项
        return true;
    }

    /**
     * 审批人是否完整
     */
    public boolean isHaveApprove() {
        for (DetailApproveBean item : mApproveList) {
            // 每个审批人id不得为空
            if (item.getContent() == null) {
                return false;
            }
        }
        return true;
    }

    public boolean isApprove() {
        return mApproveList != null || mPageType.equals("approve");
    }

    /**
     * 保存
     */
    private void save() {
        // 有审批流程时
        if (mApproveList != null) {
            // 1.判断审批人员是否完整
            if (!isHaveApprove()) {
                new SystemDialog(getContext())
                        .setHideClose()
                        .setHideTitle()
                        .setMsg("审批人信息不完整,请先维护审批人管理!")
                        .setRightButton("确认", null)
                        .show();
                return;
            }
            // 2.判断选项全部选【是】
            if (!isSelectFirstFinish()) {
                new SystemDialog(getContext())
                        .setHideClose()
                        .setHideTitle()
                        .setMsg("只有选择【是】才能发起申请!")
                        .setRightButton("确认", null)
                        .show();
                return;
            }
        }
        if (mSaveCallback != null)
            mSaveCallback.onSaveCallback(mIndex, mOptionAdapter.getData());
    }

    /**
     * 设置审批按钮事件
     */
    public void setApproveCallback(ProcessApproveAdapter.AuditCallback auditCallback) {
        mAuditCallback = auditCallback;
    }

    /**
     * 设置保存按钮监听
     */
    public void setSaveCallback(SaveCallback saveCallback) {
        mSaveCallback = saveCallback;
    }

    /**
     * 保存回调接口
     */
    public interface SaveCallback {
        /**
         * 保存时回调方法
         *
         * @param pageIndex  页面位置
         * @param optionList 选项数据集合
         */
        void onSaveCallback(int pageIndex, List<DetailItemBean> optionList);
    }
}
