package com.patzn.lims.res.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.res.entity.LmsUnit;
import com.patzn.lims.res.mapper.LmsUnitMapper;
import com.patzn.lims.res.service.ILmsUnitService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;


/**
 * <p>
 * 单位表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2017-11-29
 */
@Service
public class LmsUnitServiceImpl extends BaseServiceImpl<LmsUnitMapper, LmsUnit> implements ILmsUnitService {


    @Override
    public Page<LmsUnit> page(Page<LmsUnit> page, LmsUnit lmsUnit) {
        QueryWrapper wrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(lmsUnit.getName())) {
            wrapper.like("name", lmsUnit.getName());
        }
        return page(page, wrapper);
    }


    @Override
    public List<LmsUnit> list(LmsUnit lmsUnit) {
        return list(Wrappers.query(lmsUnit).orderBy(true,true,"sort"));
    }


    @Override
    public int count(Collection<String> names) {
        return super.count( Wrappers.<LmsUnit>query().in("name", names));
    }


    @Override
    public boolean save(LmsUnit lmsUnit) {
        verifyUnitName(lmsUnit);
        return super.save(lmsUnit);
    }


    @Override
    public boolean updateById(LmsUnit lmsUnit) {
        return super.updateById(lmsUnit);
    }


    /**
     * 单位名称校验
     */
    private void verifyUnitName(LmsUnit lmsUnit) {
        QueryWrapper wrapper =Wrappers.query();
        wrapper.eq("name", lmsUnit.getName());
        if (null != lmsUnit.getId()) {
            wrapper.ne("id", lmsUnit.getId());
        }
        if (super.count(wrapper) > 0) {
            PtAssert.fail("抱歉!该单位已存在，请改换其它单位。");
        }
    }


    @Override
    public LmsUnit getById(Serializable id) {
        LmsUnit lmsUnit = super.getById(id);
        if (null == lmsUnit) {
            PtAssert.fail("该耗材单位异常，请刷新重试。");
        }
        return lmsUnit;
    }


    @Override
    public boolean importUnit(MultipartFile file) {
        return  false;
    }

    @Override
    public int countForChemical(Collection<String> names) {
        if (CollectionUtils.isEmpty(names)) {
            return 0;
        }
        return super.count( Wrappers.<LmsUnit>query().in("name", names));
    }

    @Override
    public List<LmsUnit> listUnit(Collection<String> exunit) {
        if (CollectionUtils.isEmpty(exunit)) {
            return null;
        }
        return list(Wrappers.<LmsUnit>query().select("id, name").in("name", exunit));
    }
}
