package com.tax.file.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.tax.file.mapper.FileTokenMapper;
import com.tax.file.model.*;
import com.tax.file.model.token.TokenInfoModel;
import com.tax.file.service.api.FileServerService;
import com.tax.file.service.api.FileTokenService;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.utils.NationUtil;
import com.tax.file.utils.token.TokenFactory;
import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.common.service.AbstractService;
import com.yxcheng.token.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Transactional
@Component
@ComponentScan(basePackages = {"com.tax.file.dao", "com.tax.file.integration"})
public class FileTokenServiceImpl extends AbstractService<FileTokenMapper,FileTokenExample,FileToken> implements FileTokenService {

    protected   final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    protected RedisService redisService;
    @Autowired
    protected TkTaxUserService tkTaxUserService;
    @Autowired
    protected FileServerService fileServerService;

    public FileToken selectTokenInfoByTaxno(TkTaxUser taxUser) {
        FileTokenExample example = new FileTokenExample();
        example.createCriteria().andTaxnoEqualTo(taxUser.getTaxno()).andUserNameEqualTo(taxUser.getUserName());
        FileToken fileToken = getOne(example);

        //补充未入库税号信息
        if(null == fileToken) {
            FileToken nFileToken = new FileToken();
            nFileToken.setTaxno(taxUser.getTaxno());
            nFileToken.setTokenStatus(FileToken.TOKEN_STATUS_OFF);
            nFileToken.setReqDate(DateUtils.getDate());
            nFileToken.setZone(taxUser.getZoneCode());
            nFileToken.setTokenType(FileToken.TOKEN_TYPE_ZD);
            this.baseMapper.insertSelective(nFileToken);
        }
        return fileToken;
    }

    public List<FileToken> findWaitToken(Integer tokenId, Integer pageNum) {
        return this.baseMapper.findWaitTokenList(tokenId, pageNum);
    }

    public TokenInfoModel getTokenCodeByUrl(TkTaxUser taxUser) {
        FileServerExample fileServerExample = new FileServerExample();
        fileServerExample.createCriteria().andServerNoEqualTo(taxUser.getServerNo());

        FileServer fileServer = fileServerService.getOne(fileServerExample);
        TokenInfoModel tokenModel = TokenFactory.getTokenCode(taxUser, fileServer);

        return tokenModel;
    }

    public String getTokenCode(TkTaxUser taxUser) {
        String tokenCode = "";
        FileTokenExample example = new FileTokenExample();
        example.createCriteria().andTaxnoEqualTo(taxUser.getTaxno()).andUserNameEqualTo(taxUser.getUserName());
        FileToken fileToken = getOne(example);
        //补充未入库税号信息
        if(null == fileToken) {
            fileToken = new FileToken();
            fileToken.setTaxno(taxUser.getTaxno());
            fileToken.setTokenStatus(FileToken.TOKEN_STATUS_OFF);
            fileToken.setReqDate(DateUtils.getDate());
            fileToken.setZone(taxUser.getZoneCode());
            fileToken.setTokenType(FileToken.TOKEN_TYPE_ZD);
            fileToken.setUserName(taxUser.getUserName());
            fileToken.setUpdateDate(DateUtils.getDate());
            this.baseMapper.insertSelective(fileToken);
        }
        if(null != fileToken && fileToken.getTokenStatus().equals(FileToken.TOKEN_STATUS_ON)) {
            tokenCode = fileToken.getToken();
        }
        return tokenCode;
    }

    public void updateToken(FileToken fileToken) {
        this.baseMapper.updateToken(fileToken);
    }

    @Override
    public synchronized void noticeGetNewToken(String uuidFlag, TkTaxUser taxUser) {
        FileTokenExample example = new FileTokenExample();
        example.createCriteria().andTaxnoEqualTo(taxUser.getTaxno()).andUserNameEqualTo(taxUser.getUserName());
        FileToken fileToken = getOne(example);
        if(FileToken.TOKEN_STATUS_ON.equals(fileToken.getTokenStatus())) {
            fileToken.setTokenStatus(FileToken.TOKEN_STATUS_OFF);
            this.baseMapper.updateTokenStatus(fileToken);
            logger.info(uuidFlag + " run " + taxUser.getTaxno() + " notice token is success!");
        }
    }

    public boolean checkToken(String uuidFlag, TkTaxUser tkTaxUser, String token) {
        boolean tokenFlag = false;
        try {
            JSONObject result = NationUtil.incomeMonthQuery(uuidFlag, tkTaxUser, token);
            if(result!=null) {
                String code = result.getString("key1");
                if ("01".equals(code)) {
                    tokenFlag = true;
                } else if("w4000000".equals(code)) {
                    noticeGetNewToken(uuidFlag, tkTaxUser);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(uuidFlag + " checkToken " + tkTaxUser.getTaxno() +  " is error!" + e.getMessage());
        }
        return tokenFlag;
    }

    public List<Map<String, Object>> queryNotifyToken() {
        return baseMapper.queryNotifyToken();
    }

}
