package com.dxhy.core.job.controller;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.redis.RedisUtils;
import com.dxhy.core.job.entity.SysDeptJobEntity;
import com.dxhy.core.job.service.InvoiceInterfaceService;
import com.dxhy.core.job.thread.RecordInvoiceThread;

import lombok.extern.slf4j.Slf4j;

/**
 * @author user
 */
@RestController
@RequestMapping("invoiceInterface")
@Slf4j

public class InvoiceInterfaceController extends AbstractController {

    @Resource
    private InvoiceInterfaceService invoiceInterfaceService;

    @Value("${jxjk.threadNum}")
    private Integer threadNum;
    @Value("${jxjk.invoiceParam}")
    private String invoiceParam;

    @Resource
    private RedisUtils redisUtils;

    @RequestMapping("/getRecordInvoice")
    public void getRecordInvoice() throws Exception {
        log.info("全票面底账采集任务开始-");
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(3), new ThreadPoolExecutor.CallerRunsPolicy());
        String[] types = invoiceParam.split(",");
        // 查询购方企业
        String dept = redisUtils.get("permission:dept");
        List<SysDeptJobEntity> sysDeptList = JSONObject.parseArray(dept, SysDeptJobEntity.class);
        for (String type : types) {
            for (SysDeptJobEntity org : sysDeptList) {
                if (!threadPoolExecutor.isShutdown()) {
                    String taxno = org.getTaxno();
                    threadPoolExecutor.execute(new RecordInvoiceThread(invoiceInterfaceService, type, taxno));
                }
            }
        }
        threadPoolExecutor.shutdown();
        threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
        log.info("全票面底账采集任务结束-");
    }
}
