package com.zksy.data.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.data.annotation.XhDataLogRecord;
import com.zksy.data.domain.po.XcrInvoiceIssuance;
import com.zksy.data.domain.response.XcrInvoiceIssuanceResponse;
import com.zksy.data.mapper.XcrInvoiceIssuanceMapper;
import com.zksy.data.service.XcrInvoiceIssuanceService;
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 java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import java.util.stream.Collectors;

/**
* @author 邵洋
* @description 针对表【xcr_invoice_issuance(发票开票信息)】的数据库操作Service实现
* @createDate 2024-10-17 11:08:47
*/
@Service
@Slf4j
public class XcrInvoiceIssuanceServiceImpl extends ServiceImpl<XcrInvoiceIssuanceMapper, XcrInvoiceIssuance>
    implements XcrInvoiceIssuanceService{
    @Autowired
    private XhRequestUtil xhRequestUtil;
    @Autowired
    private RedisService redisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @XhDataLogRecord("发票开票信息")
    public void saveDataByUniCode(String address) {
        //模拟从数据库中取数据大约为3000-4000条
        List<String> creditCodes = (List<String>) redisService.getList("creditNames").get(0);
        Vector<XcrInvoiceIssuance> toDatabaseList = new Vector<>();
        creditCodes.parallelStream().unordered().forEach(creditCode -> {
            List<XcrInvoiceIssuance> list = xhRequestUtil.httpRequestByUniCode(creditCode, address,
                    XcrInvoiceIssuanceResponse.class,
                    XcrInvoiceIssuance.class,
                    "TAXPAYNAME"
            );
            if(list != null){
                toDatabaseList.addAll(list);
            }
        });
        SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MMM-yy", Locale.US);
        List<XcrInvoiceIssuance> xcrInvoiceIssuances = toDatabaseList.stream().map(q -> {
            Date date;
            try {
                date = inputFormat.parse(q.getAPPLYDATE());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            q.setA(date);
            return q;
        }).collect(Collectors.toList());
        this.remove(null);
        this.saveBatch(xcrInvoiceIssuances);
        log.info("发票开票信息同步完成");
    }
}




