package com.casic.missiles.modular.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.application.service.AbstractDeptService;
import com.casic.missiles.core.application.service.AbstractTenantService;
import com.casic.missiles.modular.system.dao.TenantDeptMapper;
import com.casic.missiles.modular.system.dto.TenantDTO;
import com.casic.missiles.modular.system.model.Tenant;
import com.casic.missiles.modular.system.model.TenantDept;
import com.casic.missiles.modular.system.service.ITenantDeptService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lwh123
 * @since 2022-06-07
 */
@Service
public class TenantDeptServiceImpl extends ServiceImpl<TenantDeptMapper, TenantDept> implements ITenantDeptService {
    @Resource
    private AbstractTenantService abstractTenantService;
    @Resource
    private AbstractDeptService abstractDeptService;

    @Override
    public List<TenantDTO> tenantList(QueryWrapper<Tenant> query) {
        List<Tenant> tenants = abstractTenantService.list(query);
        List<TenantDTO> dtos = tenants.stream().map(tenant -> {
            TenantDTO dto = new TenantDTO();
            BeanUtils.copyProperties(tenant, dto);
            QueryWrapper<TenantDept> dtoQuery = new QueryWrapper<>();
            dtoQuery.eq("tenant_id",dto.getId());
            TenantDept tenantDept = this.getOne(dtoQuery);
            if (tenantDept != null) {
                dto.setDeptId(tenantDept.getDeptId());
                dto.setDeptName(abstractDeptService.getDeptName(tenantDept.getDeptId()));
            }
            return dto;
        }).collect(Collectors.toList());
        return dtos;
    }

    @Override
    public void relateTenant(TenantDept tenantDept) {
        QueryWrapper<TenantDept> dtoQuery = new QueryWrapper<>();
        dtoQuery.eq("tenant_id",tenantDept.getTenantId());
        this.remove(dtoQuery);
        this.save(tenantDept);
    }
}
