package cn.ey.biz.module.system.service.permission;

import cn.ey.biz.module.system.controller.admin.permission.vo.userRole.UserDataRoleExcelVO;
import cn.ey.biz.module.system.dal.dataobject.permission.DataRoleDO;
import cn.ey.biz.module.system.dal.dataobject.permission.UserDataRoleDO;
import cn.ey.biz.module.system.dal.dataobject.user.AdminUserDO;
import cn.ey.biz.module.system.dal.mapper.permission.DataRoleMapper;
import cn.ey.biz.module.system.dal.mapper.permission.UserDataRoleMapper;
import cn.ey.biz.module.system.dal.mapper.user.AdminUserMapper;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户数据角色关联表实现
 */
@Service
public class UserDataRoleServiceImpl  implements UserDataRoleService{

    @Resource
    private UserDataRoleMapper userDataRoleMapper;
    @Resource
    private AdminUserMapper userMapper;
    @Resource
    private DataRoleMapper dataRoleMapper;

    @Override
    public List<UserDataRoleExcelVO> getListUserDataRole() {
        return userDataRoleMapper.getUserDataRoleGpnName();
    }

    @Override
    @Transactional
    public void importUserDataRoleList(List<UserDataRoleExcelVO> userRoleExceList) {
        List<UserDataRoleDO> userRoleDOList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(userRoleExceList)){
            List<String> gpnList = userRoleExceList.stream().map(x -> x.getGpn()).collect(Collectors.toList());
            List<AdminUserDO>  usersList=userMapper.selectList(new LambdaUpdateWrapper<AdminUserDO>().in(AdminUserDO::getGpn,gpnList));
            List<DataRoleDO> dataRoleList=dataRoleMapper.selectList();

            for (UserDataRoleExcelVO urLi:userRoleExceList){
                List<AdminUserDO> adminUserList=usersList.stream().filter(x->x.getGpn().equals(urLi.getGpn())).collect(Collectors.toList());
                List<DataRoleDO> dataRoleLists=dataRoleList.stream().filter(x->x.getName().equals(urLi.getName())).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(adminUserList)&& CollectionUtil.isNotEmpty(dataRoleLists)){
                    UserDataRoleDO userDataRoleDO=new UserDataRoleDO();
                    userDataRoleDO.setUserId(adminUserList.get(0).getId());
                    userDataRoleDO.setRoleId(dataRoleLists.get(0).getId());
                    userRoleDOList.add(userDataRoleDO);
                }
            }
            userDataRoleMapper.insertBatch(userRoleDOList);
        }
    }


}
