package cn.axzo.msg.center.inside.notices.service.impl.v3;

import cn.axzo.basics.common.BeanMapper;
import cn.axzo.basics.profiles.api.UserProfileServiceApi;
import cn.axzo.basics.profiles.dto.basic.PersonProfileDto;
import cn.axzo.msg.center.api.request.v3.SearchMessageReqV3;
import cn.axzo.msg.center.api.response.v3.SearchMessageRespV3;
import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.axzo.msg.center.dal.MessageRecordV3Dao;
import cn.axzo.msg.center.domain.entity.MessageRecordV3;
import cn.azxo.framework.common.model.CommonResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author yanglin
 */
@Component
@RequiredArgsConstructor
public class MessageRecordServiceV3 {

    private final MessageRecordV3Dao messageRecordV3Dao;
    private final UserProfileServiceApi userProfileServiceApi;

    public List<SearchMessageRespV3> search(SearchMessageReqV3 req) {
        if (req.getLimit() >= 100) {
            req.setLimit(100);
        }
        if (req.getReceiverPersonId() == null && StringUtils.isNotBlank(req.getReceiverPhone())) {
            CommonResponse<PersonProfileDto> profileResp = userProfileServiceApi
                    .getUnionPersonProfile(null, req.getReceiverPhone());
            PersonProfileDto personProfile = BizAssertions.assertResponse(profileResp, "未找根据手机找到人员");
            BizAssertions.assertNotNull(personProfile, "未找根据手机找到人员");
            req.setReceiverPersonId(personProfile.getId());
        }
        List<MessageRecordV3> records = messageRecordV3Dao.lambdaQuery()
                .eq(req.getReceiverOuId() != null, MessageRecordV3::getReceiverOuId, req.getReceiverOuId())
                .eq(req.getReceiverPersonId() != null, MessageRecordV3::getReceiverPersonId, req.getReceiverPersonId())
                .eq(StringUtils.isNotBlank(req.getBizEventMappingCode()), MessageRecordV3::getBizEventMappingCode, req.getBizEventMappingCode())
                .eq(StringUtils.isNotBlank(req.getBizCode()), MessageRecordV3::getBizCode, req.getBizCode())
                .eq(StringUtils.isNotBlank(req.getTemplateCode()), MessageRecordV3::getTemplateCode, req.getTemplateCode())
                .like(StringUtils.isNotBlank(req.getTitle()), MessageRecordV3::getTitle, req.getTitle())
                .like(StringUtils.isNotBlank(req.getContent()), MessageRecordV3::getContent, req.getContent())
                .ge(req.getStartTime() != null, MessageRecordV3::getCreateAt, req.getStartTime())
                .le(req.getEndTime() != null, MessageRecordV3::getCreateAt, req.getEndTime())
                .orderByDesc(MessageRecordV3::getId)
                .last("LIMIT " + req.getLimit())
                .list();
        return BeanMapper.copyList(records, SearchMessageRespV3.class);
    }

}
