package com.purui.prims.headless.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.purui.prims.auth.api.authentication.pojo.User;
import com.purui.prims.common.util.BeanMapper;
import com.purui.prims.headless.api.pojo.request.DecoratorReq;
import com.purui.prims.headless.api.pojo.response.DecoratorResp;
import com.purui.prims.headless.server.persistence.dataobject.DecoratorDO;
import com.purui.prims.headless.server.persistence.mapper.DecoratorDOMapper;
import com.purui.prims.headless.server.persistence.mapper.DecoratorTypeDOMapper;
import com.purui.prims.headless.server.service.DecoratorService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DecoratorServiceImpl extends ServiceImpl<DecoratorDOMapper, DecoratorDO> implements DecoratorService {

    @Resource
    private DecoratorTypeDOMapper decoratorTypeDOMapper;

    @Override
    public boolean saveOrUpdate(DecoratorReq decoratorReq, User user) {
        DecoratorDO decoratorDO = new DecoratorDO();
        BeanMapper.mapper(decoratorReq, decoratorDO);
        return super.saveOrUpdate(decoratorDO);
    }

    @Override
    public void delete(Integer id) {
        removeById(id);
    }

    @Override
    public List<DecoratorResp> getDecorators(DecoratorReq decoratorReq) {
        QueryWrapper<DecoratorDO> queryWrapper = new QueryWrapper<>();
        if (decoratorReq.getTypeId() != null) {
            queryWrapper.eq("type_id", decoratorReq.getTypeId());
        }
        if (StringUtils.isNotEmpty(decoratorReq.getName())) {
            queryWrapper.like("name", decoratorReq.getName());
        }
        return super.list(queryWrapper).stream().map(decoratorDO -> {
            DecoratorResp decoratorResp = new DecoratorResp();
            BeanMapper.mapper(decoratorDO, decoratorResp);
            decoratorResp.setTypeName(decoratorTypeDOMapper.selectById(decoratorDO.getTypeId()).getName());
            return decoratorResp;
        }).collect(Collectors.toList());
    }

    @Override
    public DecoratorResp getDecorator(Integer id) {
        DecoratorDO decoratorDO = super.getById(id);
        DecoratorResp decoratorResp = new DecoratorResp();
        BeanMapper.mapper(decoratorDO, decoratorResp);
        return decoratorResp;
    }

}
