package com.cyksj.service.translations.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.mapper.BackInfoTranslationsMapper;
import com.cyksj.model.dto.TranslationsDto;
import com.cyksj.model.entity.BackInfoTranslations;
import com.cyksj.service.translations.BackInfoTranslationsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 项目名: yhlxj2
 * 文件名: BackInfoTranslationsServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/7/16 14:20
 */
@Service
@RequiredArgsConstructor
public class BackInfoTranslationsServiceImpl extends ServiceImpl<BackInfoTranslationsMapper, BackInfoTranslations> implements BackInfoTranslationsService {
	private final BackInfoTranslationsMapper backInfoTranslationsMapper;

	@Override
	public void saveOrUpdateTranslations(TranslationsDto dto) {
		List<BackInfoTranslations> fields = dto.getFields();
		if (CollUtil.isEmpty(fields)) {
			return;
		}
		backInfoTranslationsMapper.batchInsertOrUpdate(dto.getFuncId(), dto.getType().ordinal(), dto.getFields(), dto.getLang());
	}

	@Override
	public void saveOrUpdateBackInfoTranslations(BackInfoTranslations.Type type, Long funcId, Object obj, String lang) {
		if (StrUtil.isEmpty(lang) || funcId == null) {
			return;
		}
		TranslationsDto translationsDto = new TranslationsDto();
		translationsDto.setType(type);
		translationsDto.setLang(lang);
		translationsDto.setFuncId(funcId);
		List<BackInfoTranslations> fields = new ArrayList<>();
		for (Field declaredField : obj.getClass().getDeclaredFields()) {
			try {
				declaredField.setAccessible(true);
				Optional.ofNullable(declaredField.get(obj)).ifPresent(val -> {
					if (val instanceof String) {
						BackInfoTranslations backInfoTranslations = new BackInfoTranslations();
						backInfoTranslations.setFieldName(declaredField.getName());
						backInfoTranslations.setDesp(val.toString());
						fields.add(backInfoTranslations);
					}
				});
			} catch (IllegalAccessException e) {
			}
		}
		if (CollUtil.isNotEmpty(fields)) {
			translationsDto.setFields(fields);
			saveOrUpdateTranslations(translationsDto);
		} else {
			backInfoTranslationsMapper.delete(Wrappers.lambdaQuery(BackInfoTranslations.class).eq(BackInfoTranslations::getType, type.ordinal()).eq(BackInfoTranslations::getFuncId, funcId).eq(BackInfoTranslations::getLang, lang));
		}
	}
}
