package com.tax.file.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.constants.RedisContants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.tax.file.constants.CommonConstants;
import com.tax.file.constants.FileConstants;
import com.tax.file.mapper.TkFileMapper;
import com.tax.file.mapper.TkTaxUserMapper;
import com.tax.file.model.FileServer;
import com.tax.file.model.FileServerExample;
import com.tax.file.model.FileUser;
import com.tax.file.model.FileUserExample;
import com.tax.file.model.InvoiceFileReq;
import com.tax.file.model.InvoiceFileRes;
import com.tax.file.model.InvoiceFileTaxManageFunctionReq;
import com.tax.file.model.InvoiceFileTaxManageReq;
import com.tax.file.model.TkFile;
import com.tax.file.model.TkFileExample;
import com.tax.file.model.TkTaxUser;
import com.tax.file.model.TkTaxUserExample;
import com.tax.file.model.TkUserUrl;
import com.tax.file.model.TkUserUrlExample;
import com.tax.file.service.api.FileServerService;
import com.tax.file.service.api.FileUserService;
import com.tax.file.service.api.InvoiceFileService;
import com.tax.file.service.api.TkFileService;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.service.api.TkUserUrlService;
import com.tax.file.service.async.apply.repeat.DataRepeatApplyService;
import com.tax.file.utils.CommonUtil;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.model.JsonResult;
import com.yxcheng.token.utils.DateUtils;
import com.yxcheng.token.utils.HttpHelper;
import com.yxcheng.token.utils.ObjectUtil;
import com.yxcheng.token.utils.ResponseContent;
import com.yxcheng.token.utils.StringUtil;
import com.yxcheng.token.utils.UUIDGenerator;

import lombok.extern.slf4j.Slf4j;


@Transactional
@Component
@ComponentScan(basePackages = {"com.tax.file.dao", "com.tax.file.integration"})
@Slf4j
public class InvoiceFileServiceImpl implements InvoiceFileService {
	@Autowired
	DataRepeatApplyService dataRepeatApplyService;
	
	@Autowired
    TkTaxUserService tkTaxUserService;
	@Autowired
    TkFileService tkFileService;
	@Autowired
	FileServerService fileServerService;
	@Autowired
    TkFileMapper tkFileMapper;
	@Autowired
	TkTaxUserMapper tkTaxUserMapper;
	@Autowired
	RestTemplate restTemplate;
	
    @Autowired
    TkUserUrlService tkUserUrlService;
    @Autowired
    FileUserService fileUserService;

    @Autowired
    RedisService redisService;
	
	/**
		* 发票文件下载
		*
		* @param invoiceFileReq
		* @return
    */
	@Override
	public JsonResult<Map> download(InvoiceFileReq invoiceFileReq) {
		Map result = new HashMap();
		//1.查询发票的文件信息
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date dd = DateUtils.getDateBefore(new Date(), Integer.parseInt(FileConstants.applyCycle));//计算申请周期
		Map map = new HashMap();
		//map.put("dd", sdf.format(dd));
		map.put("username", invoiceFileReq.getAccessKeyID());
		map.put("pageSize", CommonConstants.PAGE_SIZE);
		List<TkFile> tkFiles = tkFileMapper.getTkFilePage(map);
		
		log.info("发票文件下载，查询到发票数量："+tkFiles.size()+",用户名:"+invoiceFileReq.getAccessKeyID());
		
		if(tkFiles == null || tkFiles.size() == 0){
			result.put("taskno", "");
			result.put("quantity", 0);
			result.put("invoiceFileList",null);
			result.put("followTask", false);
			return new JsonResult(result);
		}
		
		//2.进行校验，数据重复下载不能超过5次
		String taskno = UUID.randomUUID().toString();
		Iterator<TkFile> iter = tkFiles.iterator();
		String tasknoOut = null;
		boolean flag = true;
		while(iter.hasNext()){
			TkFile tkFile = iter.next();
			
			if(StringUtil.isNotEmpty(tkFile.getTaskno())){
				tasknoOut = tkFile.getTaskno();
			}
			
			Integer downCount = tkFile.getDownCount();
			if(downCount == null){
				downCount = 0;
			}
			
			if(downCount < 5){
				flag = false;
			}
			
			tkFile.setDownCount(downCount+1);//统计下载次数
			tkFile.setTaskno(taskno);
		}
		
		if(flag){
			JsonResult jsonResult = new JsonResult();
			jsonResult.errorResponse(ResultEnum.file_down_repeat_error);
			jsonResult.setData(tasknoOut);//任务编号
			return jsonResult;
		}
		//3.更新任务编号
		int len = tkFileMapper.updateTasknoBatch(tkFiles);
		log.info("发票文件下载，更新任务编号："+len+",用户名:"+invoiceFileReq.getAccessKeyID());
		
		//4.组装返回JSON
		List<InvoiceFileRes> invoiceFiles = getFileModel(tkFiles);
		int quantity = invoiceFiles.size();
		result.put("taskno", taskno);
		result.put("quantity", quantity);
		result.put("invoiceFileList",invoiceFiles);
		result.put("followTask", quantity == CommonConstants.PAGE_SIZE?true:false);
		return new JsonResult(result);
	}
	
	//模型转换
	private List<InvoiceFileRes> getFileModel(List<TkFile> tkFiles){
		List<InvoiceFileRes> invoiceFiles = new ArrayList<InvoiceFileRes>();
		if(tkFiles != null && tkFiles.size() >0){
			Iterator<TkFile> iter = tkFiles.iterator();
			while(iter.hasNext()){
				TkFile tkFile = iter.next();
				InvoiceFileRes iFile = new InvoiceFileRes();
				iFile.setInvSpec(tkFile.getInvSpec());
				iFile.setInvType(tkFile.getInvType());
				iFile.setTaxno(tkFile.getTaxno());
				iFile.setUrl(tkFile.getUrl());
				iFile.setErrorCode(tkFile.getErrorCode());
				iFile.setApplyDate(tkFile.getApplyDate() != null?new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tkFile.getApplyDate()):"");
				iFile.setInvDate_start(tkFile.getInvDateStart() != null?new SimpleDateFormat("yyyy-MM-dd").format(tkFile.getInvDateStart()):"");
				iFile.setInv_date_end(tkFile.getInvDateEnd() != null?new SimpleDateFormat("yyyy-MM-dd").format(tkFile.getInvDateEnd()):"");
				invoiceFiles.add(iFile);
			}
		}
		return invoiceFiles;
	}
	
	 /**
		* 发票文件下载反馈
		*
		* @param invoiceFileReq
		* @return
     */
	@Override
	public JsonResult<Map> downloadRes(InvoiceFileReq invoiceFileReq) {
		log.info("发票文件下载反馈，任务编号："+invoiceFileReq.getTaskno()+",用户名:"+invoiceFileReq.getAccessKeyID());
		
		//1.查询任务编号
		int cou = tkFileMapper.getTkFileByTaskno(invoiceFileReq.getTaskno());
		
		if(cou == 0){
			 return new JsonResult().errorResponse(ResultEnum.file_taskno_error);
		}
		
		//2.更新
		TkFile tkFile = new TkFile();
		tkFile.setResponseStatus("1");
		tkFile.setResponseTime(new Date());
		TkFileExample example = new TkFileExample();
		example.createCriteria().andTasknoEqualTo(invoiceFileReq.getTaskno()).andDownCountGreaterThan(0);
		int len = tkFileMapper.updateByExampleSelective(tkFile, example);
		log.info("发票文件下载反馈，任务编号："+invoiceFileReq.getTaskno()+",更新记录数量："+len);
		return new JsonResult();
	}
	 /**
		* 获取税号信息
		*
		* @param invoiceFileReq
		* @return
    */
	@Override
	public JsonResult<Map> taxInfo(InvoiceFileReq invoiceFileReq) {
		if(StringUtil.isEmpty(invoiceFileReq.getTaxno())){
			return new JsonResult().errorResponse(ResultEnum.param_error);
		}
		
		TkTaxUserExample example = new TkTaxUserExample();
		example.createCriteria().andTaxnoEqualTo(invoiceFileReq.getTaxno())
		.andUserNameEqualTo(invoiceFileReq.getAccessKeyID());
		List<TkTaxUser> taxUsers = tkTaxUserMapper.selectByExample(example);
		
		if(taxUsers == null || taxUsers.size() == 0){
			return new JsonResult().errorResponse(ResultEnum.notfound);
		}
		
		TkTaxUser taxUser = taxUsers.get(0);
		Map map = new HashMap();
		
		if(!"1".equals(taxUser.getInit()) || taxUser.getApplyDownDate() == null){//如果税号未初始化或申请日期为空，直接返回信息
			map.put("username", invoiceFileReq.getAccessKeyID());
			map.put("taxno", invoiceFileReq.getTaxno());
			map.put("invDateStart", "");//开票日期起
			map.put("invDateEnd", "");//开票日期止
			map.put("downStatus", "0");//下载状态 '0'未下载 '1'已下载
			return new JsonResult(map);	
		}
		
		Date[] nationDates = DateUtils.getNationDates(FileConstants.applyCycle);
		Date preDateEnd = null;
		Date preDateStart = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		if(nationDates == null || nationDates.length == 0){
		    preDateEnd = DateUtils.getPreLastDay(new Date(), 1);
	        preDateStart = DateUtils.getApplyStartDate(preDateEnd, FileConstants.applyCycle);
		}else{
			preDateStart = nationDates[0];
			preDateEnd = nationDates[1];
		}
		
		boolean flag = false;
		if(preDateEnd != null){
			flag = taxUser.getApplyDownDate().after(preDateEnd);//申请下载时间是否在结束日期之后
		}

		map.put("username", invoiceFileReq.getAccessKeyID());
		map.put("taxno", invoiceFileReq.getTaxno());
		map.put("invDateStart", sdf.format(preDateStart));//开票日期起
		map.put("invDateEnd", sdf.format(preDateEnd));//开票日期止
		//map.put("applyStatus", flag?"1":"0");//申请状态 '0' 未申请  '1'已申请
		map.put("downStatus", flag && "2".equals(taxUser.getApplyStatus())?"1":"0");//下载状态 '0'未下载 '1'已下载
		map.put("runStatus", taxUser.getDelFlag());
		
		return new JsonResult(map);
	}
    /**
		* 税号初始化
		*
		* @param invoiceFileReq
		* @return
    */
	@Override
	public JsonResult<String> taxInit(InvoiceFileReq invoiceFileReq) {
		JsonResult result = new JsonResult();
		String optType = invoiceFileReq.getOptType();
		//1.查询server
		FileServerExample fileServerExample = new FileServerExample();
		fileServerExample.createCriteria().andServerNoEqualTo(FileConstants.getTaxInitServerNo());
		List<FileServer> fileServers = fileServerService.selectByExample(fileServerExample);
		
		if(fileServers == null || fileServers.size() == 0){
			 return JsonResult.errorResult("-1","未查询到服务");
		}
		
		FileServer server = fileServers.get(0);
		
		//2.查询taxUser
		TkTaxUserExample userExample = new TkTaxUserExample();
		userExample.createCriteria().andTaxnoEqualTo(invoiceFileReq.getTaxno())
		.andUserNameEqualTo(invoiceFileReq.getAccessKeyID());
		List<TkTaxUser> taxUsers = tkTaxUserService.selectByExample(userExample);
		
		//3.业务处理
		boolean flag = false;//如果一个税号注册过一次了，则不再红哥那注册
		if("0".equals(optType)){//增加
			if(taxUsers != null && taxUsers.size() > 0){
				 return JsonResult.errorResult("-1","此税号已注册");
			}
			JSONObject resultJson1 = callWh(invoiceFileReq,server);//调用内部服务1，文豪
			if(resultJson1 != null && !"0".equals(resultJson1.getString("errorCode"))){
				return JsonResult.errorResult("-1",resultJson1.getString("message")+",用户名"+invoiceFileReq.getAccessKeyID());
			}
			
			if(taxUsers == null || taxUsers.size() == 0){		
				
				TkTaxUserExample userExample2 = new TkTaxUserExample();
				userExample2.createCriteria().andTaxnoEqualTo(invoiceFileReq.getTaxno());
				List<TkTaxUser> taxUsers2 = tkTaxUserService.selectByExample(userExample2);
				
				TkTaxUser record = new TkTaxUser();
				record.setTaxno(invoiceFileReq.getTaxno());
				record.setUserName(invoiceFileReq.getAccessKeyID());
				record.setDelFlag(getDelFlag(optType));
				record.setZoneCode(invoiceFileReq.getZoneCode());
				record.setCreateDate(new Date());
				tkTaxUserService.insertSelective(record);
				
				//3.1 优化重复税号
				if(taxUsers2 != null && taxUsers2.size() > 0){
					flag = true;
					dataRepeatApplyService.init(record, taxUsers2.get(0));
				}
			}
		}else if("2".equals(optType) || "3".equals(optType)){//开启或停用
			if(taxUsers == null || taxUsers.size() == 0){
				 return JsonResult.errorResult("-1","此税号未注册");
			}
			
			if(taxUsers != null && taxUsers.size() > 0){
				TkTaxUser record = taxUsers.get(0);
				record.setDelFlag(getDelFlag(optType));
				tkTaxUserService.updateByPrimaryKey(record);
			}
		}else{
			 return JsonResult.errorResult("-1","optType操作类型不正确");
		}
		
		if("0".equals(optType) && flag == true){
			log.info("taxInit "+invoiceFileReq.getTaxno()+",ku is zhuce，not zai hongge na zhuce");
			return result;
		}
		
		JSONObject resultJson2 = callHg(invoiceFileReq);//调用内部服务2，红哥
		if(resultJson2 != null && !"0".equals(resultJson2.getString("CODE"))){
			return JsonResult.errorResult("-1",resultJson2.getString("MESSAGE")+",用户名"+invoiceFileReq.getAccessKeyID());
		}
				
		return result;
	}
	
	   /**
			* 获取发票下载的税号信息
			*
			* @param invoiceFileReq
			* @return
	    */
		@Override
		public JsonResult<String> getTaxInfo(InvoiceFileReq invoiceFileReq) {
			log.info("invoicefile getTaxInfo is start ,"+invoiceFileReq.toString());
			//1.处理功能编号01(发票下载)
			TkTaxUserExample example = new TkTaxUserExample();
			example.createCriteria().andTaxnoEqualTo(invoiceFileReq.getTaxno())
			.andUserNameEqualTo(invoiceFileReq.getAccessKeyID());
			List<TkTaxUser> taxUsers = tkTaxUserMapper.selectByExample(example);
			
			Map map = new HashMap();
			map.put("taxno", invoiceFileReq.getTaxno());
			List<Map> functionList = new ArrayList();
			
			if(taxUsers == null || taxUsers.size() == 0){
				functionList.add(getFunction("01","","","","","",""));
			}else{
				TkTaxUser taxUser = taxUsers.get(0);
				map.put("taxno", invoiceFileReq.getTaxno());


				
				if(!"1".equals(taxUser.getInit()) || taxUser.getApplyDownDate() == null){//如果税号未初始化或申请日期为空，直接返回信息
					functionList.add(getFunction("01",transUserStatus(taxUser.getDelFlag())
						,"0","","","",""));
				}else{
					Date[] nationDates = DateUtils.getNationDates(FileConstants.applyCycle);
					Date preDateEnd = null;
					Date preDateStart = null;
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					
					if(nationDates == null || nationDates.length == 0){
					    preDateEnd = DateUtils.getPreLastDay(new Date(), 1);
				        preDateStart = DateUtils.getApplyStartDate(preDateEnd, FileConstants.applyCycle);
					}else{
						preDateStart = nationDates[0];
						preDateEnd = nationDates[1];
					}
					
					boolean flag = false;
					if(preDateEnd != null){
						flag = taxUser.getApplyDownDate().after(preDateEnd);//申请下载时间是否在结束日期之后
					}
                    String tokenStatusMsg = redisService.get(RedisContants.FILE_TOKEN_STATUS + taxUser.getTaxno());

					functionList.add(getFunction(
							"01", transUserStatus(taxUser.getDelFlag()),
							flag && "2".equals(taxUser.getApplyStatus())?"1":"0",
							taxUser.getDownDate()!=null?sdf.format(taxUser.getDownDate()):"",
							sdf.format(preDateStart),sdf.format(preDateEnd),tokenStatusMsg));
				}
			}
				
			//处理功能编号02(异步采集)
			TkUserUrlExample userUrlExample = new TkUserUrlExample();
			userUrlExample.createCriteria().andAccessKeyIdEqualTo(invoiceFileReq.getAccessKeyID());
			List<TkUserUrl> userUrls = tkUserUrlService.selectByExample(userUrlExample);
			
			if(userUrls == null || userUrls.size() == 0){
				functionList.add(getFunction("02","","","",""));
			}else{
				TkUserUrl userUrl = userUrls.get(0);
				String hgResult = callHgGetTaxInfo(invoiceFileReq,userUrl);
				if(StringUtil.isEmpty(hgResult)){
					functionList.add(getFunction("02","","","",""));
				}else{
					JSONObject jsonStr = JSONObject.parseObject(hgResult);
					if(jsonStr != null && !"0".equals(jsonStr.getString("CODE"))){
						functionList.add(getFunction("02","","","",""));
					}else{
						JSONObject dataJson = jsonStr.getJSONObject("DATA");
						if(dataJson != null){						
							functionList.add(getFunction("02",dataJson.getString("userStatus"),dataJson.getString("curCollectFlag")
									,dataJson.getString("lastCollectDate"),dataJson.getString("zone")));
						}else{
							functionList.add(getFunction("02","","","",""));
						}
					}
				}
			}
			
			map.put("functionList", functionList);
			log.info("invoicefile getTaxInfo is end ,"+JSONObject.toJSONString(map));
			return new JsonResult(map);
		}
		
	private Map getFunction(String functionNo,String taxnoStatus,String curOverFlag,String lastOverDate
			,String invDateStart,String invDateEnd,String tokenStatusMsg){
			Map function = new HashMap();
			function.put("functionNo", functionNo);
			function.put("taxnoStatus", taxnoStatus);
			function.put("curOverFlag", curOverFlag);
			function.put("lastOverDate", lastOverDate);
			function.put("invDateStart", invDateStart);
			function.put("invDateEnd", invDateEnd);
			function.put("tokenStatusMsg", tokenStatusMsg);
			return function;
	}
	
	private Map getFunction(String functionNo,String taxnoStatus,String curOverFlag,String lastOverDate){
		Map function = new HashMap();
		function.put("functionNo", functionNo);
		function.put("taxnoStatus", taxnoStatus);
		function.put("curOverFlag", curOverFlag);
		function.put("lastOverDate", lastOverDate);
		return function;
	}


    private Map getFunction(String functionNo,String taxnoStatus,String curOverFlag,String lastOverDate,String zoneCode){
        Map function = getFunction(functionNo, taxnoStatus, curOverFlag, lastOverDate);
        function.put("zoneCode",zoneCode);
        return function;
    }
		
	public String callHgGetTaxInfo(InvoiceFileReq invoiceFileReq,TkUserUrl userUrl){
			 log.info(invoiceFileReq.getTaxno() + "callHgGetTaxInfo is start ...");
             String result = null;
		        try {
		        	String url = userUrl.getRequestUrl()+"/client/getTaxnoInfo.do?";
		            String signStr = "AccessKeyID=%s&SignatureNonce=%s&TaxNo=%s&TimeStamp=%s&Version=1.0";

		            String signatureNonce = UUIDGenerator.generate();
		            String timeStamp = DateUtils.getDataString(DateUtils.yyyymmddthhmmssz);

		            signStr = String.format(signStr,userUrl.getUsername(),signatureNonce, invoiceFileReq.getTaxno(), timeStamp);
		            url += signStr + ("&Signature=" + getSign(signStr));

		    		log.info(invoiceFileReq.getTaxno() + "callHgGetTaxInfo request url:"+url);

		            ResponseContent ret = HttpHelper.getUrlRespContent(url);
		    		log.info(invoiceFileReq.getTaxno() + "callHgGetTaxInfo request result:"+(ret == null?"null":ret.getContent()));
		            if(ret != null){
		            	result =  ret.getContent();
		            }
		        } catch (Exception e) {
		            e.printStackTrace();
                    log.error(invoiceFileReq.getTaxno() + " is error!" + e.getMessage());
		            return null;
		        }
		        
		        log.info(invoiceFileReq.getTaxno() + "callHgGetTaxInfo is end ...");
		        return result;
	}
	
    /**
		* 税号管理
		*
		* @param invoiceFileReq
		* @return
    */
	@Override
	public JsonResult<String> taxManage(InvoiceFileTaxManageReq invoiceFileReq) {
		
		log.info("invoicefile taxManage is start ,"+invoiceFileReq.toString());
		
		List<InvoiceFileTaxManageFunctionReq> functionList = invoiceFileReq.getFunctionList();
		if(functionList == null || functionList.size() == 0){
			  log.info("invoicefile taxManage  functionList is null");
			  return new JsonResult().errorResponse(ResultEnum.param_error);
		}
		
		JsonResult result = new JsonResult();
		List<Map> functionResultList = new ArrayList();
		Map dataResult = new HashMap();
		dataResult.put("taxno", invoiceFileReq.getTaxno());
		
		for(InvoiceFileTaxManageFunctionReq function:functionList){
			   Map functionResult = new HashMap();
			   functionResult.put("functionNo", function.getFunctionNo());
			   functionResult.put("optResult", "0");
			   functionResult.put("optMessage", "操作成功");
			
			   log.info("invoicefile taxManage function,"+function.toString());
			   
			   if(!ObjectUtil.checkData(function.getOptType(),function.getFunctionNo()
					   ,function.getValidType(),function.getBussinessType()
					   ,function.getKeyType())){
			       functionResult.put("optResult", "-1");
			       functionResult.put("optMessage", ResultEnum.param_error);
			       functionResultList.add(functionResult);
			       continue;
			   }
			   
			 //1.校验
				if("01".equals(function.getFunctionNo())&& StringUtil.isEmpty(function.getInitMonth())){
				    functionResult.put("optResult", "-1");
				    functionResult.put("optMessage", "initMonth不能为空");
				    functionResultList.add(functionResult);
				    continue;
				}
				
				if("01".equals(function.getFunctionNo())){
					if(StringUtil.isEmpty(function.getInvSpec())){
					    functionResult.put("optResult", "-1");
					    functionResult.put("optMessage", "invSpec不能为空");
					    functionResultList.add(functionResult);
					    continue;
					}
					
					String initMonth = function.getInitMonth();
					if(!CommonUtil.isInteger(initMonth)){
					    functionResult.put("optResult", "-1");
					    functionResult.put("optMessage", "initMonth必须为数字");
					    functionResultList.add(functionResult);
					    continue;
					}
					int im = Integer.parseInt(initMonth);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.set(Calendar.DATE,1);
                    calendar.set(Calendar.MONTH,1);
                    calendar.set(Calendar.YEAR,2015);
                    int initMonthEnd = DateUtils.monthCompare(new Date(), calendar.getTime());
                    if(im < 0 || im > initMonthEnd){
					    functionResult.put("optResult", "-1");
					    functionResult.put("optMessage", "initMonth从2015-01-01开始，需要在[0-"+initMonth+"]这个区间内");
					    functionResultList.add(functionResult);
					    continue;
					}
				}
				   
				List<String> optList = new ArrayList();
				optList.add("0");optList.add("1");optList.add("2");
				
				if(!optList.contains(function.getOptType())){
				    functionResult.put("optResult", "-1");
				    functionResult.put("optMessage", "optType操作类型不正确");
				    functionResultList.add(functionResult);
				    continue;
				}
				
				String optType = function.getOptType();
				String functionNo = function.getFunctionNo();
				
				if("0".equals(optType)){//
					JSONObject resultJson1 = callWhTaxManager(invoiceFileReq);//调用内部服务1，插入token,文豪
					if(resultJson1 != null && !"0".equals(resultJson1.getString("errorCode"))){
						if(!"12005".equals(resultJson1.getString("errorCode"))){//12005已注册过
							functionResult.put("optResult", "-1");
							functionResult.put("optMessage", resultJson1.getString("message"));
							functionResultList.add(functionResult);
							continue;
						}
					}
				}
				
				if("01".equals(functionNo)){//发票下载
										
					TkTaxUserExample userExample = new TkTaxUserExample();
					userExample.createCriteria().andTaxnoEqualTo(invoiceFileReq.getTaxno())
					.andUserNameEqualTo(invoiceFileReq.getAccessKeyID());
					List<TkTaxUser> taxUsers = tkTaxUserService.selectByExample(userExample);

					if("0".equals(optType)){//增加
						if(taxUsers != null && taxUsers.size() > 0){
							 functionResult.put("optResult", "-1");
							 functionResult.put("optMessage", "此税号已注册");
							 functionResultList.add(functionResult);
							 continue;
						}
                        String checkFlag = "2";
                        if(invoiceFileReq.getAccessKeyID().equals("bwgf-limit")) {
                            checkFlag = checkTaxno(invoiceFileReq.getAccessKeyID(), invoiceFileReq.getTaxno());
                            if(checkFlag.equals("2")) {
                                functionResult.put("optResult", "-1");
                                functionResult.put("optMessage", "检测审核信息失败");
                                functionResultList.add(functionResult);
                                continue;
                            }
                        }

						if(taxUsers == null || taxUsers.size() == 0){
							TkTaxUserExample userExample2 = new TkTaxUserExample();
							userExample2.createCriteria().andTaxnoEqualTo(invoiceFileReq.getTaxno());
							List<TkTaxUser> taxUsers2 = tkTaxUserService.selectByExample(userExample2);
							
							TkTaxUser record = new TkTaxUser();
							record.setTaxno(invoiceFileReq.getTaxno());
							record.setUserName(invoiceFileReq.getAccessKeyID());
							if(invoiceFileReq.getAccessKeyID().equals("bwgf-limit") && checkFlag.equals("0")) {
                                record.setDelFlag("9");
								record.setUserStatus("1");
                            } else {
                                record.setDelFlag(getDelFlag(optType));
                                if("2".equals(optType)) {
                                    record.setUserStatus("5");
                                } else {
                                    record.setUserStatus("3");
                                }
                            }
							record.setZoneCode(invoiceFileReq.getZoneCode());
							record.setCreateDate(new Date());
							record.setInvSpec(function.getInvSpec());
							record.setIsRepeat((taxUsers2 != null && taxUsers2.size() > 0)?"1":"0");
							record.setIsOnce(function.getValidType());
							record.setInitMonth(Integer.parseInt(function.getInitMonth()));
							record.setKeyType(function.getKeyType());
							tkTaxUserService.insertSelective(record);
							
							
							FileUserExample fileUserExample = new FileUserExample();
							fileUserExample.createCriteria().andUserNameEqualTo(invoiceFileReq.getAccessKeyID());
							List<FileUser> fileUsers = fileUserService.selectByExample(fileUserExample);
							
							if(fileUsers == null || fileUsers.size() == 0){
								FileUser fileUser = new FileUser();
								fileUser.setUserName(invoiceFileReq.getAccessKeyID());
								fileUser.setTkServer(CommonUtil.getServerNo());
								fileUser.setValidType(function.getValidType());
								fileUser.setBussinessType(function.getBussinessType());
								fileUser.setKeyType(function.getKeyType());
								
								fileUserService.insertSelective(fileUser);
							}

							//优化重复税号
							if(taxUsers2 != null && taxUsers2.size() > 0){
								dataRepeatApplyService.init(record, taxUsers2.get(0));
							}
						}
					}else if("1".equals(optType) || "2".equals(optType)){//开启或停用
						if(taxUsers == null || taxUsers.size() == 0){
							 functionResult.put("optResult", "-1");
							 functionResult.put("optMessage", "此税号未注册");
							 functionResultList.add(functionResult);
							 continue;
						}
						
						if(taxUsers != null && taxUsers.size() > 0){
							TkTaxUser record = taxUsers.get(0);
                            if(invoiceFileReq.getAccessKeyID().equals("bwgf-limit") && (record.getDelFlag().equals("9") || record.getUserStatus().equals("1"))) {
                                //不允许修改
                            } else {
                                record.setDelFlag(getDelFlag(optType));
                                if("2".equals(optType)) {
                                    record.setUserStatus("5");
                                } else {
                                    record.setUserStatus("3");
                                }
                            }
							if(StringUtils.isNotBlank(invoiceFileReq.getZoneCode())){
                                record.setZoneCode(invoiceFileReq.getZoneCode());
                            }
							tkTaxUserService.updateByPrimaryKey(record);
						}
					}
				}else if("02".equals(functionNo)){
					TkUserUrlExample userUrlExample = new TkUserUrlExample();
					userUrlExample.createCriteria().andAccessKeyIdEqualTo(invoiceFileReq.getAccessKeyID());
					List<TkUserUrl> userUrls = tkUserUrlService.selectByExample(userUrlExample);
					
					if(userUrls == null || userUrls.size() == 0){
						functionResult.put("optResult", "-1");
						functionResult.put("optMessage", "userUrl is not config");
						functionResultList.add(functionResult);
					    continue;
					}
					
					JSONObject resultJson2 = callHgManage(invoiceFileReq,function,userUrls.get(0));//调用内部服务，红哥
					if(resultJson2 != null && !"0".equals(resultJson2.getString("CODE"))){
						functionResult.put("optResult", "-1");
						functionResult.put("optMessage", resultJson2.getString("MESSAGE"));
						functionResultList.add(functionResult);
					    continue;
					}

                    JSONObject resultJson1 = callWhTaxManager(invoiceFileReq);//调用内部服务1，插入token,文豪
                    if(resultJson1 != null && !"0".equals(resultJson1.getString("errorCode"))){
                        if(!"12005".equals(resultJson1.getString("errorCode"))){//12005已注册过
                            functionResult.put("optResult", "-1");
                            functionResult.put("optMessage", resultJson1.getString("message"));
                            functionResultList.add(functionResult);
                            continue;
                        }
                    }
				}else{
					functionResult.put("optResult", "-1");
					functionResult.put("optMessage", "functionNo不正确");
					functionResultList.add(functionResult);
				    continue;
				}
				
				functionResultList.add(functionResult);
		}
		
		dataResult.put("functionList", functionResultList);
		result.setData(dataResult);
		log.info("invoicefile taxManage is end ,"+result);
		return result;
	}

	public String checkTaxno(String accessKeyID, String taxno) {
        String checkFlag = "2";
        try {
            InvoiceFileReq invoiceFileRe = new InvoiceFileReq();
            invoiceFileRe.setAccessKeyID(accessKeyID);
            invoiceFileRe.setTaxno(taxno);

            TkUserUrlExample userUrlExample = new TkUserUrlExample();
            userUrlExample.createCriteria().andAccessKeyIdEqualTo(accessKeyID);
            List<TkUserUrl> userUrls = tkUserUrlService.selectByExample(userUrlExample);
            if(userUrls != null && userUrls.size() > 0){
                TkUserUrl userUrl = userUrls.get(0);
                String hgResult = callHgGetTaxInfo(invoiceFileRe,userUrl);
                if(StringUtil.isNotEmpty(hgResult)){
                    JSONObject jsonStr = JSONObject.parseObject(hgResult);
                    if (jsonStr != null) {
                        if("0".equals(jsonStr.getString("CODE"))) {
                            JSONObject dataJson = jsonStr.getJSONObject("DATA");
                            if(dataJson != null && !"1".equals(dataJson.getString("userStatus"))) {
                                checkFlag = "1";
                            } else {
                                checkFlag = "0";
                            }
                        } else {
                            checkFlag = "0";
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
			log.error("checkTaxno accessKeyID:"+accessKeyID + ",taxno:" + taxno + " is error!" + e.getMessage());
        }
		return checkFlag;
	}
	
	public String getDelFlag(String optType){
		String delFlag = null;
		if("0".equals(optType) || "1".equals(optType)){
			delFlag = "0";
		}else if("2".equals(optType)){
			delFlag = "1";
		}
		return delFlag;
	}
	
	public JSONObject callHgManage(InvoiceFileTaxManageReq invoiceFileReq,InvoiceFileTaxManageFunctionReq function
			,TkUserUrl userUrl){
		log.info("callHgManage is start ...");
		String requestUrl = userUrl.getRequestUrl()+"/client/optTaxnoInfo.do?";
	    String signStr = "AccessKeyID=%s&SignatureNonce=%s&TaxNo=%s&TimeStamp=%s&Version=1.0";
		String signatureNonce = UUIDGenerator.generate();
	    String timeStamp = DateUtils.getDataString(DateUtils.yyyymmddthhmmssz);
	    signStr = String.format(signStr,userUrl.getUsername(),signatureNonce,invoiceFileReq.getTaxno(), timeStamp);
	    requestUrl += signStr + ("&Signature=" + getSign(signStr));
		
		JSONObject json = new JSONObject();
		json.put("taxno", invoiceFileReq.getTaxno());
		json.put("zoneCode", invoiceFileReq.getZoneCode());
		json.put("optType", function.getOptType());
		json.put("validType", function.getValidType());
		json.put("bussinessType", function.getBussinessType());
		json.put("keyType", function.getKeyType());
		
		log.info("callHgManage request url:"+requestUrl+",param:"+json.toJSONString());
		
		HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<JSONObject> entity = new HttpEntity<>(json,headers);
        JSONObject resultJson = restTemplate.postForObject(requestUrl, entity, JSONObject.class);
		log.info("callHgManage request result:"+(resultJson == null?"null":resultJson.toJSONString()));
		return resultJson;
	}
	
	public JSONObject callHg(InvoiceFileReq invoiceFileReq){
		String requestUrl = FileConstants.taxInitHUrl+"?";
	    String signStr = "AccessKeyID=%s&SignatureNonce=%s&TaxNo=%s&TimeStamp=%s&Version=1.0";
		String signatureNonce = UUIDGenerator.generate();
	    String timeStamp = DateUtils.getDataString(DateUtils.yyyymmddthhmmssz);
	    signStr = String.format(signStr,invoiceFileReq.getAccessKeyID(),signatureNonce,invoiceFileReq.getTaxno(), timeStamp);
	    requestUrl += signStr + ("&Signature=" + getSign(signStr));	
		
		JSONObject json = new JSONObject();
		json.put("taxno", invoiceFileReq.getTaxno());
		json.put("zoneCode", invoiceFileReq.getZoneCode());
		json.put("optType", invoiceFileReq.getOptType());
		
		log.info("callHg request url:"+requestUrl+",param:"+json.toJSONString());
		
		HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<JSONObject> entity = new HttpEntity<>(json,headers);
        JSONObject resultJson = restTemplate.postForObject(requestUrl, entity, JSONObject.class);
		log.info("callHg request result:"+(resultJson == null?"null":resultJson.toJSONString()));
		return resultJson;
	}
	
	public JSONObject callWhTaxManager(InvoiceFileTaxManageReq invoiceFileReq){
		JSONObject json = new JSONObject();
		json.put("taxno", invoiceFileReq.getTaxno());
		json.put("zoneCode", invoiceFileReq.getZoneCode());
		//json.put("userCode", server.getUsername());
		json.put("userCode", invoiceFileReq.getAccessKeyID());
		json.put("serverNo", CommonUtil.getServerNo());
		json.put("secert", invoiceFileReq.getSecert());
		
		log.info("callWhTaxManager request url:"+FileConstants.taxInitUrl+",param:"+json.toJSONString());
		
		HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
		HttpEntity<Object> entity = new HttpEntity<Object>(json, headers);
		JSONObject resultJson = restTemplate.postForObject(FileConstants.taxInitUrl, entity, JSONObject.class);
		log.info("callWhTaxManager request result:"+(resultJson == null?"null":resultJson.toJSONString()));
		return resultJson;
	}
	
	public JSONObject callWh(InvoiceFileReq invoiceFileReq,FileServer server){
		JSONObject json = new JSONObject();
		json.put("taxno", invoiceFileReq.getTaxno());
		json.put("zoneCode", invoiceFileReq.getZoneCode());
		json.put("userCode", server.getUsername());
		json.put("serverNo", FileConstants.getTaxInitServerNo());
		
		log.info("callWh request url:"+FileConstants.taxInitUrl+",param:"+json.toJSONString());
		
		HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
		HttpEntity<Object> entity = new HttpEntity<Object>(json, headers);
		JSONObject resultJson = restTemplate.postForObject(FileConstants.taxInitUrl, entity, JSONObject.class);
		log.info("callWh request result:"+(resultJson == null?"null":resultJson.toJSONString()));
		return resultJson;
	}
	
    public static String getSign(String data){
        try {
        	return "test";//内部调用，不延签
            //return Security.getSignature(data.getBytes("UTF-8"),accessKeySecret.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String transUserStatus(String delFlag) {
        String userStatus = "5";
        if("0".equals(delFlag)) {
            userStatus = "3";
        } else if("9".equals(delFlag)) {
            userStatus = "1";
        }
        return userStatus;
    }

}
