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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tax.file.context.FileDownContext;
import com.tax.file.model.DownFileModel;
import com.tax.file.model.PageModel;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class FileDownQueryPageService extends AbstractFileDownService{

    public boolean doPage(String uuidFlag, DownFileModel model, FileDownContext context, Date applyDateStart, Date applyDateEnd) {
        //是否下载处理完标记
        PageModel page = new PageModel();
        int runNum = 0;

        //结果是否返回标记
        boolean resultFlag = executeData(uuidFlag, model,context,applyDateStart,applyDateEnd,page);
        while ((resultFlag && page.isNextPage())) {
            resultFlag = executeData(uuidFlag, model, context, applyDateStart, applyDateEnd, page);
            runNum++;
            if (runNum > 100) {
                // 防止一个线程占用太多时间，也防止死循环
                break;
            }
        }
        return model.isFinish();
    }

    private boolean executeData(String uuidFlag, DownFileModel model, FileDownContext context, Date applyDateStart, Date applyDateEnd,PageModel page) {
        JSONObject result = fileDownQuery(uuidFlag, model.getTaxUser(), context, applyDateStart, applyDateEnd,page);
        if(result != null){
            JSONObject key2 = result.getJSONObject("key2");
            JSONArray invList = key2.getJSONArray("aaData");

            Integer iTotalRecords = key2.getInteger("iTotalRecords");
            Integer iTotalDisplayRecords = key2.getInteger("iTotalDisplayRecords");
            Integer sEcho = key2.getInteger("sEcho");

            logger.info(uuidFlag + " taxno is " + model.getTaxUser().getTaxno() +  " has total data: " + invList.size() + ", iTotalRecords:" + iTotalRecords +", sEcho:" + sEcho);

            page.setiTotalRecords(iTotalRecords);
            page.setsEcho(sEcho);
            page.setiTotalDisplayRecords(iTotalDisplayRecords);
            page.setCurPage(page.getCurPage() + 1);

            model.setInvList(invList);

            if (!doDownLoad(uuidFlag, model)) {
                model.setFinish(false);
            }
            return true;
        }
        model.setFinish(false);
        return false;
    }

}
