package com.unis.model;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.unis.model.bean.aeration.AerationBean;
import com.unis.model.bean.detail.DetailApproveBean;
import com.unis.model.bean.process.ProcessDetailBean;
import com.unis.model.bean.process.ProcessListBean;
import com.unis.model.bean.user.UserBean;
import com.unis.model.event.TodoEvent;
import com.xyxsbj.mylibrary.tool.DateTool;
import com.xyxsbj.mylibrary.tool.SPTool;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * 包名: com.unis.model
 * 类名: ProcessModel
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/12/16 11:30
 * 更新人:
 * 更新时间: 2020/12/16 11:30
 * 更新说明:
 * 版本号: 1.0
 */
public class ProcessModel {
    private ProcessModel() {
    }

    private static class SingleHolder {
        private static final ProcessModel INSTANCE = new ProcessModel();
    }

    public static ProcessModel get() {
        return SingleHolder.INSTANCE;
    }

    /**
     * 机械通风列表
     */
    public void getProcessList(int page, String type, final DataCallback<List<AerationBean>> callBack) {
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page);
        map.put("pageSize", 10);

        Map<String, Object> condition = new HashMap();
        condition.put("type", type);// 类型
        condition.put("houseId", HouseModel.get().getSelectHouse().houseCode);// 仓房id
        condition.put("depotId", DepotModel.get().getSelectDepot().depotCode);// 库id
        map.put("condition", gson.toJson(condition));

        PostRequest<String> request = OkGo.post(UrlPath.process_list);
        request.upJson(gson.toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response.body());
                JSONObject object = new JSONObject(json);
                String records = object.getString("records");
                List<AerationBean> list = new Gson().fromJson(records,
                        new TypeToken<List<AerationBean>>() {
                        }.getType());
                callBack.onSuccess(list);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }


    /**
     * 获取流程和选项
     */
    public void getProcessAll(String type, final DataCallback<List<ProcessListBean>> callBack) {
        GetRequest<String> request = OkGo.get(UrlPath.process_all + "/" + type);
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response);
                List<ProcessListBean> list =
                        new Gson().fromJson(json, new TypeToken<List<ProcessListBean>>() {
                        }.getType());
                callBack.onSuccess(list);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 获取审批流程
     */
    public void getApproveAll(String type, final DataCallback<List<DetailApproveBean>> callBack) {
        UserBean user = UserModel.get().getUser();
        String id = user.getUid().toString();
        String depotId = DepotModel.get().getSelectDepot().depotCode;
        String url = UrlPath.approve_all + "/" + type + "/" + id + "/" + depotId;
        GetRequest<String> request = OkGo.get(url);
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response);
                List<DetailApproveBean> list =
                        new Gson().fromJson(json, new TypeToken<List<DetailApproveBean>>() {
                        }.getType());
                callBack.onSuccess(list);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 增加记录
     *
     * @param callBack
     */
    public void add(
            List<Map<String, Object>> subList,
            String type,
            String houseId,
            String depotId,
            String fromPeople,
            String applyPeople,
            String ongoingStep,
            final DataCallback<String> callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("subList", subList);// 流程选项
        map.put("type", type);// 流程类型(如:tf）
        map.put("houseId", Integer.parseInt(houseId));// 仓房id
        map.put("depotId", Integer.parseInt(depotId));// 库id
        map.put("fromPeople", Integer.parseInt(fromPeople));// 提交人
//        map.put("toPeople", Integer.parseInt(fromPeople));// 审批人
        map.put("applyPeople", Integer.parseInt(applyPeople));// 申请人
        map.put("ongoingStep", ongoingStep);// 当前流程索引值
        map.put("auditTime", DateTool.formatDate(new Date(), DateTool.YTDTD_DATE));// 审批时间
        map.put("applyTime", DateTool.formatDate(new Date(), DateTool.YTDTD_DATE));// 申请时间
        PostRequest<String> request = OkGo.post(UrlPath.process_add);
        request.upJson(new Gson().toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                callBack.onSuccess(null);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 修改机械通风
     */
    public void update(
            List<Map<String, Object>> subList,
            String auditState,
            String type,
            String processId,
            String ongoingStep,
            final DataCallback<String> callBack) {

        Map<String, Object> map = new HashMap<>();
        // 流程id
        map.put("processId", processId);
        // 流程类型(如:tf）
        map.put("type", type);
        // 流程选项
        map.put("subList", subList);
        // 审批状态(0:提交,1审批通过:,2:审批不通过，3:审批完成进行中，4已完成）
        map.put("auditState", Integer.parseInt(auditState));
        // 进行到哪一步的流程索引
        map.put("ongoingStep", ongoingStep);
        PostRequest<String> request = OkGo.post(UrlPath.process_update);
        request.upJson(new Gson().toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                callBack.onSuccess(null);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 查询详情数据
     */
    public void getDetail(String processId, final DataCallback<ProcessDetailBean> callBack) {
        GetRequest<String> request = OkGo.get(UrlPath.process_detail + "/" + processId);
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response);
                callBack.onSuccess(new Gson().fromJson(json, ProcessDetailBean.class));
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }


    /**
     * 已发起列表
     */
    public void getApplyList(int page, final DataCallback<List<AerationBean>> callBack) {
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page);
        map.put("pageSize", 10);
        Map<String, Object> condition = new HashMap();
        condition.put("userId", UserModel.get().getUser().getUid());// 用户id
        map.put("condition", gson.toJson(condition));

        PostRequest<String> request = OkGo.post(UrlPath.todo_apply_list);
        request.upJson(gson.toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response.body());
                JSONObject object = new JSONObject(json);
                String records = object.getString("records");
                List<AerationBean> list = new Gson().fromJson(records,
                        new TypeToken<List<AerationBean>>() {
                        }.getType());
                callBack.onSuccess(list);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 待处理列表
     */
    public void getTodoList(int page, final DataCallback<List<AerationBean>> callBack) {
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page);
        map.put("pageSize", 10);
        Map<String, Object> condition = new HashMap();
        condition.put("userId", UserModel.get().getUser().getUid());// 用户id
        condition.put("startTime", "");
        condition.put("endTime", "");
        map.put("condition", gson.toJson(condition));

        PostRequest<String> request = OkGo.post(UrlPath.todo_list);
        request.upJson(gson.toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response.body());
                JSONObject object = new JSONObject(json);
                String records = object.getString("records");
                List<AerationBean> list = new Gson().fromJson(records,
                        new TypeToken<List<AerationBean>>() {
                        }.getType());
                callBack.onSuccess(list);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 待处理 数量
     */
    public void getTodoCount(final DataCallback<Integer> callBack) {
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", 1);
        map.put("pageSize", 10);
        Map<String, Object> condition = new HashMap();
        condition.put("userId", UserModel.get().getUser().getUid());// 用户id
        condition.put("startTime", "");
        condition.put("endTime", "");
        map.put("condition", gson.toJson(condition));
        PostRequest<String> request = OkGo.post(UrlPath.todo_list);
        request.upJson(gson.toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response.body());
                JSONObject object = new JSONObject(json);
                int total = object.optInt("total", 0);
                callBack.onSuccess(total);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 已处理列表
     */
    public void getFinishList(int page, final DataCallback<List<AerationBean>> callBack) {
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page);
        map.put("pageSize", 10);
        Map<String, Object> condition = new HashMap();
        condition.put("userId", UserModel.get().getUser().getUid());// 用户id
        map.put("condition", gson.toJson(condition));

        PostRequest<String> request = OkGo.post(UrlPath.todo_finish_list);
        request.upJson(gson.toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response.body());
                JSONObject object = new JSONObject(json);
                String records = object.getString("records");
                List<AerationBean> list = new Gson().fromJson(records,
                        new TypeToken<List<AerationBean>>() {
                        }.getType());
                callBack.onSuccess(list);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 审批
     */
    public void audit(String id,
                      String auditState,
                      String ongoingStep,
                      final DataCallback<String> callBack) {

        Map<String, Object> map = new HashMap<>();
        // 通风id
        map.put("id", Integer.parseInt(id));
        // 审批状态 1=通过 2=不通过
        map.put("auditState", Integer.parseInt(auditState));
        // 审批时间
        map.put("auditTime", DateTool.formatDate(new Date(), DateTool.YTDTD_DATE));
        // 流程索引
        map.put("ongoingStep", ongoingStep);

        PostRequest<String> request = OkGo.post(UrlPath.process_audit);
        request.upJson(new Gson().toJson(map));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                callBack.onSuccess(null);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callBack.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 处理待办状态
     *
     * @param todoId 待办ID
     */
    public void setTodoManageById(String todoId, String auditState, final DataCallback<String> callback) {
        GetRequest<String> request = OkGo.get(UrlPath.todo_manage + "/" + todoId + "/" + auditState);
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                callback.onSuccess(null);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callback.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 处理待办状态
     */
    public void setTodoManage(String type, String auditState, final DataCallback<String> callback) {
        String uid = UserModel.get().getUser().getUid().toString();
        String depotId = DepotModel.get().getSelectDepot().depotCode;
        String houseId = HouseModel.get().getSelectHouse().houseCode;
        StringBuilder sb = new StringBuilder();
        sb.append(UrlPath.todo_manage)
                .append("/")
                .append(uid)
                .append("/")
                .append(type)
                .append("/")
                .append(depotId)
                .append("/")
                .append(houseId)
                .append("/")
                .append(auditState);
        GetRequest<String> request = OkGo.get(sb.toString());
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                callback.onSuccess(null);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callback.onError(getErrorMsg(response));
            }
        });
    }


    /**
     * 将待办置为已办理
     */
    public void setTodo(String houseId, String tab, String auditState) {
        String type = tab;
        switch (tab) {
            case "保管员每周检查粮情":
                type = "code0";
                break;
            case "主管科长每2周检查粮情":
                type = "code2";
                break;
            case "分管副总每月检查粮情":
                type = "code5";
                break;
            case "总经理每季检查粮情":
                type = "code8";
                break;
        }

        AerationBean selectTodo = ProcessModel.get().getSelectTodo();
        // 类型一致 仓房一致
        if (selectTodo != null && type.equals(selectTodo.getType()) && houseId.equals(selectTodo.getHouseId())) {
            // 指定ID的待办改为已处理
            ProcessModel.get().setTodoManageById(selectTodo.getId(), auditState, new DataCallback<String>() {
                @Override
                public void onSuccess(String data) {
                    // 刷新待办列表
                    EventBus.getDefault().post(new TodoEvent());
                }
            });
            SPTool.remove(Constant.KEY_SELECT_TODO);
        } else {
            // 将最新的待办为已处理
            ProcessModel.get().setTodoManage(type, auditState, new DataCallback<String>() {
                @Override
                public void onSuccess(String data) {
                    // 刷新待办列表
                    EventBus.getDefault().post(new TodoEvent());
                }
            });
        }
    }

    /**
     * 保存要处理的待办
     */
    public void saveSelectTodo(AerationBean bean) {
        SPTool.saveString(Constant.KEY_SELECT_TODO, new Gson().toJson(bean));
    }

    /**
     * 获取要处理的待办
     */
    public AerationBean getSelectTodo() {
        String json = SPTool.getString(Constant.KEY_SELECT_TODO, null);
        if (json != null) {
            return new Gson().fromJson(json, AerationBean.class);
        }
        return null;
    }

    /**
     * 删除要处理的待办
     */
    public void removeSelectTodo() {
        SPTool.remove(Constant.KEY_SELECT_TODO);
    }
}
