package com.tax.token.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tax.token.mapper.TkRealTokenLogMapper;
import com.tax.token.model.*;
import com.tax.token.service.api.TkRealTokenLogService;
import com.tax.token.utils.CleanCookieUtil;
import com.yxcheng.token.common.model.JsonResult;
import com.yxcheng.token.utils.DateUtils;
import com.yxcheng.token.utils.StringUtil;
import com.yxcheng.token.utils.UUIDGenerator;
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.Date;
import java.util.List;

@Transactional
@Component
@ComponentScan(basePackages = {"com.tax.token.dao", "com.tax.token.integration"})
public class TkRealTokenLogServiceImpl implements TkRealTokenLogService {

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

    @Autowired
    private TkRealTokenLogMapper realTokenLogMapper;

    @Override
    public void saveRealTokenLog(String uuId, TkToken token, String tokenFrom) {
        try {
            TkRealTokenLog tokenLog = new TkRealTokenLog();
            tokenLog.setTaxno(token.getTaxno());
            tokenLog.setReqDate(token.getReqDate());
            tokenLog.setToken(token.getToken());
            tokenLog.setTokenStatus(token.getTokenStatus());
            if(null!=token.getTaxUserInfo()) {
                tokenLog.setSecert(token.getTaxUserInfo());
            }
            tokenLog.setUserCode(token.getUserCode());
            tokenLog.setZoneCode(token.getZoneCode());
            tokenLog.setServerNo(token.getServerNo());
            tokenLog.setResContext(StringUtil.getShortLog(token.getResContext(), 3000));
            tokenLog.setIsValid(token.getCheckType());
            tokenLog.setIpServerNo(token.getTarget());
            tokenLog.setKeyCode(token.getSite());
            tokenLog.setLoginTaxno(token.getLoginTaxno());
            if(null==token.getResDate()) {
                tokenLog.setResDate(DateUtils.getDate());
            } else {
                tokenLog.setResDate(token.getResDate());
            }
            tokenLog.setLostTime(DateUtils.getMillSecondsDiff(tokenLog.getReqDate(),tokenLog.getResDate()));
            tokenLog.setTimeFlag(uuId);

            if(StringUtil.isNotEmpty(token.getResContext())) {
                CookieResultVo cookieResultVo = JSON.parseObject(token.getResContext(), CookieResultVo.class);
                tokenLog.setLoginType(cookieResultVo.getLoginType());
                tokenLog.setErrorCode(cookieResultVo.getCode());
                tokenLog.setErrorMessage(cookieResultVo.getMessage());
                tokenLog.setSecretMd5(cookieResultVo.getSession());
                tokenLog.setProxyIp(cookieResultVo.getProxyip());
                tokenLog.setTaxLoginName(cookieResultVo.getUserName());
            }

            realTokenLogMapper.insertSelective(tokenLog);
        } catch (Exception e) {
            logger.error(uuId + " saveRealTokenLog taxno " + token.getTaxno() + " is error! " ,e);
        }
    }

    @Override
    public void saveRealTokenLog(String uuId, Date reqDate, CleanCookieVo cleanCookieVo, CookieReq cookieReq, JsonResult result) {
        try {
            TkRealTokenLog tokenLog = new TkRealTokenLog();
            tokenLog.setTaxno(cookieReq.getTaxno());
            tokenLog.setReqDate(reqDate);
            if(null!=cookieReq.getUserInfoJson()) {
                tokenLog.setSecert(JSON.toJSONString(cookieReq.getUserInfoJson()));
            }
            tokenLog.setUserCode(cookieReq.getUserCode());
            tokenLog.setZoneCode(cookieReq.getZoneCode());
            tokenLog.setResContext(StringUtil.getShortLog(JSON.toJSONString(result), 3000));

            if(null != cleanCookieVo) {
                tokenLog.setToken(cleanCookieVo.getRequestContext());
                if(StringUtil.isNotEmpty(cleanCookieVo.getResponseContext())) {
                    tokenLog.setResContext(StringUtil.getShortLog(cleanCookieVo.getResponseContext(), 3000));
                }
            }
            tokenLog.setIsValid("9");
            tokenLog.setIpServerNo(cookieReq.getTarget());
            tokenLog.setKeyCode(cookieReq.getSite());
            tokenLog.setResDate(DateUtils.getDate());
            tokenLog.setLostTime(DateUtils.getMillSecondsDiff(tokenLog.getReqDate(),tokenLog.getResDate()));
            tokenLog.setTimeFlag(uuId);
            realTokenLogMapper.insertSelective(tokenLog);
        } catch (Exception e) {
            logger.error(uuId + " saveRealTokenLog clean taxno " + cookieReq.getTaxno() + " is error! " ,e);
        }
    }

    public PageInfo<TkRealTokenLog> selectRealTokenListPage(TokenReportReq tokenReportReq) {
        logger.info("selectRealTokenListPage tokenList params is " + tokenReportReq);
        PageHelper.startPage(tokenReportReq.getPageNumber(), tokenReportReq.getPageSize());
        List<TkRealTokenLog> tokenList = realTokenLogMapper.selectRealTokenListPage(tokenReportReq);
        logger.info("selectRealTokenListPage tokenList size is " + tokenList.size());
        PageInfo<TkRealTokenLog> pageinfo = new PageInfo<TkRealTokenLog>(tokenList);
        return pageinfo;
    }

    public String queryRealTokenById(String applyId){
        TkRealTokenLog realTokenLog = realTokenLogMapper.selectByPrimaryKey(Integer.parseInt(applyId));
        return this.completePeriod(realTokenLog);
    }

    public String completePeriod(TkRealTokenLog realTokenLog) {
        JSONObject requestParam = new JSONObject();
        if (StringUtil.isNotEmpty(realTokenLog.getTokenStatus()) && realTokenLog.getTokenStatus().equals("1")) {
            requestParam.put("cookie", realTokenLog.getToken());
            requestParam.put("dqdm", realTokenLog.getZoneCode());
        }
        IncomeCompletePeriod incomeCompletePeriod = IncomeCompletePeriod.builder()
                .requestParam(requestParam)
                .reqContext(realTokenLog.getSecert())
                .resContext(realTokenLog.getResContext())
                .build();
        return JSON.toJSONString(incomeCompletePeriod);
    }

    public CleanCookieVo cleanTokenById(String applyId) {
        logger.info("cleanTokenById params is " + applyId);
        TkRealTokenLog realTokenLog = realTokenLogMapper.selectByPrimaryKey(Integer.parseInt(applyId));
        CleanCookieVo cleanMap = null;
        String uuId = UUIDGenerator.generate();
        try {
            if(StringUtil.isNotEmpty(realTokenLog.getSecretMd5())) {
                CookieReq cookieReq = new CookieReq();
                cookieReq.setUserCode(realTokenLog.getUserCode());
                cookieReq.setTaxno(realTokenLog.getTaxno());
                cookieReq.setUserInfo(realTokenLog.getSecretMd5());
                cookieReq.setZoneCode(realTokenLog.getZoneCode());
                cleanMap = CleanCookieUtil.cleanCookiebyMd5(uuId, cookieReq, "2");
                logger.info(uuId + " cleanTokenById taxno is " + realTokenLog.getTaxno() + " cleanCookie result is " + JSON.toJSONString(cleanMap));
            } else {
                cleanMap = new CleanCookieVo();
                cleanMap.setCode("-1");
                cleanMap.setMessage("没有md5信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(uuId + " cleanTokenById cleanCookie taxno is " + realTokenLog.getTaxno() + " ,send is error!" + e.getMessage());
        }
        if(null==cleanMap) {
            cleanMap = new CleanCookieVo();
            cleanMap.setCode("-1");
            cleanMap.setMessage("清理异常");
        }

        return cleanMap;
    }

    public String queryRealTokenByTokenId(String applyId){
        TkRealTokenLog realTokenLog = realTokenLogMapper.selectByPrimaryKey(Integer.parseInt(applyId));
        return JSON.toJSONString(realTokenLog);
    }
}
