package cn.iocoder.yudao.module.crm.service.crmoperatelog;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.crm.controller.admin.crmoperatelog.vo.CrmOperatelogPageReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.crmoperatelog.CrmOperatelogDO;
import cn.iocoder.yudao.module.crm.dal.mysql.crmoperatelog.CrmOperatelogMapper;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

/**
 * 操作日志 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class CrmOperatelogServiceImpl implements CrmOperatelogService {

    @Resource
    private CrmOperatelogMapper crmOperatelogMapper;
    @Resource
    private AdminUserApi adminUserApi;


    @Override
    public void createLog(String title, Long customerId, Long contractId, Long receivableId) {
        String nickname = "";
        if (SecurityFrameworkUtils.getLoginUser() != null) {
            CommonResult<AdminUserRespDTO> result = adminUserApi.getUser(SecurityFrameworkUtils.getLoginUser().getId());
            if (result.isSuccess() && result.getCheckedData() != null) {
                nickname = result.getCheckedData().getNickname();
            }
        }
        CrmOperatelogDO crmOperatelogDO = CrmOperatelogDO.builder()
                .title(title)
                .customerId(customerId)
                .contractId(contractId)
                .receivableId(receivableId)
                .ip(ServletUtils.getClientIP())
                .useragent(ServletUtils.getUserAgent())
                .url(ServletUtils.getUrl())
                .nickname(nickname)
                .username(nickname)
                .build();

        crmOperatelogMapper.insert(crmOperatelogDO);
    }


    @Override
    public PageResult<CrmOperatelogDO> getOperatelogPage(CrmOperatelogPageReqVO pageReqVO) {
        return crmOperatelogMapper.selectPage(pageReqVO);
    }
}
