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

import com.yd.common.enums.CommonEnum;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.api.service.ApiTaxationService;
import com.yd.csf.feign.dto.taxation.ApiObjectTaxationDto;
import com.yd.csf.feign.dto.taxation.ApiTaxationDto;
import com.yd.csf.service.dto.TaxationDto;
import com.yd.csf.service.model.Taxation;
import com.yd.csf.service.service.ITaxationService;
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.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Slf4j
@Service
public class ApiTaxationServiceImpl implements ApiTaxationService {

    @Autowired
    private ITaxationService iTaxationService;

    /**
     * 保存税务列表信息
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveTaxationList(ApiObjectTaxationDto dto) {
        //先删后新增
        iTaxationService.delByObjectBizId(dto.getObjectBizId());

        //新增
        if (!CollectionUtils.isEmpty(dto.getApiTaxationDtoList())) {
            List<Taxation> saveList = dto.getApiTaxationDtoList().stream().map(d -> {
                Taxation taxation = new Taxation();
                BeanUtils.copyProperties(dto,taxation);
                taxation.setTaxId(d.getTaxId());
                taxation.setTaxCountry(d.getTaxCountry());
                taxation.setTaxationBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_TAXATION.getCode()));
                return taxation;
            }).collect(Collectors.toList());
            iTaxationService.saveOrUpdateBatch(saveList);
        }
        return Result.success();
    }

    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public Result<List<Taxation>> list(ApiObjectTaxationDto dto) {
        List<Taxation> list = iTaxationService.queryList(TaxationDto.builder().objectBizId(dto.getObjectBizId()).build());
        return Result.success(list);
    }

    @Override
    public List<ApiTaxationDto> apiTaxationDtoList(String objectBizId) {
        List<ApiTaxationDto> apiTaxationDtoList = new ArrayList<>();
        Result<List<Taxation>> result = list(ApiObjectTaxationDto.builder().objectBizId(objectBizId).build());
        if (!CollectionUtils.isEmpty(result.getData())) {
            apiTaxationDtoList = result.getData().stream().map(d -> {
                ApiTaxationDto taxationDto = new ApiTaxationDto();
                BeanUtils.copyProperties(d,taxationDto);
                return taxationDto;
            }).collect(Collectors.toList());
        }
        return apiTaxationDtoList;
    }


}
