package com.huiju.estateagents.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.property.entity.TaUserCommunity;
import com.huiju.estateagents.property.entity.TpCommunity;
import com.huiju.estateagents.property.mapper.TaUserCommunityMapper;
import com.huiju.estateagents.property.mapper.TpCommunityMapper;
import com.huiju.estateagents.property.service.ITaUserCommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yansen
 * @since 2021-01-19
 */
@Service
public class TaUserCommunityServiceImpl extends ServiceImpl<TaUserCommunityMapper, TaUserCommunity> implements ITaUserCommunityService {

    @Autowired
    TaUserCommunityMapper taUserCommunityMapper;

    @Autowired
    TpCommunityMapper tpCommunityMapper;

    @Override
    public List<TpCommunity> getListBy(Integer orgId, Integer userId) {
        return tpCommunityMapper.getListOfUser(orgId, userId);
    }

    @Override
    public boolean addUserCommunity(Integer orgId, Integer userId, List<TpCommunity> communityList) throws Exception {
        if (null == orgId || null == userId || null == communityList) {
            throw new Exception("未找到授权小区需要操作的记录");
        }

        // 先删除原有授权记录
        QueryWrapper<TaUserCommunity> deleteQuery = new QueryWrapper<>();
        deleteQuery.eq("org_id", orgId);
        deleteQuery.eq("user_id", userId);
        remove(deleteQuery);

        // 新增记录
        List<TaUserCommunity> list = new ArrayList<>();
        for (TpCommunity community: communityList) {
            TaUserCommunity userCommunity = new TaUserCommunity();
            userCommunity.setOrgId(orgId);
            userCommunity.setUserId(userId);
            userCommunity.setCommunityId(community.getId());
            list.add(userCommunity);
        }

        return saveBatch(list);
    }
}
