package cn.iocoder.yudao.module.bpm.service.definition;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.cc.BpmProcessCcPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.cc.BpmProcessCcSaveReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessCcDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.definition.BpmProcessCcMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

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

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.PROCESS_CC_NOT_EXISTS;

/**
 * BPM 流程抄送配置 Service 实现类
 *
 * @author 符溶馨
 */
@Service
@Validated
public class BpmProcessCcServiceImpl implements BpmProcessCcService {

    @Resource
    private BpmProcessCcMapper processCcMapper;

    @Resource
    private DeptApi deptApi;

    @Override
    public Long createProcessCc(BpmProcessCcSaveReqVO createReqVO) {
        // 插入
        BpmProcessCcDO processCc = BeanUtils.toBean(createReqVO, BpmProcessCcDO.class);
        processCcMapper.insert(processCc);
        // 返回
        return processCc.getId();
    }

    @Override
    public void updateProcessCc(BpmProcessCcSaveReqVO updateReqVO) {
        // 校验存在
        validateProcessCcExists(updateReqVO.getId());
        // 更新
        BpmProcessCcDO updateObj = BeanUtils.toBean(updateReqVO, BpmProcessCcDO.class);
        processCcMapper.updateById(updateObj);
    }

    @Override
    public void deleteProcessCc(Long id) {
        // 校验存在
        validateProcessCcExists(id);
        // 删除
        processCcMapper.deleteById(id);
    }

    private void validateProcessCcExists(Long id) {
        if (processCcMapper.selectById(id) == null) {
            throw exception(PROCESS_CC_NOT_EXISTS);
        }
    }

    @Override
    public BpmProcessCcDO getProcessCc(Long id) {
        return processCcMapper.selectById(id);
    }

    @Override
    public PageResult<BpmProcessCcDO> getProcessCcPage(BpmProcessCcPageReqVO pageReqVO) {
        return processCcMapper.selectPage(pageReqVO);
    }

    @Override
    public List<BpmProcessCcDO> getCCListByName(String name, Long userId) {

        // 获取用户所在公司编号
        DeptRespDTO dto = deptApi.getUserCompanyDept(userId).getCheckedData();

        return processCcMapper.selectList(new LambdaQueryWrapperX<BpmProcessCcDO>()
                .likeIfPresent(BpmProcessCcDO::getName, name)
                .likeIfPresent(BpmProcessCcDO::getCompanyDeptId, String.valueOf(dto.getId())));
    }
}