package cn.kk.spring_simple_operation.service.impl;

import cn.kk.spring_simple_operation.entity.BrandRecordTool;
import cn.kk.spring_simple_operation.mapper.BrandRecordToolMapper;
import cn.kk.spring_simple_operation.model.dto.BrandAccountDto;
import cn.kk.spring_simple_operation.service.BrandRecordToolService;
import cn.kk.spring_simple_operation.service.VisualDesignLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 品牌备案工具 服务实现类
 * </p>
 *
 * @author guokunkun
 * @since 2025-04-01
 */
@Service
public class BrandRecordToolServiceImpl extends ServiceImpl<BrandRecordToolMapper, BrandRecordTool> implements BrandRecordToolService {

	@Resource
	private VisualDesignLogService visualDesignLogService;

	@Override
	public void updateBrandId(List<BrandAccountDto> list) {
		List<BrandRecordTool> recordTools = baseMapper.getByBrandAndAccount(list);
		Map<String, BrandRecordTool> recordToolMap = recordTools.stream().collect(Collectors.toMap(t -> t.getAccount() + "-" + t.getRecordBrand(), Function.identity(), (a, b) -> b));
		AtomicInteger count = new AtomicInteger(0);
		list.forEach(dto -> {
			BrandRecordTool brandRecordTool = recordToolMap.get(dto.getAccount() + "-" + dto.getBrand());
			if (Objects.isNull(brandRecordTool) || StringUtils.isBlank(dto.getBrandId())) return;
			if (dto.getBrandId().equals(brandRecordTool.getBrandId())) return;
			visualDesignLogService.addLog("brand_record_tool", String.format("brand id 由 [%s] 更新为 [%s] (刷数据)", brandRecordTool.getBrandId(), dto.getBrandId()), brandRecordTool.getId());
			brandRecordTool.setBrandId(dto.getBrandId());
			this.updateById(brandRecordTool);
			count.incrementAndGet();
		});
		System.out.printf("更新 %d 条品牌备案工具的品牌 ID%n", count.get());
	}
}
