package com.corewing.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corewing.app.dto.AccessStatisticsRequest;
import com.corewing.app.entity.AppAccessStatistics;
import com.corewing.app.mapper.AppAccessStatisticsMapper;
import com.corewing.app.service.AppAccessStatisticsService;
import com.corewing.app.util.CommonIpAddressUtil;
import com.corewing.app.util.CommonServletUtil;
import com.corewing.app.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AppAccessStatisticsServiceImpl extends ServiceImpl<AppAccessStatisticsMapper, AppAccessStatistics> implements AppAccessStatisticsService {

    @Override
    public boolean accumulate(AccessStatisticsRequest accessStatisticsRequest) {

        AppAccessStatistics appAccessStatistics = new AppAccessStatistics();
        if(StpUtil.isLogin()) {
            Object loginId = StpUtil.getLoginId();
            if(loginId != null) {
                appAccessStatistics.setUserId(Long.parseLong(loginId.toString()));
            }
        }

        if(StrUtil.isNotBlank(accessStatisticsRequest.getVisitPage())) {
            appAccessStatistics.setVisitPage(accessStatisticsRequest.getVisitPage());
        }
        if(StrUtil.isNotBlank(accessStatisticsRequest.getAccessType())) {
            appAccessStatistics.setAccessType(accessStatisticsRequest.getAccessType());
        }
        appAccessStatistics.setAccessDevice(accessStatisticsRequest.getAccessDevice());
        appAccessStatistics.setAccessIp(IpUtil.getClientIp(CommonServletUtil.getRequest()));
        appAccessStatistics.setAccessAddress(CommonIpAddressUtil.getCityInfo(appAccessStatistics.getAccessIp()));
        try {
            // 解析设备型号
            JSONObject parse = JSONUtil.parseObj(appAccessStatistics.getAccessDevice());
            appAccessStatistics.setDeviceModel(parse.getStr("model"));
            appAccessStatistics.setDeviceBrand(parse.getStr("brand"));
            appAccessStatistics.setDeviceSystem(parse.getStr("system"));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return save(appAccessStatistics);
    }
}
