package com.engine.organization.util;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.engine.common.service.HrmCommonService;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.core.exception.ECException;
import com.engine.organization.exception.OrganizationRunTimeException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import weaver.general.BaseBean;
import weaver.hrm.User;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

@Slf4j
public class ResponseResult<T, R> {

    private static final long serialVersionUID = 1L;

    private User user;
    private boolean permission;

    HrmCommonService hrmCommonService = new HrmCommonServiceImpl();

    public ResponseResult(User user) {
        this.user = user;
    }

    private void permission() {
        if (permission) {
            List<Object> roleInfo = hrmCommonService.getRoleInfo(user.getUID());
            roleInfo.stream().map(m -> (Map) m).filter(m -> m.get("roleid") != null && m.get("roleid").toString().equals("28")).findFirst().orElseThrow(() -> new OrganizationRunTimeException("无权限"));
        }
    }

    /**
     * 统一返回方法
     */
    public static String run(Function<Map<String, Object>, Map<String, Object>> f, Map<String, Object> m) {
        BaseBean b = new BaseBean();
        try {
            b.writeLog(getJsonString(m));
            return Ok(f.apply(m));
        } catch (OrganizationRunTimeException e) {
            return Error(e.getMessage());
        } catch (ECException e) {
            b.writeLog(e);
            Throwable cause = e.getCause();
            return Error(cause.getMessage());
        } catch (Exception e) {
            b.writeLog(e);
            return Error(e.getMessage());
        }
    }

    /**
     * 成功返回
     */
    private static String Ok(Map<String, Object> map) {
        Map<String, Object> apidatas = new HashMap<>();
        apidatas.put("status", true);
        apidatas.put("data", map);
        return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 失败返回
     */
    private static String Error(String message) {
        Map<String, Object> apidatas = new HashMap<>();
        apidatas.put("status", false);
        apidatas.put("errormsg", message);
        return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 统一返回方法
     */
    public String run(Function<T, R> f, T m) {
        BaseBean b = new BaseBean();
        try {
            permission();
            b.writeLog(getJsonString(m));
            return Ok(f.apply(m));
        } catch (OrganizationRunTimeException e) {
            return Error(e.getMessage());
        } catch (ECException e) {
            b.writeLog(e);
            Throwable cause = e.getCause();
            return Error(cause.getMessage());
        } catch (Exception e) {
            b.writeLog(e);
            return Error(e.getMessage());
        }
    }

    /**
     * 统一返回方法（有参无返回）
     */
    public String run(Consumer<T> f, T t) {
        BaseBean b = new BaseBean();
        try {
            permission();
            f.accept(t);
            return Ok();
        } catch (OrganizationRunTimeException e) {
            return Error(e.getMessage());
        } catch (ECException e) {
            b.writeLog(e);
            Throwable cause = e.getCause();
            return Error(cause.getMessage());
        } catch (Exception e) {
            b.writeLog(e);
            return Error(e.getMessage());
        }
    }


    /**
     * 统一返回方法（无参有返回）
     */
    public String run(Supplier<R> f) {
        try {
            permission();
            return Ok(f.get());
        } catch (OrganizationRunTimeException e) {
            return Error(e.getMessage());
        } catch (ECException e) {
            BaseBean b = new BaseBean();
            b.writeLog(e);
            Throwable cause = e.getCause();
            return Error(cause.getMessage());
        } catch (Exception e) {
            BaseBean b = new BaseBean();
            b.writeLog(e);
            return Error(e.getMessage());
        }
    }

    /**
     * 成功返回
     */
    private String Ok(R r) {
        Map<String, Object> apidatas = new HashMap<>();
        apidatas.put("status", true);
        apidatas.put("data", r);
        return getJsonString(apidatas);
//        return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
    }

    private static String getJsonString(Object apidatas) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(apidatas);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 成功返回
     */
    private String Ok() {
        Map<String, Object> apidatas = new HashMap<>();
        apidatas.put("status", true);
        return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
    }

}
