package shop.alien.store.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeDict;
import shop.alien.entity.store.StoreDictionary;
import shop.alien.entity.store.vo.StoreDictionaryVo;
import shop.alien.mapper.LifeDictMapper;
import shop.alien.mapper.StoreDictionaryMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * 字典
 */
@Service
@RequiredArgsConstructor
public class LifeDictService {

    private final LifeDictMapper lifeDictMapper;

    private final StoreDictionaryMapper StoreDictionaryMapper;

    public List<StoreDictionaryVo> getLifeDictByTypeName(String typeName) {
        List<StoreDictionaryVo> result = new ArrayList<>();
        QueryWrapper<StoreDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(typeName), "type_name", typeName);
        queryWrapper.lambda().isNull(StoreDictionary::getParentId);
        queryWrapper.orderByAsc("dict_id");
        List<StoreDictionary> storeDictionaries = StoreDictionaryMapper.selectList(queryWrapper);
        //转Vo，并且查询子集数据
        for (StoreDictionary storeDictionary : storeDictionaries) {
            StoreDictionaryVo storeDictionaryVo = new StoreDictionaryVo();
            BeanUtils.copyProperties(storeDictionary, storeDictionaryVo);
            //查询数据子集
            List<StoreDictionary> childList =
                    StoreDictionaryMapper.selectList(new LambdaUpdateWrapper<StoreDictionary>().eq(StoreDictionary::getParentId, storeDictionary.getId()));
            List<StoreDictionaryVo> childVos = new ArrayList<>();
            for (StoreDictionary storeDict : childList) {
                StoreDictionaryVo childDictionaryVo = new StoreDictionaryVo();
                BeanUtils.copyProperties(storeDict, childDictionaryVo);
                childVos.add(childDictionaryVo);
            }
            storeDictionaryVo.setSubDataList(childVos);
            result.add(storeDictionaryVo);
        }
        return result;
    }

    public Integer addLifeDict(LifeDict lifeDict) {
        return lifeDictMapper.insert(lifeDict);
    }

    public Integer deleteLifeDict(LifeDict lifeDict) {
        LambdaUpdateWrapper<LifeDict> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeDict::getId, lifeDict.getDictName());
        return lifeDictMapper.delete(wrapper);
    }
}
