package com.tax.token.job;

import com.tax.token.constants.TokenConstants;
import com.tax.token.model.*;
import com.tax.token.service.api.*;
import lombok.extern.slf4j.Slf4j;
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.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Slf4j
@Component
public class SynTokenService {
    @Autowired
    private TkTokenService tokenService;
    @Autowired
    private TkTokenLogService tokenLogService;
    @Autowired
    private TkZoneInfoService zoneInfoService;
    @Autowired
    private TkServerService tkServerService;
    @Autowired
    private TkTokenRemarkLogService tkTokenRemarkLogService;
    @Autowired
    private TkUserService tkUserService;

    public void handleToken(String uuId, TkToken tkToken) throws Exception {
        TkZoneInfoExample zoneInfoExample = new TkZoneInfoExample();
        zoneInfoExample.createCriteria().andZoneCodeEqualTo(tkToken.getZoneCode());
        log.info("{} SynTokenService, the taxno is {}", uuId,  tkToken.getTaxno());
        TkZoneInfo tkZoneInfo = zoneInfoService.selectByExample(zoneInfoExample).get(0);
        tokenService.synZoneInfo(tkZoneInfo);

        TkServerExample serverExample = new TkServerExample();
        serverExample.createCriteria().andServerNoEqualTo(tkToken.getServerNo());
        TkServer tkServer = tkServerService.selectByExample(serverExample).get(0);

        TkUser tkUser = tkUserService.getUserByUserCode(tkToken.getUserCode(), TokenConstants.FUNCTION_NO_FPY);
        log.info("{} SynTokenService start {}", uuId, tkToken.getTaxno());
        // 向第三方获取token
        tkToken.setZoneFlag(tkUser.getZoneFlag());
        tokenService.getTokenByThird(uuId, tkToken, tkZoneInfo,tkServer,false, "1");
        log.info("{} SynTokenService end {}", uuId, tkToken.getTaxno());
        //更新token最新的数据
        tokenService.updateTokenInfo(uuId, tkToken);
        tokenLogService.saveTokenLog(uuId, tkToken, "1");
        //记录问题数据日志
        tkTokenRemarkLogService.saveRemarkLog(uuId, tkToken);
    }

    @Async("myExecutor")
    public Future<String> asyncTask(CountDownLatch latch, String uuId, TkToken tkToken){
        try {
            this.handleToken(uuId, tkToken);
        } catch (Exception e) {
            log.error("{} async task is error!", uuId, e);
        } finally {
            latch.countDown();
        }
        return new AsyncResult<>("tkToken taxNo=" + tkToken.getTaxno() + " userCode=" + tkToken.getUserCode() + " accomplished!");
    }

}
