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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tax.file.context.FileDownContext;
import com.tax.file.model.*;
import com.tax.file.service.api.*;
import com.tax.file.service.async.strategy.ExecuteTimesLimitStrategy;
import com.tax.file.utils.NationUtil;
import com.yxcheng.token.utils.DateUtils;
import com.yxcheng.token.utils.FileUtils;
import com.yxcheng.token.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class DataFileDownService {

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

    @Autowired
    protected TkFileService tkFileService;
    @Autowired
    protected FileLogService fileLogService;
    @Autowired
    protected FileTaxLogService fileTaxLogService;
    @Autowired
    protected TkFileSegmentService tkFileSegmentService;
    @Autowired
    protected ExecuteTimesLimitStrategy timesLimitStrategy;
    @Autowired
    private FileTokenService fileTokenService;


    protected TkFileSegment assembleTkTFileSegment(TkFile tkFile, String fileName, String fileDPath) {
        Date curDate = DateUtils.getDate();
        TkFileSegment entity = new TkFileSegment();
        entity.setUserName(tkFile.getUserName());
        entity.setFileName(fileName);
        entity.setPath(fileDPath);
        entity.setInvSpec(tkFile.getInvSpec());
        entity.setInvType(tkFile.getInvType());
        entity.setTaxno(tkFile.getTaxno());
        entity.setSuffix(FileUtils.getSuffix(fileName));
        entity.setIsComplete("0");
        entity.setInvDateStart(tkFile.getInvDateStart());
        entity.setInvDateEnd(tkFile.getInvDateEnd());
        entity.setApplyDate(tkFile.getApplyDate());
        entity.setFileMonth(tkFile.getFileMonth());
        entity.setFileMd5(tkFile.getFileMd5());
        entity.setZoneCode(tkFile.getZoneCode());
        entity.setCreateDate(curDate);
        entity.setUpdateDate(curDate);
        return entity;
    }


    protected JSONObject fileDownQuery(String uuidFlag, TkTaxUser taxUser, FileDownContext context, Date applyDateStart, Date applyDateEnd, PageModel page){
        TkFile query = new TkFile();
        query.setTaxno(taxUser.getTaxno());
        query.setToken(context.getToken());
        query.setInvDateStart(applyDateStart);
        query.setInvDateEnd(applyDateEnd);
        query.setZoneCode(taxUser.getZoneCode());
        Date reqDate = new Date();

        JSONObject result = null;
        try {
            result = NationUtil.fileDownQuery(uuidFlag, query, page);
            if(result!=null){
                if("01".equals(result.getString("key1"))){
                    //返回成功但是没有数据
                    if(result.getJSONObject("key2").getInteger("iTotalRecords") == 0){
                        return null;
                    }
                    return result;
                } else if(!"01".equals(result.getString("key1"))){
                    fileLogService.saveLog(uuidFlag, taxUser.getUserName(), taxUser.getTaxno(), reqDate, JSON.toJSONString(query), JSON.toJSONString(result),new Date(),"2");
                } else if("w4000000".equals(result.getString("key1"))) {
                    fileTokenService.noticeGetNewToken(uuidFlag, taxUser);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            fileLogService.saveLog(uuidFlag, taxUser.getUserName(), taxUser.getTaxno(), reqDate,JSON.toJSONString(query), e.getMessage(),new Date(),"2");
        }
        return null;
    }

    public void insertSegmentList(List<TkFileSegment> segments) {
        if(segments!=null && segments.size()>0){
            for(TkFileSegment segment :segments){
                tkFileSegmentService.insertSelective(segment);
            }
        }
    }

    protected JSONObject fileDownloadQuery(String uuidFlag, TkTaxUser taxUser, PageModel page, DownFileReqModel downFileReqModel){
        Date reqDate = new Date();
        JSONObject result = null;
        String responseResult = "";
        try {
            result = NationUtil.fileDownloadQuery(uuidFlag, page, downFileReqModel);
            if(result!=null){
                responseResult = StringUtil.getShortLog(JSON.toJSONString(result), 500);
                if("01".equals(result.getString("key1"))){
                    //返回成功但是没有数据
//                    if(result.getJSONObject("key2").getInteger("iTotalRecords") == 0){
//                        result = null;
//                    }
                } else if("w4000000".equals(result.getString("key1"))) {
                    fileTokenService.noticeGetNewToken(uuidFlag, taxUser);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseResult = StringUtil.getShortLog(e.getMessage(), 500);
            logger.error(uuidFlag + ",taxno is " + downFileReqModel.getCert() + " is error!" + e.getMessage());
        }
        fileTaxLogService.saveLog(uuidFlag, taxUser.getUserName(), taxUser.getTaxno(), reqDate, JSON.toJSONString(downFileReqModel, SerializerFeature.WriteDateUseDateFormat)
                , responseResult, DateUtils.getDate(),"2", downFileReqModel, "0");
        return result;
    }

    protected JSONObject fileDownload(String uuidFlag, TkTaxUser taxUser, TkFile query){
        Date reqDate = new Date();
        JSONObject result = null;
        String responseResult = "";
        try {
            result = NationUtil.fileDown(uuidFlag, query);
            if(result!=null){
                responseResult = StringUtil.getShortLog(JSON.toJSONString(result), 500);
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseResult = StringUtil.getShortLog(e.getMessage(), 500);
            logger.error(uuidFlag + ",taxno is " + taxUser.getTaxno() + " is error!" + e.getMessage());
        }
        fileTaxLogService.saveLog(uuidFlag, taxUser.getTaxno(), reqDate, JSON.toJSONString(query, SerializerFeature.WriteDateUseDateFormat)
                , responseResult, DateUtils.getDate(),"3", query, "0");
        return result;
    }

}
