package com.tzld.piaoquan.ad.engine.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tzld.piaoquan.ad.engine.commons.redis.AlgorithmRedisHelper;
import com.tzld.piaoquan.ad.engine.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    protected AlgorithmRedisHelper algRedisHelper;

    @Override
    public String getUserLayer4Level(String mid) {

        Map<String, String> userLayer = this.getUserLayer(mid);
        if (MapUtils.isEmpty(userLayer)) {
            return "无曝光";
        }

        return userLayer.getOrDefault("layer_l4", "无曝光");
    }

    @Override
    public Map<String, String> getUserLayer(String mid) {

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("layer", "无曝光");
        resultMap.put("layer_l4", "无曝光");
        resultMap.put("layer_l6", "无曝光");

        if (StringUtils.isEmpty(mid)) {
            return resultMap;
        }

        String key = String.format("ad:engine:mid:layer:%s", mid);
        String value = algRedisHelper.get(key);
        if (StringUtils.isEmpty(value)) {
            return resultMap;
        }

        try {
            Map<String, String> layerMap = JSON.parseObject(value, new TypeReference<Map<String, String>>() {
            });
            String layer3L = layerMap.getOrDefault("layer", "无曝光");
            if (StringUtils.equals(layer3L, "已转化")) {
                layer3L = "有转化";
            }

            Map<String, String> basic4lMap = JSON.parseObject(layerMap.getOrDefault("basic_l4", "{}"), new TypeReference<Map<String, String>>() {
            });

            String layer4L = basic4lMap.getOrDefault("level", "无曝光");


            resultMap.put("layer", layer3L);
            resultMap.put("layer_l4", layer4L);

            Map<String, String> basic6lMap = JSON.parseObject(layerMap.getOrDefault("basic_l6", "{}"), new TypeReference<Map<String, String>>() {
            });
            String layer6L = basic6lMap.getOrDefault("level", "无曝光");
            resultMap.put("layer_l6", layer6L);
            return resultMap;
        } catch (Exception e) {
            log.error("UserServiceImpl getUserLayer error: ", e);
        }

        return resultMap;
    }
}
