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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.sys.entity.SysCompanyRelSystem;
import com.patzn.lims.sys.mapper.SysCompanyRelSystemMapper;
import com.patzn.lims.sys.service.ISysCompanyRelSystemService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 公司系统关联表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2017-08-03
 */
@Service
public class SysCompanyRelSystemServiceImpl extends BaseServiceImpl<SysCompanyRelSystemMapper, SysCompanyRelSystem> implements ISysCompanyRelSystemService {

    @Override
    public IPage<SysCompanyRelSystem> page(Page<SysCompanyRelSystem> page, SysCompanyRelSystem sysCompanyRelSystem) {
        return this.page(page, Wrappers.query(sysCompanyRelSystem));
    }

    @Override
    public List<SysCompanyRelSystem> list(SysCompanyRelSystem sysCompanyRelSystem) {
        return this.list(Wrappers.query(sysCompanyRelSystem));
    }

    @Override
    public List<SysCompanyRelSystem> getRelSystem(Long companyId) {
        return this.list(Wrappers.<SysCompanyRelSystem>query()
                .select("system_id")
                .eq("company_id", companyId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addRelSystem(Long companyId, Long[] systemIds) {
        int result = baseMapper.delete(Wrappers.<SysCompanyRelSystem>query()
                .eq("company_id", companyId));
        if (ArrayUtils.isNotEmpty(systemIds)) {
            List<SysCompanyRelSystem> relList = new ArrayList<>();
            for (Long systemId : systemIds) {
                SysCompanyRelSystem rel = new SysCompanyRelSystem();
                rel.setCompanyId(companyId);
                rel.setSystemId(systemId);
                relList.add(rel);
            }
            return this.saveBatch(relList);
        }
        return SqlHelper.retBool(result);
    }
}
