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

import com.alibaba.fastjson.JSONObject;
import com.tax.file.model.*;
import com.tax.file.service.api.FIncomeInvoiceService;
import com.tax.file.service.api.FileServerService;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.utils.NationDic;
import com.tax.file.utils.NationUtil;
import com.tax.file.utils.income.IncomeFileExcelUtil;
import com.tax.file.utils.token.TokenFactory;
import org.apache.commons.lang.StringUtils;
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.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Component
public class AsynIncomeApplyService {

    @Autowired
    protected TkTaxUserService tkTaxUserService;
    @Autowired
    protected FileServerService fileServerService;
    @Autowired
    private FIncomeInvoiceService incomeInvoiceService;



    @Async("myExecutor")
    public Future<String> doIncomeApply(CountDownLatch latch, String taxno, List<FIncomeInvoice> list){
        try {

            TkTaxUserExample taxUserExample = new TkTaxUserExample();
            taxUserExample.createCriteria().andTaxnoEqualTo(taxno);

            TkTaxUser taxUser = tkTaxUserService.getOne(taxUserExample);


            FileServerExample fileServerExample = new FileServerExample();
            fileServerExample.createCriteria().andServerNoEqualTo(taxUser.getServerNo());

            FileServer fileServer = fileServerService.getOne(fileServerExample);

            String tokenCode = TokenFactory.getTokenCode(taxUser, fileServer).getToken();

            if(StringUtils.isBlank(tokenCode)){
                return new AsyncResult<>("AsynIncomeApplyService taxno="+taxUser.getTaxno()+" get token failed!");
            }



            String path = NationUtil.getIncomeFilePath(taxUser.getZoneCode(), taxUser.getUserName(), taxno);
            IncomeFileExcelUtil.generateExcel(list,path);


            FIncomeInvoice query = new FIncomeInvoice();
            query.setTaxno(taxno);
            query.setToken(tokenCode);
            query.setZoneCode(taxUser.getZoneCode());
            query.setFilePath(path);

            JSONObject jsonObject = NationUtil.incomeFileUpload(query);
            String key1 = jsonObject.getString("key1");
            if("01".equals(key1)){
                executeSuccessData(list);
            }else if("w4000000".equals(key1)){
                //记录日志
            }else{
                executeFailData(jsonObject,list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }

        return new AsyncResult<>("AsynIncomeApplyService taxno="+taxno+" accomplished!");
    }

    private void executeFailData(JSONObject jsonObject, List<FIncomeInvoice> list) {
        String info = NationDic.incomeUploadDic.get(jsonObject.getString("key1"));
        if(info.contains("$")) {
            int errornum = jsonObject.getInteger("key3");
            info = info.replace("$", String.valueOf(errornum + 1));
            System.out.println(info);
            FIncomeInvoice incomeInvoice = list.get((errornum - 1));
            incomeInvoice.setDelFlag("1");
            incomeInvoice.setResult(info);
            incomeInvoiceService.updateByPrimaryKeySelective(incomeInvoice);
        }
    }

    private void executeSuccessData(List<FIncomeInvoice> list) {
        for(FIncomeInvoice entity:list){
            entity.setApplyStatus("1");
            entity.setApplyDate(new Date());
            incomeInvoiceService.updateByPrimaryKeySelective(entity);
        }
    }
}
