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

import com.google.common.collect.Lists;
import com.tax.file.model.TkFile;
import com.tax.file.model.TkTaxUser;
import com.tax.file.service.api.TkFileService;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.utils.NationDic;
import com.yxcheng.token.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Component
public class ResetApplyService {

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

    @Autowired
    protected TkTaxUserService tkTaxUserService;
    @Autowired
    protected TkFileService tkFileService;

    @Async("resetExecutor")
    public Future<String> doResetApply(String uuidFlag, CountDownLatch latch, TkTaxUser taxUser) {
        String taxno = taxUser.getTaxno();
        String curMonth = DateUtils.getDataString(new SimpleDateFormat("yyyyMM"));
        try {
            boolean userDownFlag = false;
            List<TkFile> waitUpdateFileList = Lists.newArrayList();
            List<TkFile> applyFileList = tkFileService.queryResetFileList(taxUser);
            for(TkFile applyFile:applyFileList) {
                if(applyFile.getDownStatus().equals("0")) {
                    userDownFlag = true;
                } else {
                    String fileMonth = applyFile.getFileMonth();
                    //跨月后不再申请部分月份，直接作废
                    if(applyFile.getFileDataType().equals("0") && !curMonth.equals(fileMonth)) {
                        applyFile.setApplyErrorCode("2");
                        applyFile.setApplyStatus(NationDic.APPLY_STATUS_FAIL);
                        applyFile.setResponseStatus(NationDic.RESPONSE_STATUS_PAST);
                        applyFile.setUpdateDate(DateUtils.getDate());
                        tkFileService.updateApplyInfoByPrimaryKey(applyFile);
                        userDownFlag = true;
                    } else {
                        //如果下载结果 3-文件已过期
                        if(applyFile.getErrorCode().equals("3") || applyFile.getErrorCode().equals("6")) {
                            if(applyFile.getApplyErrorCode().equals("1") && DateUtils.dayCompare(applyFile.getOldApplyDate(), DateUtils.getDate()) > 30) {
                                applyFile.setApplyStatus("0");
                                applyFile.setDownStatus("0");
                                applyFile.setOldApplyDate(null);
                                applyFile.setResetDate(DateUtils.getDate());
                                waitUpdateFileList.add(applyFile);
                            } else if(applyFile.getApplyErrorCode().equals("0")) {
                                if(null==applyFile.getResetDate() ||
                                        (null!=applyFile.getResetDate() && DateUtils.dayCompare(applyFile.getResetDate(), DateUtils.getDate()) > 0)) {
                                    if(applyFile.getFileDataType().equals("0")) {
                                        applyFile.setDownStatus("0");
                                        applyFile.setDownCount(0);
                                        applyFile.setResetDate(DateUtils.getDate());
                                    } else {
                                        applyFile.setApplyStatus("0");
                                        applyFile.setDownStatus("0");
                                        applyFile.setOldApplyDate(null);
                                        applyFile.setResetDate(DateUtils.getDate());
                                    }
                                    waitUpdateFileList.add(applyFile);
                                }
                            }

                        } else if(applyFile.getErrorCode().equals("4") || applyFile.getErrorCode().equals("7")) {
                            //一直没有生成的，过了日期重新申请
                            if(null!=applyFile.getOldApplyDate() && DateUtils.dayCompare(applyFile.getOldApplyDate(), DateUtils.getDate()) > 30) {
                                applyFile.setApplyStatus("0");
                                applyFile.setDownStatus("0");
                                applyFile.setOldApplyDate(null);
                                applyFile.setResetDate(DateUtils.getDate());
                                waitUpdateFileList.add(applyFile);
                            } else if(null==applyFile.getResetDate() ||
                                    (null!=applyFile.getResetDate() && DateUtils.dayCompare(applyFile.getResetDate(), DateUtils.getDate()) > 0)) {
                                applyFile.setDownStatus("0");
                                applyFile.setDownCount(0);
                                applyFile.setResetDate(DateUtils.getDate());
                                waitUpdateFileList.add(applyFile);
                            }
                        } else {
                            logger.info(uuidFlag + " doResetApply " + taxno + " no need process! ");
                        }
                    }

                }
            }
            if(waitUpdateFileList.size()>0) {
                tkFileService.updateApplyFileList(waitUpdateFileList);
                userDownFlag = true;
            }
            if(userDownFlag) {
                Date curDate = DateUtils.getDate();
                taxUser.setApplyStatus("1");
                taxUser.setDownStatus("1");
                taxUser.setFixApplyDownDate(curDate);
                taxUser.setUpdateDate(curDate);
                tkTaxUserService.updateByPrimaryKeySelective(taxUser);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info(uuidFlag + " doResetApply " + taxno + " error is " + e.getMessage());
        }finally {
            latch.countDown();
        }
        return new AsyncResult<>("doResetApply taxno="+taxno+" accomplished!");
    }

    @Async("resetExecutor")
    public Future<String> doResetMonthApply(String uuidFlag, CountDownLatch latch, TkTaxUser taxUser) {
        String taxno = taxUser.getTaxno();
        try {
            Date curDate = DateUtils.getDate();
            taxUser.setApplyStatus("1");
            taxUser.setDownStatus("1");
            taxUser.setInit("0");
            taxUser.setOverFlag("0");
            taxUser.setFixHistoryDate(curDate);
            taxUser.setUpdateDate(curDate);
            tkTaxUserService.updateByPrimaryKeySelective(taxUser);
        }catch (Exception e){
            e.printStackTrace();
            logger.info(uuidFlag + " doResetMonthApply " + taxno + " error is " + e.getMessage());
        }finally {
            latch.countDown();
        }
        return new AsyncResult<>("doResetMonthApply taxno="+taxno+" accomplished!");
    }
}
