package com.kym.service.impl;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.kym.common.utils.CommUtil;
import com.kym.entity.DataDict;
import com.kym.mapper.DataDictMapper;
import com.kym.service.DataDictService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author zuy
 * @since 2023-08-13
 */
@Service
public class DataDictServiceImpl extends MPJBaseServiceImpl<DataDictMapper, DataDict> implements DataDictService {


    @Override
    public Object list(DataDict query) {
        var list = lambdaQuery()
                .like(CommUtil.isNotEmptyAndNull(query.getCode()), DataDict::getCode, query.getCode())
                .like(CommUtil.isNotEmptyAndNull(query.getName()), DataDict::getName, query.getName())
                .list();
        return list;
    }

/*
    @Override
    public Object listV2(IQuery<DataDict> query) {
        QueryChainWrapper<DataDict> wrapper = getWrapper(query.query, DataDict.class);
        wrapper.select("distinct(code)");
        Long count = wrapper.count();
        PageHelper.startPage(query.pageNum, query.pageSize);
        List<DataDict> list = wrapper.list();
        if (CommUtil.isNotEmptyAndNull(list)) {

            List<DataDict> list1 = lambdaQuery().in(CommUtil.isNotEmptyAndNull(list), DataDict::getCode, list.stream().map(DataDict::getCode).collect(Collectors.toList())).list();
            return IQuery.newPageBean(count, list1.stream().filter(CommUtil.distinctByKey(DataDict::getCode)).toList());
        } else {
            return IQuery.newPageBean(0, Collections.emptyList());
        }
    }*/

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(List<DataDict> dictList) {
        List<DataDict> list = lambdaQuery().list();
        if (CommUtil.isNotEmptyAndNull(list)) {
            Map<String, List<DataDict>> dbDictMap = list.stream().collect(Collectors.groupingBy(DataDict::getCode));
            //校验重名和重复值
            dictList.forEach(dict -> {
                List<DataDict> dataDicts = dbDictMap.get(dict.getCode());
                if (CommUtil.isNotEmptyAndNull(dataDicts)) {
                        CommUtil.asserts(dataDicts.stream().noneMatch(k-> !Objects.equals(k.getId(), dict.getId()) &&(k.getName().equalsIgnoreCase(dict.getName())||k.getValue().equalsIgnoreCase(dict.getValue()))),String.format("字典%s取值异常，请核对",dict.getCode()));
                }
            });
        }
        saveOrUpdateBatch(dictList);
    }

}
