package com.zcloud.domain.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.domain.command.convertor.DomainDepartmentUserCoConvertor;
import com.zcloud.domain.domain.gateway.DomainDepartmentGateway;
import com.zcloud.domain.domain.model.DomainDepartmentE;
import com.zcloud.domain.dto.DomainDepartmentAddCmd;
import com.zcloud.domain.dto.DomainDepartmentUserAddCmd;
import com.zcloud.domain.persistence.dataobject.DomainDepartmentUserDO;
import com.zcloud.domain.persistence.repository.DomainDepartmentRepository;
import com.zcloud.domain.persistence.repository.DomainDepartmentUserRepository;
import com.zcloud.gbscommon.utils.Tools;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2026-01-27 11:28:51
 */
@Component
@AllArgsConstructor
public class DomainDepartmentAddExe {
    private final DomainDepartmentGateway domainDepartmentGateway;
    private final DomainDepartmentRepository domainDepartmentRepository;
    private final DomainDepartmentUserRepository domainDepartmentUserRepository;
    private final DomainDepartmentUserCoConvertor domainDepartmentUserCoConvertor;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(DomainDepartmentAddCmd cmd) {
        //查询领域类型是否存在
        domainDepartmentRepository.checkDomainType(cmd.getDomainType(), null);
        DomainDepartmentE domainDepartmentE = new DomainDepartmentE();
        BeanUtils.copyProperties(cmd, domainDepartmentE);
        boolean res = false;
        try {
            res = domainDepartmentGateway.add(domainDepartmentE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        List<DomainDepartmentUserAddCmd> domainDepartmentUserAddCmdList = cmd.getDomainDepartmentUserAddCmdList();
        List<DomainDepartmentUserDO> domainDepartmentUserDOList = domainDepartmentUserCoConvertor.converCmdsToDOs(domainDepartmentUserAddCmdList);
        domainDepartmentUserDOList.forEach(
                domainDepartmentUserDO -> {
                    domainDepartmentUserDO.setDomainDepartmentUserId(Tools.get32UUID());
                    domainDepartmentUserDO.setDomainDepartmentId(domainDepartmentE.getDomainDepartmentId());
                }
        );
        domainDepartmentUserRepository.saveBatch(domainDepartmentUserDOList);
        return true;
    }
}

