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.*;
import com.tax.file.utils.NationDic;
import com.yxcheng.token.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @ProjectName: tax-sys-test
 * @Package: com.tax.file.service.async.down
 * @ClassName: FileDownQueryService
 * @Author: ddx
 * @Description: ${description}
 * @Date: 2021-09-14 17:20
 * @Version: 1.0
 */
@Component
public class FileDownQueryService extends AbstractFileDownService {

    private static final Logger logger = LoggerFactory.getLogger(FileDownQueryService.class);

    public boolean runDownloadFileList(String uuidFlag, DownFileModel model, FileDownContext context, String applyDateStart, String applyDateEnd, TkTaxUser taxUser) {
        boolean saveFlag = true;
        String curMonth = DateUtils.getDataString(new SimpleDateFormat("yyyyMM"));
        //准备待下载列表
        Map<String, Map<String, TkFile>> fileGroup = tkFileService.queryWaitDownFileMap(taxUser);
        for(String fileGroupKey:fileGroup.keySet()) {
            String fileInvSpec = fileGroupKey.split("=")[2];
            String fileInvType = fileGroupKey.split("=")[3];
            Map<String, TkFile> tkFileMap = fileGroup.get(fileGroupKey);
            model.setTkFileMap(tkFileMap);
            boolean resultFlag = downloadInvFileList(uuidFlag, model, context.getToken(), applyDateStart, applyDateEnd, taxUser, fileInvSpec, fileInvType);

            logger.info(uuidFlag + " taxno is " + model.getTaxUser().getTaxno() +  " applyDateStart: " + applyDateStart
                    + ", applyDateEnd:" + applyDateEnd +", fileInvSpec:" + fileInvSpec + ", fileInvType:" + fileInvType + ",resultFlag:" + resultFlag);

            if(resultFlag) {
                if(tkFileMap.size()>0) {
                    for(String tkFileKey:tkFileMap.keySet()) {
                        TkFile tkFile = tkFileMap.get(tkFileKey);
                        String fileMonth = tkFile.getFileMonth();
                        //跨月后不再申请部分月份，直接作废
                        if(tkFile.getFileDataType().equals("0") && !curMonth.equals(fileMonth)) {
                            tkFile.setApplyErrorCode("2");
                            tkFile.setApplyStatus(NationDic.APPLY_STATUS_FAIL);
                            tkFile.setResponseStatus(NationDic.RESPONSE_STATUS_PAST);
                            tkFile.setUpdateDate(DateUtils.getDate());
                            tkFileService.updateApplyInfoByPrimaryKey(tkFile);
                        } else {
                            //如果申请达到当月的结束申请流程次数并且不再重置重新申请
                            if(tkFile.getApplyErrorCode().equals("6")) {
                                tkFile.setDownStatus("3");
                                tkFile.setResponseStatus("3");
                            } else {
                                tkFile.setDownStatus("2");
                            }
                            tkFile.setErrorCode(DownFileInfoModel.NO_FIND_RECORD);
                            tkFile.setFileName(DownFileInfoModel.NO_FIND_RECORD_CN);
                            tkFile.setUpdateDate(DateUtils.getDate());
                            tkFileService.updateByPrimaryKey(tkFile);
                        }
                    }
                }
            } else {
                saveFlag = false;
            }
        }

        return saveFlag;
    }

    private boolean downloadInvFileList(String uuidFlag, DownFileModel model, String tokenCode,
                                     String applyDateStart, String applyDateEnd, TkTaxUser taxUser, String fileInvSpec, String fileInvType) {

        //局端对应类型列表
        DownFileReqModel downFileReqModel = new DownFileReqModel();
        downFileReqModel.setFileInvSpec(fileInvSpec);
        downFileReqModel.setFileInvType(fileInvType);
        downFileReqModel.setCert(taxUser.getTaxno());
        downFileReqModel.setToken(tokenCode);
        downFileReqModel.setApplyDateStart(applyDateStart);
        downFileReqModel.setApplyDateEnd(applyDateEnd);
        downFileReqModel.setDqdm(taxUser.getZoneCode());

        //是否下载处理完标记
        PageModel page = new PageModel();
        int runNum = 0;
        //结果是否返回标记
        boolean resultFlag = executeData(uuidFlag, model, page, downFileReqModel, true);
        while ((resultFlag && page.isNextPage())) {
            resultFlag = executeData(uuidFlag, model, page, downFileReqModel, false);
            runNum++;
            if (runNum > 100) {
                // 防止一个线程占用太多时间，也防止死循环
                break;
            }
        }
        return resultFlag;
    }

    private boolean executeData(String uuidFlag, DownFileModel model, PageModel page, DownFileReqModel downFileReqModel, boolean isFirst) {
        JSONObject result = fileDownloadQuery(uuidFlag, model.getTaxUser(), page, downFileReqModel);
        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 + 1);
            page.setiTotalDisplayRecords(iTotalDisplayRecords);
            page.setCurPage(page.getCurPage() + 1);
            model.setInvList(invList);

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


}
