package com.tax.file.service.async.income;

import com.tax.file.constants.FileConstants;
import com.tax.file.model.FIncomeInvoice;
import com.tax.file.model.FIncomeInvoiceExample;
import com.tax.file.model.TkTaxUser;
import com.tax.file.model.TkTaxUserExample;
import com.tax.file.mq.rabbit.producer.RabbitMQMessageProducer;
import com.tax.file.service.api.FIncomeInvoiceService;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.service.async.apply.AsyncTkFileApplyService;
import com.tax.file.service.async.strategy.ExecuteTimesLimitStrategy;
import com.tax.file.utils.income.IncomeFileExcelUtil;
import com.yxcheng.token.constants.RedisContants;
import com.yxcheng.token.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;


@Component
public class IncomeApplyTask {
    private static final Logger logger = LoggerFactory.getLogger(IncomeApplyTask.class);

    @Autowired
    private FIncomeInvoiceService incomeInvoiceService;

    @Autowired
    private AsynIncomeApplyService asynIncomeApplyService;

    public void apply() {
        CountDownLatch latch = null;
        FIncomeInvoiceExample example = new FIncomeInvoiceExample();
        example.createCriteria().andApplyStatusEqualTo("0").andDelFlagEqualTo("0");
        List<FIncomeInvoice> invoices = incomeInvoiceService.selectByExample(example);


        if(invoices!=null && invoices.size()>0){
            Map<String,List<FIncomeInvoice>> map  = IncomeUtil.splitToTaxno(invoices);
            latch = new CountDownLatch(map.size());
            for (Map.Entry<String,List<FIncomeInvoice>> entry : map.entrySet()) {
                asynIncomeApplyService.doIncomeApply(latch,entry.getKey(),entry.getValue());
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        Map<String, List<FIncomeInvoice>> map = new HashMap<>();
        List<FIncomeInvoice>list = new ArrayList<>();
        FIncomeInvoice incomeInvoice = new FIncomeInvoice();
        incomeInvoice.setInvKind("12345");
        list.add(incomeInvoice);

        map.put("123",list);
        System.out.println(map);

        List<FIncomeInvoice>list1 =  map.get("123");
        FIncomeInvoice incomeInvoice1 = new FIncomeInvoice();
        incomeInvoice1.setInvKind("12345345");
        list1.add(incomeInvoice1);
        System.out.println(map);
    }
}
