package com.ruoyi.dk.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.component.core.constant.TenantConstants;
import com.ruoyi.dk.domain.AgreementSetting;
import com.ruoyi.dk.domain.HomeSetting;
import com.ruoyi.dk.domain.LoansSetting;
import com.ruoyi.dk.service.AgreementSettingService;
import com.ruoyi.dk.service.HomeSettingService;
import com.ruoyi.dk.service.LoansSettingService;
import com.ruoyi.system.event.AddTenantEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AddTenantEventListener {

    @Autowired
    private HomeSettingService homeSettingService;
    @Autowired
    private LoansSettingService loansSettingService;
    @Autowired
    private AgreementSettingService agreementSettingService;

    @EventListener
    public void event(AddTenantEvent addTenantEvent){
        String defaultTenantId = TenantConstants.DEFAULT_TENANT_ID;
        List<HomeSetting> homeSettingList = homeSettingService.list(Wrappers.lambdaQuery(HomeSetting.class).eq(HomeSetting::getTenantId, defaultTenantId));
        for (HomeSetting setting : homeSettingList) {
            setting.setTenantId(addTenantEvent.getTenantId());
            setting.setId(null);
        }
        List<LoansSetting> loansSettingList = loansSettingService.list(Wrappers.lambdaQuery(LoansSetting.class).eq(LoansSetting::getTenantId, defaultTenantId));
        for (LoansSetting setting : loansSettingList) {
            setting.setTenantId(addTenantEvent.getTenantId());
            setting.setId(null);
        }
        List<AgreementSetting> agreementSettingList = agreementSettingService.list(Wrappers.lambdaQuery(AgreementSetting.class).eq(AgreementSetting::getTenantId, defaultTenantId));
        for (AgreementSetting setting : agreementSettingList) {
            setting.setTenantId(addTenantEvent.getTenantId());
            setting.setId(null);
        }
        agreementSettingService.saveBatch(agreementSettingList);
        homeSettingService.saveBatch(homeSettingList);
        loansSettingService.saveBatch(loansSettingList);
    }
}
