package com.tiesheng.core.service;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.tiesheng.core.config.web.TieshengWebConfigurer;
import com.tiesheng.core.config.web.bean.CurrentWebUser;
import com.tiesheng.core.mapper.CoreLogLoginMapper;
import com.tiesheng.core.mapper.CoreLogOperationMapper;
import com.tiesheng.core.pojos.dao.CoreLogLogin;
import com.tiesheng.core.pojos.dao.CoreLogOperation;
import com.tiesheng.core.pojos.dao.CorePlatformUnique;
import com.tiesheng.util.ServletKit;
import com.tiesheng.util.ip2region.DataBlock;
import com.tiesheng.util.ip2region.Ip2Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hao
 */
@Service
public class CoreLogService extends TsServiceBase<CoreLogOperationMapper, CoreLogOperation> {

    @Autowired
    TieshengWebConfigurer tieshengWebConfigurer;
    @Autowired
    CoreLogLoginMapper coreLogLoginMapper;

    public CoreLogLoginMapper getLogLoginMapper() {
        return coreLogLoginMapper;
    }

    ///////////////////////////////////////////////////////////////////////////
    // 操作日志
    ///////////////////////////////////////////////////////////////////////////


    /**
     * 添加操作日志
     */
    public void addOperationLog(String title, String subject, Object params) {
        CoreLogOperation operation = new CoreLogOperation();
        CurrentWebUser currentWebUser = tieshengWebConfigurer.getCurrentUserName();
        operation.setUserId(currentWebUser.getId());
        operation.setUserName(currentWebUser.getName());
        operation.setTitle(title);
        operation.setSubject(subject);
        if (params != null) {
            operation.setParams(JSONUtil.toJsonStr(params));
        }
        save(operation);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 登录日志
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 添加登录日志
     *
     * @param platformUnique
     */
    public void addLoginLog(CorePlatformUnique platformUnique) {

        HttpServletRequest request = ServletKit.getRequest();
        String ip = ServletUtil.getClientIP(request);


        CoreLogLogin login = new CoreLogLogin();
        login.setUserId(platformUnique.getUserId());
        login.setPlatform(platformUnique.getPlatform());

        CurrentWebUser currentWebUser = tieshengWebConfigurer.getCurrentUserName();
        login.setUserName(currentWebUser.getName());

        login.setIp(ip);
        DataBlock dataBlock = Ip2Region.getInstance().btreeSearch(ip);
        login.setAddress(dataBlock.getRegion());
        coreLogLoginMapper.insert(login);
    }


}
