package com.ruoyi.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.page.MpPageUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.DozerUtils;
import com.ruoyi.platform.domain.PlatformPost;
import com.ruoyi.platform.domain.PlatformUserPost;
import com.ruoyi.platform.domain.dto.PlatformPostDTO;
import com.ruoyi.platform.domain.vo.PlatformPostVO;
import com.ruoyi.platform.mapper.PlatformPostMapper;
import com.ruoyi.platform.mapper.PlatformUserPostMapper;
import com.ruoyi.platform.service.IPlatformPostService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 *@Description 岗位信息 服务层处理
 *@Author zhushuyong
 *@Date 2021/5/27 12:20
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Service
public class PlatformPostServiceImpl extends ServiceImpl<PlatformPostMapper, PlatformPost> implements IPlatformPostService {

    @Resource
    private PlatformPostMapper postMapper;

    @Resource
    private PlatformUserPostMapper userPostMapper;

    /**
     * 查询岗位信息集合
     *
     * @param postDTO 岗位信息
     * @return 岗位信息集合
     */
    @Override
    public TableDataInfo<PlatformPostVO> selectPostPage(PlatformPostDTO postDTO) {
        IPage<PlatformPost> platformPostIPage = this.page(MpPageUtils.intPage(), getWrapper(postDTO));
        return MpPageUtils.copyPage(platformPostIPage, PlatformPostVO.class);
    }

    @Override
    public List<PlatformPostVO> selectPostList(PlatformPostDTO postDTO) {
        return BeanUtil.copyToList(this.list(getWrapper(postDTO)), PlatformPostVO.class);
    }

    private LambdaQueryWrapper<PlatformPost> getWrapper(PlatformPostDTO postDTO) {
        return new LambdaQueryWrapper<PlatformPost>().eq(StringUtils.isNotBlank(postDTO.getStatus()),PlatformPost::getStatus,postDTO.getStatus())
                .like(StringUtils.isNotBlank(postDTO.getPostCode()),PlatformPost::getPostCode,postDTO.getPostCode())
                .like(StringUtils.isNotBlank(postDTO.getPostName()),PlatformPost::getPostName,postDTO.getPostName());
    }

    /**
     * 查询所有岗位
     *
     * @return 岗位列表
     */
    @Override
    public List<PlatformPostVO> selectPostAll() {
        return BeanUtil.copyToList(list(), PlatformPostVO.class);
    }

    /**
     * 根据用户ID查询岗位
     *
     * @param userId 用户ID
     * @return 岗位列表
     */
    @Override
    public List<PlatformPostVO> selectPostsByUserId(String userId) {
        List<PlatformPostVO> userPosts = postMapper.selectPostsByUserId(userId);
        List<PlatformPostVO> posts = selectPostAll();
        for (PlatformPostVO postVO : posts) {
            for (PlatformPostVO userRole : userPosts) {
                if (postVO.getId().equals(userRole.getId())) {
                    postVO.setFlag(true);
                    break;
                }
            }
        }
        return posts;
    }

    /**
     * 通过岗位ID查询岗位信息
     *
     * @param postId 岗位ID
     * @return 角色对象信息
     */
    @Override
    public PlatformPostVO selectPostById(String postId) {
        return DozerUtils.copyProperties(getById(postId),PlatformPostVO.class);
    }

    /**
     * 批量删除岗位信息
     *
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public int deletePostByIds(String ids) throws BusinessException {
        String[] postIds = Convert.toStrArray(ids);
        for (String postId : postIds) {
            PlatformPostVO post = selectPostById(postId);
            if (countUserPostById(postId) > 0) {
                throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
        return postMapper.deleteBatchIds(Arrays.asList(postIds));
    }

    /**
     * 新增保存岗位信息
     *
     * @param postDTO 岗位信息
     * @return 结果
     */
    @Override
    public int insertPost(PlatformPostDTO postDTO) {
        return postMapper.insert(DozerUtils.copyProperties(postDTO, PlatformPost.class));
    }

    /**
     * 修改保存岗位信息
     *
     * @param postDTO 岗位信息
     * @return 结果
     */
    @Override
    public int updatePost(PlatformPostDTO postDTO) {
        return postMapper.updateById(DozerUtils.copyProperties(postDTO, PlatformPost.class));
    }

    /**
     * 通过岗位ID查询岗位使用数量
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public long countUserPostById(String postId) {
        return userPostMapper.selectCount(Wrappers.query(PlatformUserPost.builder().postId(postId).build()));
    }

    /**
     * 校验岗位名称是否唯一
     *
     * @param postDTO 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostNameUnique(PlatformPostDTO postDTO)
    {
        String postId = StringUtils.isIdNull(postDTO.getId());
        Optional<PlatformPost> info = list(new LambdaQueryWrapper<PlatformPost>()
                .eq(StringUtils.isNotBlank(postDTO.getPostName())
                        ,PlatformPost::getPostName,
                        postDTO.getPostName())).stream().findFirst();
        if (info.isPresent() && !postId.equals(info.get().getId())) {
            return UserConstants.POST_NAME_NOT_UNIQUE;
        }
        return UserConstants.POST_NAME_UNIQUE;
    }

    /**
     * 校验岗位编码是否唯一
     *
     * @param postDTO 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostCodeUnique(PlatformPostDTO postDTO) {
        String postId = StringUtils.isIdNull(postDTO.getId());
        Optional<PlatformPost> info = list(new LambdaQueryWrapper<PlatformPost>()
                .eq(StringUtils.isNotBlank(postDTO.getPostCode())
                        ,PlatformPost::getPostCode,
                        postDTO.getPostCode())).stream().findFirst();
        if (info.isPresent() && !postId.equals(info.get().getId())) {
            return UserConstants.POST_CODE_NOT_UNIQUE;
        }
        return UserConstants.POST_CODE_UNIQUE;
    }

}
