package com.fufan.mtsaas.util;

import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.plugins.Page;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.dao.TSysParamDao;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.model.TSysParam;
import com.fufan.mtsaas.modules.sysmgr.common.tocken.LoginTokenBO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 接收数据进行转换
 *
 * @author Liby
 * @version 1.0
 * @date 2018-7-31
 */
@Slf4j
@Component
public class ParamUtil {
//    @Autowired
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private HttpServletRequest httpServletRequest;
    private static Pattern linePattern = Pattern.compile("_(\\w)");

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    private static int QUERY_PAGESIZE;

    @Value("${QUERY_PAGESIZE}")

    public void setPageSize(int pageSize) {
        QUERY_PAGESIZE = pageSize;
    }

    public int getPageSize() {
        return QUERY_PAGESIZE;
    }

    private static String COMPANY_CD;

    @Value("${COMPANY_CD}")

    public void setCompanyID(String CompanyID) {
        COMPANY_CD = CompanyID;
    }

    public String getCompanyID() {
        return COMPANY_CD;
    }

    @Autowired
    private TSysParamDao tsParamDao;

    public static RequestPojo doChange() {
        RequestPojo requestPojo = new RequestPojo();
        try {
            requestPojo.setIp(getIpAddress(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()));
            String str = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("Authorization");
            if (StringUtils.isBlank(str)) {
                return requestPojo;
            }
            str = str.replace("Bearer","").trim();
            LoginTokenBO loginTokenBO = JwtUtil.parseTokenBO(str);
            requestPojo.setAppKey(loginTokenBO.getAppKey());
            requestPojo.setSysId(loginTokenBO.getSysId());
            requestPojo.setCustId(loginTokenBO.getCompanyId());
            requestPojo.setStaffId(loginTokenBO.getUserId());
            requestPojo.setCreateTime(loginTokenBO.getStartTime());
            requestPojo.setUserName(loginTokenBO.getUserName());
            requestPojo.setRoleId(loginTokenBO.getRoleId());
        }catch (Exception e){

        }
//        RequestPojo requestPojo = JSON.parseObject(str).toJavaObject(RequestPojo.class);
        return requestPojo;
    }
    public static String getIpAddress(HttpServletRequest httpServletRequest) {

        String ip = httpServletRequest.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("x-real-ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getRemoteAddr();
            if ("127.0.0.1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.warn(e.toString());
                }
            }
        }
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    //设置分页参数

    /**
     * mybatis设置分页参数
     * Liby 2022-03-29
     * @param pageSize
     * @param current
     * @param page
     * @return
     */
    public static Page setPage(int pageSize, int current, Page page) {
        page.setSize(pageSize);
        page.setCurrent(current);
//        page.setSearchCount(true);

        com.github.pagehelper.PageHelper.startPage(page.getCurrent(), page.getSize(), true);

        return page;
    }

    //设置分页参数
    public static Map<String, String> setPage(Map<String, String> map, Page page) {
        //参数读取配置
        if(Objects.nonNull(QUERY_PAGESIZE) && QUERY_PAGESIZE > 0){
            Map<String, String> map1 = map;
            page.setSize(QUERY_PAGESIZE);
            if(Objects.nonNull(map) && !StringUtils.isEmpty( ParamUtil.getParamfromMap(map,"pageSize"))) {

                JSONObject hs1 = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data");
                JSONObject hs2 = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param");
                hs2.put("pageSize", QUERY_PAGESIZE);
                page.setCurrent(Integer.parseInt(ParamUtil.getParamfromMap(map, "currentPage")));
                hs1.put("param", hs2);
                map1.put("data", JSonUtil.toJSONString(hs1));
                map = map1;
            }
            return map;
        }

        if (!StringUtils.isEmpty( ParamUtil.getParamfromMap(map,"pageSize"))
                && !StringUtils.isEmpty( ParamUtil.getParamfromMap(map,"currentPage"))) {
            page.setSize(Integer.parseInt( ParamUtil.getParamfromMap(map, "pageSize")));
            page.setCurrent(Integer.parseInt( ParamUtil.getParamfromMap(map, "currentPage")));
        }else{
            page.setSize(-1);
            page.setCurrent(-1);
        }

        return map;
    }


    /**
     * 下划线转驼峰
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线效率比上面高
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    //判断校验结果,并设置返回错误参数
    public static Boolean check(Result result, String... checkResult) {
        if (areEmpty(checkResult)) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL_MSG);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return true;
        }
        return false;
    }

    //判断结果集是否为空
    public static boolean areEmpty(String... values) {
        boolean result = false;
        if (values == null || values.length == 0) {
            return result;
        } else {
            for (String value : values) {
                result |= StringUtils.isNotEmpty(value);
            }
        }
        return result;

    }

    /**
     * 转换对象
     * Liby 2019-08-22
     * @param map
     * @return
     */
    public static Map<String, String> convertParamToMap(Map<String, String> map) {
        String mapRe = "";
        try {
            mapRe = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").toString();
        } catch (Exception e) {
            log.debug("convertParamToMap get param object is not found.");
        }

        JSONObject jsonObject = JSONObject.parseObject(mapRe);
        Map<String, String> mapData = null;
        try {
            mapData = (Map) jsonObject;
        }catch (Exception e){
            log.error("convertParamToMap converting object error : {}", e);
        }
        log.debug("convertParamToMap converting object : {}", mapData);

        //赋值默认
        if(StringUtils.isEmpty(mapData.get("CompanyID"))){
            mapData.put("CompanyID", COMPANY_CD);
        }

        return mapData;
    }

    /**
     * 从Metadata获取对象
     * Liby 2019-11-05
     * @param map
     * @return
     */
    public static String getMetadatafromMap(Map<String, String> map, String strKey) {
        String mapRe = null;

        try {
            mapRe = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("metdata").get(strKey).toString();
        }catch (Exception e){
            log.debug("getMetadatafromMap get {} parameter is not found.", strKey);
        }

        return mapRe;
    }

    /**
     * 从Metadata获取对象
     * Liby 2019-10-02
     * @param map
     * @return
     */
    public static String getMetadatafromObject(String map, String strKey) {
        String mapRe = null;

        try {
            mapRe = JSON.parseObject(map).getJSONObject("data").getJSONObject("metdata").get(strKey).toString();
        }catch (Exception e){
            log.debug("getMetadatafromObject get {} parameter is not found.", strKey);
        }

        return mapRe;
    }

    /**
     * 获取对象
     * Liby 2019-10-02
     * @param map
     * @return
     */
    public static String getParamfromMap(Map<String, String> map, String strKey) {
        String mapRe = null;

        try {
            mapRe = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get(strKey).toString();
        }catch (Exception e){
            log.debug("getParamfromMap get {} parameter is not found.", strKey);
        }

        return mapRe;
    }

    /**
     * 获取对象
     * Liby 2019-10-02
     * @param map
     * @return
     */
    public static String getParamfromObject(String map, String strKey) {
        String mapRe = null;

        try {
            mapRe = JSON.parseObject(map).getJSONObject("data").getJSONObject("param").get(strKey).toString();
        }catch (Exception e){
            log.debug("getParamfromMap get {} parameter is not found.", strKey);
        }

        return mapRe;
    }

    /**
     * 获取对象
     * Liby 2019-10-02
     * @param map
     * @return
     */
    public static String getParamfromObjectWithoutData(String map, String strKey) {
        String mapRe = null;

        try {
            mapRe = JSON.parseObject(map).getJSONObject("param").get(strKey).toString();
        }catch (Exception e){
            log.debug("getParamfromObjectWithoutData get {} parameter is not found.", strKey);
        }

        return mapRe;
    }

    /**
     * 获取对象
     * Liby 2019-10-02
     * @param map
     * @return
     */
    public static String getMetadatafromObjectWithoutData(String map, String strKey) {
        String mapRe = null;

        try {
            mapRe = JSON.parseObject(map).getJSONObject("metdata").get(strKey).toString();
        }catch (Exception e){
            log.debug("getMetadatafromObjectWithoutData get {} parameter is not found.", strKey);
        }

        return mapRe;
    }
    public boolean verifyToken(){
        boolean verify = false;
        try {
            RequestPojo requestPojo = doChange();
            if (Objects.isNull(requestPojo.getSysId()) || StringUtils.isEmpty(requestPojo.getCustId())) {
                return false;
            }
            if(System.currentTimeMillis() < requestPojo.getCreateTime() + 1000 * 60 * 60){
                LoginTokenBO loginTokenBO = new LoginTokenBO();
                loginTokenBO.setSysId(requestPojo.getSysId());
                loginTokenBO.setUserId(requestPojo.getStaffId());
                loginTokenBO.setUserName(requestPojo.getUserName());
                loginTokenBO.setAppKey("erthetitrjeoitjeotjeo");
                loginTokenBO.setCompanyId(requestPojo.getCustId());
                loginTokenBO.setRoleId(requestPojo.getRoleId());
                String token = JwtUtil.createToken(loginTokenBO);
                stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_TOKEN + ":" + requestPojo.getCustId() + ":"+ loginTokenBO.getUserId(),token,60, TimeUnit.MINUTES);
                return true;
            }else {
                if(stringRedisTemplate.hasKey(RedisKeyConstant.USER_TOKEN + ":" + requestPojo.getCustId() + ":"+ requestPojo.getStaffId())){
                    LoginTokenBO loginTokenBO = new LoginTokenBO();
                    loginTokenBO.setUserId(requestPojo.getStaffId());
                    loginTokenBO.setSysId(requestPojo.getSysId());
                    loginTokenBO.setUserName(requestPojo.getUserName());
                    loginTokenBO.setAppKey("erthetitrjeoitjeotjeo");
                    loginTokenBO.setCompanyId(requestPojo.getCustId());
                    loginTokenBO.setRoleId(requestPojo.getRoleId());
                    String token = JwtUtil.createToken(loginTokenBO);
                    stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_TOKEN + ":" + requestPojo.getCustId() + ":"+ loginTokenBO.getUserId(),token,60, TimeUnit.MINUTES);
                    return true;
                }else {
                    return false;
                }
            }
        }catch (Exception e){
            log.error("token 校验失败");
        }
      return verify;
    }

    /**
     * 获取系统参数
     *
     * @param paramName
     * @return
     */
    public String getTSysParam(String paramName) {
        String retVal = null;
        TSysParam tsParam = new TSysParam();
        tsParam.setParamName(paramName);
        try {
            TSysParam info = tsParamDao.selectOne(tsParam);
            if (Objects.nonNull(info)) {
                retVal = info.getParamValue();
            }
        } catch (Exception e) {
            log.error("getTSysParam (" + paramName + ") exception: " + e.getLocalizedMessage());
        }
        return retVal;
    }

    /**
     * 更新参数值
     *
     * @param paramName
     * @param value
     * @return
     */
    public int updateParam(String paramName, String value) {
        int retVal = 0;
        TSysParam tsParam = new TSysParam();
        tsParam.setParamName(paramName);
        try {
            TSysParam entity = new TSysParam();
            entity.setParamName(paramName);
            entity.setParamValue(value);
            retVal = tsParamDao.updateByKey(entity);
        } catch (Exception e) {
            log.error("getTSysParam (" + paramName + ") exception: " + e.getLocalizedMessage());
        }
        return retVal;
    }


    public static void main(String[] args) {
        System.out.println(humpToLine("statisticsDate"));
    }

}
