package com.zcloud.zcGbsServicer.command;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.exception.BizException;
import com.zcloud.zcGbsServicer.command.convertor.ResourcePersonCoConvertor;
import com.zcloud.zcGbsServicer.domain.enums.PersonTypeEnum;
import com.zcloud.zcGbsServicer.domain.gateway.RescueTeamGateway;
import com.zcloud.zcGbsServicer.domain.gateway.ResourcePersonGateway;
import com.zcloud.zcGbsServicer.domain.model.RescueTeamE;
import com.zcloud.zcGbsServicer.domain.model.ResourcePersonE;
import com.zcloud.zcGbsServicer.dto.RescueTeamUpdateCmd;
import com.zcloud.zcGbsServicer.dto.ResourcePersonAddCmd;
import com.zcloud.zcGbsServicer.dto.ResourcePersonUpdateCmd;
import com.zcloud.zcGbsServicer.persistence.dataobject.ResourcePersonDO;
import com.zcloud.zcGbsServicer.persistence.repository.ResourcePersonRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
* web-app
* @Author makejava
* @Date 2026-01-21 17:23:00
*/
@Component
@AllArgsConstructor
public class RescueTeamUpdateExe {
    private final RescueTeamGateway rescueTeamGateway;
    private final ResourcePersonGateway resourcePersonGateway;

    private final ResourcePersonRepository resourcePersonRepository;
    private final ResourcePersonCoConvertor resourcePersonCoConvertor;

    @Transactional(rollbackFor = Exception.class)
    public void execute(RescueTeamUpdateCmd rescueTeamUpdateCmd) {
        RescueTeamE rescueTeamE = new RescueTeamE();
        BeanUtils.copyProperties(rescueTeamUpdateCmd, rescueTeamE);
        boolean res = rescueTeamGateway.update(rescueTeamE);
        boolean resPer = executePerson(rescueTeamUpdateCmd.getRescueMembers(), rescueTeamE.getTeamId());
        if (!res || !resPer) {
            throw new BizException("修改失败");
        }
    }

    /**
     * 处理人员
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean executePerson(List<ResourcePersonAddCmd> cmds, String teamId) {
        Integer bizType = PersonTypeEnum.RESCUE_TEAM.getCode();
        resourcePersonGateway.deletedResourcePersonByBizId(teamId, bizType);
        if (CollUtil.isEmpty(cmds)) {
            return true;
        }
        List<ResourcePersonE> es = resourcePersonCoConvertor.converAddToEOs(cmds);
        es.forEach(e -> {
            e.relInfo(teamId, bizType);
        });
        return resourcePersonGateway.addBatch(es);
    }

}

