package cn.iocoder.yudao.module.system.service.notify;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum;
import cn.iocoder.yudao.module.system.api.bpm.vo.BpmBusinessFormRespVO;
import cn.iocoder.yudao.module.system.controller.admin.notify.vo.message.NotifyBpmCountVO;
import cn.iocoder.yudao.module.system.controller.admin.notify.vo.message.NotifyMessageMyPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.notify.vo.message.NotifyMessagePageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.notify.NotifyMessageDO;
import cn.iocoder.yudao.module.system.dal.dataobject.notify.NotifyTemplateDO;
import cn.iocoder.yudao.module.system.dal.mysql.notify.NotifyMessageMapper;
import cn.iocoder.yudao.module.system.enums.notice.NotieBusinessTypeEnum;
import cn.iocoder.yudao.module.system.enums.notice.NotifyTypeEnum;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.module.system.enums.LogRecordConstants.*;

/**
 * 站内信 Service 实现类
 *
 * @author xrcoder
 */
@Service
@Validated
public class NotifyMessageServiceImpl implements NotifyMessageService {

    @Resource
    private NotifyMessageMapper notifyMessageMapper;


    @Override
    public Long createNotifyMessage(Long userId, Integer userType,
                                    NotifyTemplateDO template, String templateContent, Map<String, Object> templateParams) {
        NotifyMessageDO message = new NotifyMessageDO().setUserId(userId).setUserType(userType)
                .setTemplateId(template.getId()).setTemplateCode(template.getCode())
                .setTemplateType(template.getType()).setTemplateNickname(template.getNickname())
                .setTemplateContent(templateContent).setTemplateParams(templateParams).setReadStatus(false);
        notifyMessageMapper.insert(message);
        return message.getId();
    }

    @Override
    public PageResult<NotifyMessageDO> getNotifyMessagePage(NotifyMessagePageReqVO pageReqVO) {
        return notifyMessageMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<NotifyMessageDO> getMyMyNotifyMessagePage(NotifyMessageMyPageReqVO pageReqVO, Long userId, Integer userType) {
        return notifyMessageMapper.selectPage(pageReqVO, userId, userType);
    }

    @Override
    public NotifyMessageDO getNotifyMessage(Long id) {
        return notifyMessageMapper.selectById(id);
    }

    @Override
    public List<NotifyMessageDO> getUnreadNotifyMessageList(Long userId, Integer userType, Integer size) {
        return notifyMessageMapper.selectUnreadListByUserIdAndUserType(userId, userType, size);
    }

    @Override
    public Long getUnreadNotifyMessageCount(Long userId, Integer userType) {
        return notifyMessageMapper.selectUnreadCountByUserIdAndUserType(userId, userType);
    }

    @Override
    public int updateNotifyMessageRead(Collection<Long> ids, Long userId, Integer userType) {
        return notifyMessageMapper.updateListRead(ids, userId, userType);
    }

    @Override
    public int updateAllNotifyMessageRead(Long userId, Integer userType) {
        return notifyMessageMapper.updateListRead(userId, userType);
    }

    @Override
    public Long getUncompletedMessageCount(Long userId, Integer userType) {
        return notifyMessageMapper.getUncompletedMessageCount(userId, userType);
    }

    @Override
    @TenantIgnore
    public NotifyBpmCountVO getBpmListCount(Long loginUserId, Integer userType, Integer queryType) {
        NotifyBpmCountVO notifyBpmCountVO = new NotifyBpmCountVO();
        Integer businessType = NotieBusinessTypeEnum.BPM.getValue();
//        Integer notifyType = NotifyTypeEnum.NOTIFY_TODO.getValue();
        Integer completedStatus = CommonStatusEnum.ENABLE.getStatus();
        Integer readStatus = CommonStatusEnum.ENABLE.getStatus();
        Integer status = BpmProcessInstanceStatusEnum.RUNNING.getStatus();
        if (0 == queryType) {
            Long  homeCount = notifyMessageMapper.selectMyBpmCount(loginUserId, null ,userType, businessType,
                    null, completedStatus, status, null,queryType);
            notifyBpmCountVO.setTodoCount(homeCount);
        } else {


            Long  todoCount = notifyMessageMapper.selectMyBpmCount(loginUserId, null ,userType, businessType,
                    null, completedStatus, status, null, queryType);
            Long  myCreateCount = notifyMessageMapper.selectMyBpmCount(loginUserId, null ,userType, businessType,
                    null, null, BpmProcessInstanceStatusEnum.REJECT.getStatus(), CommonStatusEnum.ENABLE.getStatus(),queryType);
            notifyBpmCountVO.setTodoCount(todoCount);
            notifyBpmCountVO.setMyCreateCount(myCreateCount);
        }


        Integer notifyType = NotifyTypeEnum.NOTIFY_COPY.getValue();
        Long  copyCount = notifyMessageMapper.selectMyCopyCount(loginUserId, userType, businessType,
                notifyType, completedStatus, readStatus);



        notifyBpmCountVO.setCopyCount(copyCount);
        return notifyBpmCountVO;
    }

    @Override
    @TenantIgnore
    @LogRecord(type = NOTIFY_MESSAGE_TYPE, subType = NOTIFY_MESSAGE_UPDATE_READ_TYPE, bizNo = "{{#id}}",
            success = NOTIFY_MESSAGE_UPDATE_READ_SUCCESS)
    public int updateReadById(Long id, Long loginUserId, Integer userType) {
        NotifyMessageDO notifyMessageDO = notifyMessageMapper.selectById(id);
        LogRecordContext.putVariable("nickname", SecurityFrameworkUtils.getLoginUserNickname());
        LogRecordContext.putVariable("templateContent", notifyMessageDO.getTemplateContent());
        if (NotifyTypeEnum.NOTIFY_READ.getValue().equals(notifyMessageDO.getNotifyType())) {
            // 完成代办消息
            return  notifyMessageMapper.updateCompletedStatusById(id, userType, LocalDateTime.now(),
                    1, CommonStatusEnum.ENABLE.getStatus());
        }
        return notifyMessageMapper.updateReadById(id, userType, LocalDateTime.now());
    }

    @Override
    @TenantIgnore
    @LogRecord(type = NOTIFY_MESSAGE_TYPE, subType = NOTIFY_MESSAGE_UPDATE_READ_TYPE, bizNo = "{{#processInstanceId}}",
            success = NOTIFY_MESSAGE_UPDATE_READ_SUCCESS)
    public int updateMyCreateReadById(String processInstanceId, Long loginUserId) {
        BpmBusinessFormRespVO businessForm = notifyMessageMapper.selectBpmBusinessForm(processInstanceId);
        if (null != businessForm && (businessForm.getStatus() == BpmTaskStatusEnum.APPROVE.getStatus() ||
                businessForm.getStatus() == BpmTaskStatusEnum.REJECT.getStatus() ||
                businessForm.getStatus() == BpmTaskStatusEnum.CANCEL.getStatus())) {
            LocalDateTime now = LocalDateTime.now();
            notifyMessageMapper.update(new LambdaUpdateWrapper<NotifyMessageDO>()
                    .eq(NotifyMessageDO::getPkMessage, processInstanceId)
                    .eq(NotifyMessageDO::getCompletedStatus, 0)
                    .set(NotifyMessageDO::getReadTime, now)
                    .set(NotifyMessageDO::getReadStatus, 1)
                    .set(NotifyMessageDO::getCompletedTime, now)
                    .set(NotifyMessageDO::getCompletedStatus, 1));
        }
        return notifyMessageMapper.updateMyCreateReadById(processInstanceId);
    }
}
