package com.kym.service.miniapp.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.kym.entity.miniapp.InvoiceTitle;
import com.kym.mapper.miniapp.InvoiceTitleMapper;
import com.kym.service.miniapp.InvoiceTitleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@DS("db-miniapp")
public class InvoiceTitleServiceImpl extends MPJBaseServiceImpl<InvoiceTitleMapper, InvoiceTitle> implements InvoiceTitleService {

    @Override
    public List<InvoiceTitle> listByUser(Long userId) {
        return lambdaQuery()
                .eq(InvoiceTitle::getUserId, userId)
                .orderByDesc(InvoiceTitle::getIsDefault)
                .orderByDesc(InvoiceTitle::getUpdateTime)
                .list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTitle(InvoiceTitle title) {
        if (Boolean.TRUE.equals(title.getIsDefault())) {
            lambdaUpdate()
                    .set(InvoiceTitle::getIsDefault, false)
                    .eq(InvoiceTitle::getUserId, title.getUserId())
                    .update();
        }
        save(title);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefault(Long userId, Long titleId) {
        lambdaUpdate()
                .set(InvoiceTitle::getIsDefault, false)
                .eq(InvoiceTitle::getUserId, userId)
                .update();
        lambdaUpdate()
                .set(InvoiceTitle::getIsDefault, true)
                .eq(InvoiceTitle::getId, titleId)
                .update();
    }
}
