package com.zcloud.basic.info.gatewayimpl;

import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.basic.info.domain.gateway.PostGateway;
import com.zcloud.basic.info.domain.model.PostE;
import com.zcloud.basic.info.persistence.dataobject.PostDO;
import com.zcloud.basic.info.persistence.repository.PostRepository;
import com.zcloud.gbscommon.utils.UuidUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * web-infrastructure
 *
 * @Author SondonYong
 * @Date 2025-10-31 17:24:04
 */
@Service
@AllArgsConstructor
public class PostGatewayImpl implements PostGateway {
    private final PostRepository postRepository;

    @Override
    public Long add(PostE postE) {

        QueryWrapper<PostDO> wrapper = new QueryWrapper<>();
        wrapper.eq("department_id", postE.getDepartmentId());
        wrapper.eq("post_name", postE.getPostName());
        wrapper.eq("delete_enum", "FALSE");
        List<PostDO> postDOList = postRepository.list(wrapper);
        if(postDOList != null && postDOList.size() > 0) {
            throw new BizException("保存失败，该岗位名称已存在");
        }

        PostDO d = new PostDO();
        BeanUtils.copyProperties(postE, d);
        if(StringUtils.isEmpty(d.getPostId())){
            d.setPostId(UuidUtil.get32UUID());
        }
        if(d.getCorpinfoId() == null){
            d.setCorpinfoId(AuthContext.getTenantId());
        }
        if(StringUtils.isEmpty(d.getCorpinfoName())){
            d.setCorpinfoName(AuthContext.getName());
        }
//        if(d.getSupervisionFlag() == null){
//            d.setSupervisionFlag(0);
//        }
        postRepository.save(d);
        return d.getId();
    }

    @Override
    public Boolean update(PostE postE) {

        QueryWrapper<PostDO> wrapper = new QueryWrapper<>();
        wrapper.ne("id", postE.getId());
        wrapper.eq("department_id", postE.getDepartmentId());
        wrapper.eq("post_name", postE.getPostName());
        wrapper.eq("delete_enum", "FALSE");
        List<PostDO> postDOList = postRepository.list(wrapper);
        if(postDOList != null && postDOList.size() > 0) {
            throw new BizException("修改失败，该岗位名称已存在");
        }

        PostDO d = new PostDO();
        BeanUtils.copyProperties(postE, d);
//        if(d.getSupervisionFlag() == null){
//            d.setSupervisionFlag(0);
//        }

        postRepository.updateById(d);
        return true;
    }

    @Override
    public Boolean deletedPostById(Long id) {
        return postRepository.removeById(id);
    }

    @Override
    public Boolean deletedPostByIds(Long[] ids) {
        return postRepository.removeByIds(Arrays.asList(ids));
    }
}

