package com.unis.sxzcl.ui.aeration;

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

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.unis.model.DataCallback;
import com.unis.model.DepotModel;
import com.unis.model.HouseModel;
import com.unis.model.ProcessModel;
import com.unis.model.UserModel;
import com.unis.model.bean.user.UserBean;
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.process.ProcessStepBean;
import com.unis.model.event.AerationEvent;
import com.unis.sxzcl.R;
import com.unis.sxzcl.base.BaseListFragment;
import com.unis.sxzcl.databinding.FragmentAerationDetailBinding;
import com.unis.sxzcl.widget.dialog.SystemDialog;
import com.xyxsbj.mylibrary.tool.DPTool;
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.aeration
 * 类名: AerationDetailFragment
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/12/14 19:49
 * 更新人:
 * 更新时间: 2020/12/14 19:49
 * 更新说明:
 * 版本号: 1.0
 */
public class AerationDetailFragment extends BaseListFragment<FragmentAerationDetailBinding> implements AerationDetailAdapter.ChangeCallback, AerationStepAdapter.SwitchCallback {


    private String mPageType;
    private AerationDetailAdapter mAdapter;

    private AerationStepAdapter mStepAdapter;
    private AerationBean mBean;

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

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

        if (mBean != null) {
            // 不是申请人 只能查看
            String uid = UserModel.get().getUser().getUid().toString();
            if (!uid.equals(mBean.getApplyPeople())) {
                mPageType = "detail";
            }
            // 状态已完成 只能查看
            String auditState = mBean.getAuditState();
            if (auditState != null && auditState.equals("4")) {
                mPageType = "detail";
            }
        }

        mBinding.bar.setLeftClickListener(v -> onBack());
        mBinding.bar.setTitle("机械通风记录");
        mBinding.bar.setRightText("去审批").setRightClickListener(barRightListener);

        // 选项列表
        mAdapter = new AerationDetailAdapter();
        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();
        });

        // 流程列表
        mStepAdapter = new AerationStepAdapter();
        mStepAdapter.setPageType(mPageType);
        if (mPageType.equals("detail") && !mBean.getAuditState().equals("4")) {
            // 流程如果未走完 进度改为可编辑
            mStepAdapter.setPageType("edit");
        }
        mStepAdapter.setSwitchCallback(this);
//        mStepAdapter.setMaxClickIndex(2);
        mBinding.recyclerViewStep.setAdapter(mStepAdapter);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(RecyclerView.HORIZONTAL);
        mBinding.recyclerViewStep.setLayoutManager(manager);
    }

    View.OnClickListener barRightListener = v -> {
        Bundle bundle = new Bundle();
        bundle.putInt("tabIndex", 1);
        navigation(R.id.todoHomeFragment, bundle);
    };

    @Override
    protected void onFirstShow() {
        onRefresh();
    }

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

    @Override
    public void onRefreshData() {
        if (mAdapter.getData().size() > 0) {
            loadComplete();
            return;
        }

        if (mPageType.equals("add")) {
            // 新增时初始化数据
            ProcessModel.get().getApproveAll("tf", new DataCallback<List<DetailApproveBean>>() {
                @Override
                public void onSuccess(List<DetailApproveBean> data) {
                    if (!isActive()) return;
                    //创建审批流程数据
                    approveMap.put(data.get(0).getMainId(), data);

                    // 获取初始化流程数据
                    ProcessModel.get().getProcessAll("tf", new DataCallback<List<ProcessListBean>>() {
                        @Override
                        public void onSuccess(List<ProcessListBean> data) {
                            if (!isActive()) return;
                            // 流程列表
                            initStepListData(data);
                            // 选项列表
                            initListData(data);

                            // 设置当前显示流程
                            setCurrentStep(0);

                            loadComplete();
                        }

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

                }

                @Override
                public void onError(String error) {
                    super.onError(error);
                    if (!isActive()) return;
                    loadError();
                }
            });
        } else {
            // 编辑和详情获取数据
            getDetail();
        }

    }

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

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

                // 设置当前显示流程
                int ongoingStep = mBean.getOngoingStep() == null ?
                        0 : Integer.parseInt(mBean.getOngoingStep());
                setCurrentStep(ongoingStep);

//                // 给选项赋值
//                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));
//                        }
//                    }
//                }

                // 非新增页面时禁用第一流程选项
                if (!mPageType.equals("add")) {
                    String firstId = data.process.get(0).step.id;
                    for (DetailItemBean item : mAdapter.getData()) {
                        if (item.getFlowId().equals(firstId)) {
                            item.setEnable(false);
                            mAdapter.notifyItemChanged(mAdapter.getItemPosition(item));
                        }
                    }
                }

                // 查看详情时 不控制流程 全部显示
                if (mPageType.equals("detail") && mBean.getAuditState().equals("4"))
                    mAdapter.setFlowId(null);

                loadComplete();
            }

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


    /**
     * 初始化流程列表
     */
    private void initStepListData(List<ProcessListBean> data) {
        List<ProcessStepBean> list = new ArrayList<>();
        for (ProcessListBean bean : data) {
            list.add(bean.step);
        }
        mStepAdapter.setList(list);
    }

    /**
     * 初始化选项列表
     */
    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
                        .setSelectIndex(item.subData)   // 选中项
                        .setTime(item.operationTime)    // 操作时间
                        .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);
    }

    @Override
    public void onChangeListener(DetailItemBean item) {

        if (mStepAdapter.getCurrentIndex() == 0 && mStepAdapter.getMaxClickIndex() == 0) {
            mBinding.tvSubmit.setVisibility(View.VISIBLE);
            mBinding.tvSubmit.setText("保存并提交审批");
        } else {
            // 切换按钮显示
            showButton(item.getFlowId());
        }
    }

    /**
     * 根据流程id 判断底部按钮的显示
     *
     * @param flowId
     */
    public void showButton(String flowId) {
        // 查看详情时 不显示按钮
        if (mPageType.equals("detail")) {
            mBinding.tvSave.setVisibility(View.GONE);
            mBinding.tvSubmit.setVisibility(View.GONE);
            return;
        }

        if (isStepSelectFinish(flowId)) {
            // 选项已全选 保存并提交
            mBinding.tvSave.setVisibility(View.GONE);
            mBinding.tvSubmit.setVisibility(View.VISIBLE);
            mBinding.tvSubmit.setText("保存并提交");
        } else {
            // 选项未全选 暂存
            mBinding.tvSave.setVisibility(View.VISIBLE);
            mBinding.tvSubmit.setVisibility(View.GONE);
        }
    }

    private void onSave() {
        // 没有审批人弹出提示
        if (!isHaveApprove()) {
            showApproveDialog();
            return;
        }

        String houseId = HouseModel.get().getSelectHouse().houseCode;
        String depotId = DepotModel.get().getSelectDepot().depotCode;
        UserBean user = UserModel.get().getUser();

        // 取出选项值
        List<Map<String, Object>> subList = new ArrayList<>();
        for (DetailItemBean bean : mAdapter.getData()) {
            if (bean.getItemType() != DetailItemType.radio)
                continue;
            if (bean.getSelectIndex() == null)
                continue;
            Map<String, Object> map = new HashMap<>();
            map.put("subId", Integer.parseInt(bean.getId()));
            map.put("subData", Integer.parseInt(bean.getSelectIndex()));
            map.put("operationTime", bean.getTime());
            map.put("mainId", Integer.parseInt(bean.getFlowId()));
            subList.add(map);
        }

        showProgress("正在提交...", false);
        if (mPageType.equals("add")) {
            ProcessModel.get().add(
                    subList,
                    "tf",
                    houseId,
                    depotId,
                    user.getUid().toString(),
                    user.getUid().toString(),
                    "0",
                    mDataCallback);
        } else {

            // 进行中
            String auditState = "3";
            // 当前最大可见流程
            String ongoingStep = mBean.getOngoingStep();

            // 取出最高可见流程id
            int maxClickIndex = mStepAdapter.getMaxClickIndex();
            String id = mStepAdapter.getData().get(maxClickIndex).id;
            if (isStepSelectFinish(id)) {
                // 保存并提交 最大可见流程

                if (Integer.parseInt(ongoingStep) == mStepAdapter.getData().size() - 1) {
                    // 最后一个流程
                    // 状态 4=已完成
                    auditState = "4";
                } else {
                    // 不是最后一个流程
                    // 流程索引+1
                    int index = Integer.parseInt(ongoingStep) + 1;
                    ongoingStep = String.valueOf(index);
                }
            }

            ProcessModel.get().update(
                    subList,
                    auditState,
                    "tf",
                    mBean.getProcessId(),
                    String.valueOf(ongoingStep),
                    mDataCallback);
        }

    }


    /**
     * 审批人是否完整
     */
    public boolean isHaveApprove() {
        List<DetailApproveBean> beans = approveMap.get(mStepAdapter.getData().get(0).id);
        for (DetailApproveBean item : beans) {
            // 每个审批人id不得为空
            if (item.getContent() == null) {
                return false;
            }
        }
        return true;
    }

    public void showApproveDialog() {
        new SystemDialog(getContext())
                .setHideTitle()
                .setMsg("暂无审批人,请先去电脑上设置审批人管理")
                .setRightButton("确认", null).show();
    }

    /**
     * 最高流程的所有选项
     * 是否已全部选中
     *
     * @return true=已全部选中   false=有未选中项
     */
    public boolean isStepSelectFinish(String flowId) {
        // 判断流程是否完成
        for (DetailItemBean item : mAdapter.getData()) {
            if (item.getFlowId().equals(flowId)) {
                // 流程选项
                if (item.getSelectIndex() == null)
                    // 有未选中项
                    return false;
            }
        }
        // 全部选中
        return true;
    }

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

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

    /**
     * 顶部流程切换监听
     *
     * @param item
     */
    @Override
    public void onSwitchListener(ProcessStepBean item) {
        // 流程切换回调方法
        // 刷新列表
        mAdapter.setFlowId(item.id);

        mBinding.recyclerView.scrollToPosition(0);

        if (mStepAdapter.getCurrentIndex() == 0 && !mPageType.equals("add")) {
            // 非新增页 的第一个流程 隐藏提交按钮
            mBinding.tvSave.setVisibility(View.GONE);
            mBinding.tvSubmit.setVisibility(View.GONE);
        } else
            // 切换底部按钮的显示
            showButton(item.id);
    }


    /**
     * 设置当前流程
     */
    public void setCurrentStep(int index) {
        mStepAdapter.setMaxClickIndex(index);
        mStepAdapter.setCurrentIndex(index);
        if (index == -1) {
            mAdapter.setFlowId(null);
        } else {
            if (index > mStepAdapter.getData().size() - 1)
                index = mStepAdapter.getData().size() - 1;
            String id = mStepAdapter.getData().get(index).id;
            mAdapter.setFlowId(id);
        }
    }

}
