package com.mortals.xhx.module.access.service.impl;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.access.dao.AccessDao;
import com.mortals.xhx.module.access.model.AccessEntity;
import com.mortals.xhx.module.access.service.AccessService;
import org.springframework.beans.factory.annotation.Autowired;
import com.mortals.xhx.module.access.model.AccessSystemEntity;
import com.mortals.xhx.module.access.model.AccessSystemQuery;
import com.mortals.xhx.module.access.service.AccessSystemService;
import org.springframework.util.ObjectUtils;
import java.util.Date;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* AccessService
* 区域接入 service实现
*
* @author zxfei
* @date 2024-07-02
*/
@Service("accessService")
@Slf4j
public class AccessServiceImpl extends AbstractCRUDServiceImpl<AccessDao, AccessEntity, Long> implements AccessService {
    @Autowired
    private AccessSystemService accessSystemService;
    
    @Override
    protected void saveAfter(AccessEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getAccessSystemList())){
            entity.getAccessSystemList().stream().peek(item->{
                item.setAccessId(entity.getId());
                item.setCreateUserId(this.getContextUserId(context));
                item.setCreateTime(new Date());
            }).count();
            accessSystemService.save(entity.getAccessSystemList());
        }
        super.saveAfter(entity, context);
    }

    @Override
    protected void updateAfter(AccessEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getAccessSystemList())){
            Long[] accessSystemIds = accessSystemService.find(new AccessSystemQuery().accessId(entity.getId())).stream().map(AccessSystemEntity::getId).toArray(Long[]::new);
            accessSystemService.remove(accessSystemIds,context);
            entity.getAccessSystemList().stream().peek(item ->{
                item.setAccessId(entity.getId());
                item.setCreateUserId(this.getContextUserId(context));
                item.setCreateTime(new Date());
                item.setUpdateUserId(this.getContextUserId(context));
                item.setUpdateTime(new Date());
            }).count();
            accessSystemService.save(entity.getAccessSystemList());
        }
        super.updateAfter(entity, context);
    }

    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        List<AccessSystemEntity> accessSystemlist = accessSystemService.find(new AccessSystemQuery().accessIdList(Arrays.asList(ids)));
        accessSystemService.removeList(accessSystemlist,context);
        super.removeAfter(ids, context, result);
    }
}