package com.keyware.shandan.mark.services.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keyware.shandan.mark.mapper.MarkTypeMapper;
import com.keyware.shandan.mark.pojo.MarkType;
import com.keyware.shandan.mark.services.MarkTypeService;
import com.keyware.shandan.system.entity.SysUser;
import com.keyware.shandan.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author GuoXin
 * @date 2022-05-13
 */
@Service
public class MarkTypeServiceImpl extends ServiceImpl<MarkTypeMapper, MarkType> implements MarkTypeService {

    @Autowired
    private SysUserService userService;

    @Override
    public <E extends IPage<MarkType>> E page(E page, Wrapper<MarkType> queryWrapper) {
        E pageResult = super.page(page, queryWrapper);
        pageResult.getRecords().forEach(markType -> {
            SysUser user = userService.getById(markType.getCreateUser());
            if(user != null){
                markType.setCreateUserStr(user.getUserName());
            }else{
                markType.setCreateUserStr(markType.getCreateUser());
            }
        });
        return pageResult;
    }

    @Override
    public boolean saveOrUpdate(MarkType entity) {
        entity.setMarkType(entity.getMarkType().trim());
        if(entity.getId() == null){
            QueryWrapper<MarkType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("MARK_TYPE", entity.getMarkType());
            Assert.isTrue(count(queryWrapper) == 0, "置标类型已存在");
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    public MarkType getByName(String typeName) {
        QueryWrapper<MarkType> wrapper = new QueryWrapper<>();
        wrapper.eq("MARK_TYPE", typeName);
        return getOne(wrapper);
    }
}
