package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.DeptUser;
import com.yami.shop.dao.DeptUserMapper;
import com.yami.shop.service.DeptUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 部门用户关联Service实现类
 *
 * @author
 */
@Service
@AllArgsConstructor
public class DeptUserServiceImpl extends ServiceImpl<DeptUserMapper, DeptUser> implements DeptUserService {

    private final DeptUserMapper deptUserMapper;

    @Override
    public List<DeptUser> listByUserId(Long userId) {
        return deptUserMapper.selectByUserId(userId);
    }

    @Override
    public List<DeptUser> listByDeptId(Long deptId) {
        return deptUserMapper.selectByDeptId(deptId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUserDept(Long userId, List<Long> deptIds) {
        // 先删除用户原有的部门关联
        deptUserMapper.deleteByUserId(userId);
        // 添加新的部门关联
        if (deptIds != null && !deptIds.isEmpty()) {
            List<DeptUser> deptUsers = new ArrayList<>();
            Date now = new Date();
            for (Long deptId : deptIds) {
                DeptUser deptUser = new DeptUser();
                deptUser.setUserId(userId);
                deptUser.setDeptId(deptId);
                deptUser.setCreateTime(now);
                deptUser.setUpdateTime(now);
                deptUsers.add(deptUser);
            }
            return deptUserMapper.insertBatch(deptUsers) > 0;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByUserId(Long userId) {
        return deptUserMapper.deleteByUserId(userId) >= 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByDeptId(Long deptId) {
        return deptUserMapper.deleteByDeptId(deptId) >= 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatchUserDepts(List<Long> userIds, Long deptId) {
        if (userIds == null || userIds.isEmpty() || deptId == null) {
            return false;
        }

        // 先删除部门原有的用户关联（如果需要）
        // deptUserMapper.deleteByDeptId(deptId);

        List<DeptUser> deptUsers = new ArrayList<>();
        Date now = new Date();
        for (Long userId : userIds) {
            DeptUser deptUser = new DeptUser();
            deptUser.setUserId(userId);
            deptUser.setDeptId(deptId);
            deptUser.setCreateTime(now);
            deptUser.setUpdateTime(now);
            deptUsers.add(deptUser);
        }
        return deptUserMapper.insertBatch(deptUsers) > 0;
    }
}
