package com.yd.base.api.service.impl;

import com.yd.base.api.service.ApiRelObjectFieldService;
import com.yd.base.feign.request.relobjectfield.ApiRelObjectFieldListAddRequest;
import com.yd.base.feign.request.relobjectfield.ApiRelObjectFieldQueryRequest;
import com.yd.base.feign.response.relobjectfield.ApiRelObjectFieldQueryResponse;
import com.yd.base.service.model.RelObjectField;
import com.yd.base.service.service.IRelObjectFieldService;
import com.yd.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiRelObjectFieldServiceImpl implements ApiRelObjectFieldService {

    @Autowired
    private IRelObjectFieldService iRelObjectFieldService;

    /**
     * 查询-对象字段关系列表
     * @param request
     * @return
     */
    @Override
    public Result<List<ApiRelObjectFieldQueryResponse>> query(ApiRelObjectFieldQueryRequest request) {
        List<ApiRelObjectFieldQueryResponse> responses = iRelObjectFieldService.query(request);
        return Result.success(responses);
    }

    /**
     * 添加-单个对象和字段列表关系
     * @param request
     * @return
     */
    @Override
    public Result addRelObjectFieldList(ApiRelObjectFieldListAddRequest request) {
        //先删后新增
        //根据业务对象业务ID删除关系
        iRelObjectFieldService.delByObjectBizId(request.getObjectBizId());

        //新增
        if (!CollectionUtils.isEmpty(request.getApiObjectFieldValueDtoList())) {
            //非空列表新增
            List<RelObjectField> relObjectFieldList = request.getApiObjectFieldValueDtoList()
                    .stream().map(dto -> {
                        RelObjectField relObjectField = new RelObjectField();
                        BeanUtils.copyProperties(request,relObjectField);
                        BeanUtils.copyProperties(dto,relObjectField);
                        return relObjectField;
                    }).collect(Collectors.toList());
            iRelObjectFieldService.saveOrUpdateBatch(relObjectFieldList);
        }
        return Result.success();
    }

}
