package com.njcn.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.device.mapper.DeptLineMapper;
import com.njcn.device.pojo.po.DeptLine;
import com.njcn.device.service.DeptLineService;
import com.njcn.web.pojo.param.DeptLineParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author denghuajun
 * @date 2022/1/12 17:32
 *
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeptLineServiceImpl extends ServiceImpl<DeptLineMapper, DeptLine> implements DeptLineService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deptBindLine(DeptLineParam deptLineParam) {
        //先解绑，再进行绑定
        QueryWrapper<DeptLine> deptLineQueryWrapper = new QueryWrapper<>();
        deptLineQueryWrapper.eq("pq_dept_line.id", deptLineParam.getId());
        this.baseMapper.delete(deptLineQueryWrapper);
        List<DeptLine> deptLines = deptLineParam.getIds().stream().map(id -> {
            DeptLine deptLine = new DeptLine();
            deptLine.setId(deptLineParam.getId());
            deptLine.setLineId(id);
            return deptLine;
        }).collect(Collectors.toList());
        this.saveBatch(deptLines);
    }

    @Override
    public void deptDeleteBindLine(DeptLineParam deptLineParam) {
        for (int i = 0; i < deptLineParam.getIds().size(); i++) {
            QueryWrapper<DeptLine> deptLineQueryWrapper = new QueryWrapper<>();
            deptLineQueryWrapper.eq("pq_dept_line.id", deptLineParam.getId());
            deptLineQueryWrapper.eq("pq_dept_line.Line_Id", deptLineParam.getIds().get(i));
            this.baseMapper.delete(deptLineQueryWrapper);
        }
    }

    @Override
    public List<DeptLine> selectDeptBindLines(List<String> ids) {
        return this.lambdaQuery().in(DeptLine::getId, ids).list();
    }

    @Override
    public int removeBind(String id) {
        QueryWrapper<DeptLine> deptLineQueryWrapper = new QueryWrapper<>();
        deptLineQueryWrapper.eq("pq_dept_line.id", id);
        return this.baseMapper.delete(deptLineQueryWrapper);
    }

    @Override
    public List<String> getLineByDeptId(String id) {
        return this.lambdaQuery().in(DeptLine::getId, id).list().stream().map(DeptLine::getLineId).distinct().collect(Collectors.toList());
    }


}
