package com.zcloud.domain.command;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.exception.BizException;
import com.zcloud.domain.command.convertor.DomainGroupUserCoConvertor;
import com.zcloud.domain.domain.gateway.DomainGroupGateway;
import com.zcloud.domain.domain.model.DomainGroupE;
import com.zcloud.domain.dto.DomainDepartmentUserAddCmd;
import com.zcloud.domain.dto.DomainGroupAddCmd;
import com.zcloud.domain.dto.DomainGroupUserAddCmd;
import com.zcloud.domain.persistence.dataobject.DomainDepartmentUserDO;
import com.zcloud.domain.persistence.dataobject.DomainGroupDO;
import com.zcloud.domain.persistence.dataobject.DomainGroupUserDO;
import com.zcloud.domain.persistence.repository.DomainGroupRepository;
import com.zcloud.domain.persistence.repository.DomainGroupUserRepository;
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:29:27
 */
@Component
@AllArgsConstructor
public class DomainGroupAddExe {
    private final DomainGroupGateway domainGroupGateway;
    private final DomainGroupRepository domainGroupRepository;
    private final DomainGroupUserRepository domainGroupUserRepository;
    private final DomainGroupUserCoConvertor domainDepartmentUserCoConvertor;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(DomainGroupAddCmd cmd) {
        DomainGroupE domainGroupE = new DomainGroupE();
        BeanUtils.copyProperties(cmd, domainGroupE);

        //判断一个小组，只能负责一个领域；领域小组必须为，分子公办公司；
        cmd.getCorpinfoId();

/** 2026-06-02 需求变更：领域类型与领域组不做强关联，公司内可创建多个领域组
        List<DomainGroupDO> domainGroupDOList =domainGroupRepository.getListByCorpinfoId(cmd.getCorpinfoId());
        if (CollUtil.isNotEmpty(domainGroupDOList)) {
            throw new BizException("该公司已存在领域小组");
        }
*/
        boolean res = false;
        try {
            res = domainGroupGateway.add(domainGroupE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        List<DomainGroupUserAddCmd> domainGroupUserAddCmdList = cmd.getDomainGroupUserAddCmdList();

        List<DomainGroupUserDO> domainGroupUserDOList =domainDepartmentUserCoConvertor.converCmdsToDOs(domainGroupUserAddCmdList);
        domainGroupUserDOList.forEach(
                domainGroupUserDO -> {
                    domainGroupUserDO.setDomainGroupId(domainGroupE.getDomainGroupId());
                    domainGroupUserDO.setDomainGroupUserId(Tools.get32UUID());
                }
        );
        domainGroupUserRepository.saveBatch(domainGroupUserDOList);
        return true;
    }
}

