package com.czg.service.account.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.czg.account.dto.AcUserMsgDTO;
import com.czg.account.entity.AcUserMsg;
import com.czg.account.service.AcUserMsgService;
import com.czg.sa.StpKit;
import com.czg.service.account.mapper.AcUserMsgMapper;
import com.czg.utils.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.List;

/**
 * 服务层实现。
 *
 * @author gyj
 * @since 2025-12-09
 */
@DubboService
public class AcUserMsgServiceImpl extends ServiceImpl<AcUserMsgMapper, AcUserMsg> implements AcUserMsgService {

    @Override
    public void addUserMsg(AcUserMsg msg) {
        save(msg);
    }

    @Override
    public Long getUnReadCount() {
        return count(QueryWrapper.create().eq(AcUserMsg::getReadStatus, 0).eq(AcUserMsg::getUserId, StpKit.USER.getLoginIdAsLong()));
    }

    @Override
    public Page<AcUserMsgDTO> getUserMsgPage() {
        long userId = StpKit.USER.getLoginIdAsLong();
        ThreadUtil.execAsync(() -> {
//            AcUserMsg msg = new AcUserMsg();
//            msg.setReadStatus(1);
//            update(msg, QueryWrapper.create().eq(AcUserMsg::getUserId, userId).eq(AcUserMsg::getReadStatus, 0));
//
            updateChain().set(AcUserMsg::getReadStatus, 1)
                    .eq(AcUserMsg::getUserId, userId)
                    .eq(AcUserMsg::getReadStatus, 0)
                    .update();
        });
        return pageAs(PageUtil.buildPage(), QueryWrapper.create().eq(AcUserMsg::getUserId,
                userId).orderBy(AcUserMsg::getCreateTime, false), AcUserMsgDTO.class);
    }

    @Override
    public List<AcUserMsgDTO> getMsgListByOrderId(Long orderId) {
        return listAs(QueryWrapper.create().eq(AcUserMsg::getSourceId, orderId)
                        .eq(AcUserMsg::getSourceType, "order").ne(AcUserMsg::getTitle, "积分扣除"),
                AcUserMsgDTO.class);
    }
}
