package com.zksy.data.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.exception.DbException;
import com.zksy.data.annotation.XhDataLogRecord;
import com.zksy.data.domain.po.XcrAbnormalBusinessOperations;
import com.zksy.data.domain.response.XcrAbnormalBusinessOperationsResponse;
import com.zksy.data.mapper.XcrAbnormalBusinessOperationsMapper;
import com.zksy.data.service.XcrAbnormalBusinessOperationsService;
import com.zksy.data.utils.RedisService;
import com.zksy.data.utils.XhRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.Vector;

/**
* @author Administrator
* @description 针对表【xcr_abnormal_business_operations(经营异常名录信息)】的数据库操作Service实现
* @createDate 2024-10-19 16:45:29
*/
@Service
@Slf4j
public class XcrAbnormalBusinessOperationsServiceImpl extends ServiceImpl<XcrAbnormalBusinessOperationsMapper, XcrAbnormalBusinessOperations>
    implements XcrAbnormalBusinessOperationsService{
    @Autowired
    private XhRequestUtil xhRequestUtil;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override@XhDataLogRecord("同步企业异常名录详细信息")
    public void saveDataByUniCode(String address) {
        //模拟从数据库中取数据大约为3000-4000条
        List<String> creditCodes = (List<String>) redisService.getList("creditCodes").get(0);
        Vector<XcrAbnormalBusinessOperations> toDatabaseList = new Vector<>();
        //这个方法会占用特别长的时间
        creditCodes.parallelStream().forEach(creditCode -> {
            List<XcrAbnormalBusinessOperations> list = xhRequestUtil.httpRequestByUniCode(creditCode, address,
                    XcrAbnormalBusinessOperationsResponse.class,
                    XcrAbnormalBusinessOperations.class
            );
            if(list != null){
                toDatabaseList.addAll(list);
            }
        });
        transactionTemplate.execute((s)->{
            try {
                this.remove(null);
                this.saveBatch(toDatabaseList);
            } catch (Exception e) {
                s.setRollbackOnly();
                throw new DbException(e);
            }
            return null;
        });
        log.info("企业异常名录详细信息同步完成");
    }
}




