package com.unis.crk.basic.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.unis.crk.basic.entity.UserOrg;
import com.unis.crk.basic.mapper.UserOrgMapper;
import com.unis.crk.basic.service.IUserOrgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 机构授权表 服务实现类
 * </p>
 *
 * @author ghh
 * @since 2021-09-26
 */
@Service
public class UserOrgServiceImpl extends ServiceImpl<UserOrgMapper, UserOrg> implements IUserOrgService {
    @Resource
    private UserOrgMapper userOrgMapper;
    @Override
    public List<UserOrg> queryByUserId(String userId) {
        QueryWrapper<UserOrg> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("user_id",userId);
        List<UserOrg> userOrgs = userOrgMapper.selectList(objectQueryWrapper);
        return userOrgs;
    }

    @Override
    public void save(String userId, String[] orgIdList, String orgId) {
        // 先删除此用户所有数据
        UpdateWrapper<UserOrg> objectUpdateWrapper = new UpdateWrapper<>();
        objectUpdateWrapper.eq("user_id",userId);
        userOrgMapper.delete(objectUpdateWrapper);
        if(orgIdList.length>0){
            for (String id : orgIdList) {
                String uoId = IdUtil.simpleUUID();//动态生成32随机字符串
                UserOrg userOrg = new UserOrg();
                userOrg.setUoId(uoId);
                userOrg.setUserId(userId);
                userOrg.setOrgId(orgId);
                userOrg.setDepartId(id);
                userOrg.setUpdatetime(new Date());
                userOrgMapper.insert(userOrg);
            }
        }else{
            String uoId = IdUtil.simpleUUID();//动态生成32随机字符串
            UserOrg userOrg = new UserOrg();
            userOrg.setUoId(uoId);
            userOrg.setUserId(userId);
            userOrg.setOrgId(orgId);
            userOrg.setUpdatetime(new Date());
            userOrgMapper.insert(userOrg);
        }
    }
}
