package com.tax.file.web.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.tax.file.constants.CommonConstants;
import com.tax.file.integration.user.UserClient;
import com.tax.file.model.*;
import com.tax.file.model.fileManage.QueryFileReqModel;
import com.tax.file.service.api.InvoiceFileService;
import com.tax.file.service.api.TkUserUrlService;
import com.tax.file.service.util.UserUtils;
import com.tax.file.utils.ExpCacheUtils;
import com.yxcheng.tax.fs.minio.service.MinioTemplate;
import com.yxcheng.token.common.annotation.LogT;
import com.yxcheng.token.common.annotation.RedisLimit;
import com.yxcheng.token.common.controller.BaseClientController;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.model.CrRpcResult;
import com.yxcheng.token.common.model.InvoiceFileTaxBatchManageReq;
import com.yxcheng.token.common.model.JsonResult;
import com.yxcheng.token.utils.ObjectUtil;
import com.yxcheng.token.utils.StringUtil;
import com.yxcheng.token.utils.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 发票文件下载
 */
@RestController
@RequestMapping("/invoicefile")
@ComponentScan(basePackages = {"com.tax.token.service"})
@Slf4j
public class InvoiceFileController extends BaseClientController {

    @Autowired
    private InvoiceFileService invoiceFileService;
    @Autowired
    private UserClient userClient;
    @Autowired
	private MinioTemplate minioTemplate;
	@Autowired
	private TkUserUrlService tkUserUrlService;

	/**
	 * 发票文件下载
	 *
	 * @param invoiceFileReq
	 * @return
	 */
	@RequestMapping(value ="/download" , method = RequestMethod.POST)
	public JsonResult<Map> download(@RequestBody InvoiceFileReq invoiceFileReq){
        String timeFlag = UUIDGenerator.generate();
        JsonResult jsonResult = new JsonResult();
		try {
			//1.校验
			CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
			if(!checkUserSafe(crRpcResult)){
                jsonResult.error(crRpcResult.getCode(),crRpcResult.getMessage());
			} else {
                if(ExpCacheUtils.getDownloadTaskCountByTaxno(invoiceFileReq.getAccessKeyID()) < 5) {
                    jsonResult = invoiceFileService.download(timeFlag, invoiceFileReq);
                } else {
                    jsonResult.errorResponse(ResultEnum.file_down_repeat_error);
                }
            }
		} catch (Exception e) {
            log.error(timeFlag + " 系统异常:" + e.getMessage());
            jsonResult.errorResponse(ResultEnum.system_error);
		}
		return jsonResult;
	}

	/**
	 * 发票文件下载反馈
	 *
	 * @param invoiceFileReq
	 * @return
	 */
	@RequestMapping(value ="/downloadRes" , method = RequestMethod.POST)
	public JsonResult<Map> downloadRes(@RequestBody InvoiceFileReq invoiceFileReq){
        String timeFlag = UUIDGenerator.generate();
        JsonResult jsonResult = new JsonResult();
		try {
			//1.校验
			if(!ObjectUtil.checkData(invoiceFileReq.getTaskno())){
                jsonResult.errorResponse(ResultEnum.param_error);
			}
			CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
			if(!checkUserSafe(crRpcResult)){
                jsonResult.error(crRpcResult.getCode(),crRpcResult.getMessage());
			}
			//2.更新数据
            jsonResult =  invoiceFileService.downloadRes(timeFlag, invoiceFileReq);
		} catch (Exception e) {
            e.printStackTrace();
            log.error(timeFlag + " 系统异常:" + e.getMessage());
            jsonResult.errorResponse(ResultEnum.system_error);
        }
        return jsonResult;
	}
    

    /**
	 * 根据税号下载发票文件
	 *
	 * @param invoiceFileReq
	 * @return
	 */
    @RequestMapping(value ="/downloadList" , method = RequestMethod.POST)
    @LogT(LogT.LOG_VIEW_PART)
    public JsonResult<Map> downloadList(@RequestBody InvoiceFileReq invoiceFileReq){
        String timeFlag = UUIDGenerator.generate();
		JsonResult jsonResult = new JsonResult();
    	try {
			//1.校验
			CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
			if(!checkUserSafe(crRpcResult)){
                jsonResult.error(crRpcResult.getCode(),crRpcResult.getMessage());
			} else {
                TkTaxUser taxUser = UserUtils.getTaxUserBytaxno(invoiceFileReq.getAccessKeyID(), invoiceFileReq.getTaxno());
                if(null != taxUser) {
                	if(taxUser.getUserStatus().equals(TkTaxUser.TAX_STATUS_NORMAL)) {
						if(ExpCacheUtils.getDownloadListTaskCountByTaxno(invoiceFileReq.getAccessKeyID(), invoiceFileReq.getTaxno()) < 5) {
							jsonResult = invoiceFileService.downloadList(timeFlag, invoiceFileReq);
						} else {
							jsonResult.errorResponse(ResultEnum.file_down_repeat_error);
						}
					} else {
						jsonResult.errorResponse(ResultEnum.taxno_status_error);
					}
                } else {
                    jsonResult.errorResponse(ResultEnum.user_taxno_not_exist);
                }

            }
		} catch (Exception e) {
			e.printStackTrace();
			log.error(timeFlag + " 系统异常:" + e.getMessage());
			jsonResult.errorResponse(ResultEnum.system_error);
		}
		return jsonResult;
    }
    
    /**
   	 * 根据税号下载发票文件反馈
   	 *
   	 * @param invoiceFileReq
   	 * @return
   	 */
       @RequestMapping(value ="/downloadListRes" , method = RequestMethod.POST)
       @LogT(LogT.LOG_VIEW_PART)
       public JsonResult<Map> downloadListRes(@RequestBody InvoiceFileReq invoiceFileReq){
           String timeFlag = UUIDGenerator.generate();
           JsonResult jsonResult = new JsonResult();
           try {
			//1.校验
			   if(!ObjectUtil.checkData(invoiceFileReq.getTaskno())){
                   jsonResult.errorResponse(ResultEnum.param_error);
			   } else {
                   CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
                   if(!checkUserSafe(crRpcResult)){
                       jsonResult.error(crRpcResult.getCode(),crRpcResult.getMessage());
                   } else {
                       TkTaxUser taxUser = UserUtils.getTaxUserBytaxno(invoiceFileReq.getAccessKeyID(), invoiceFileReq.getTaxno());
                       if(null != taxUser) {
						   if(taxUser.getUserStatus().equals(TkTaxUser.TAX_STATUS_NORMAL)) {
							   jsonResult = invoiceFileService.downloadListRes(timeFlag, invoiceFileReq);
						   } else {
							   jsonResult.errorResponse(ResultEnum.taxno_status_error);
						   }
                       } else {
                           jsonResult.errorResponse(ResultEnum.user_taxno_not_exist);
                       }
                   }
               }
            } catch (Exception e) {
               e.printStackTrace();
               log.error(timeFlag + " 系统异常:" + e.getMessage());
               jsonResult.errorResponse(ResultEnum.system_error);
            }
            return jsonResult;
       }
       /**
      	 * 获取税号信息
      	 *
      	 * @param invoiceFileReq
      	 * @return
      	 */
     @RedisLimit(count = 10,unitTime = 60)
     @RequestMapping(value ="/taxInfo" , method = RequestMethod.POST)
     @LogT(LogT.LOG_VIEW_PART)
     public JsonResult<Map> taxInfo(@RequestBody InvoiceFileReq invoiceFileReq){
        try {
   			   //1.校验
   			   if(!ObjectUtil.checkData(invoiceFileReq.getTaxno())){
   			       return new JsonResult().errorResponse(ResultEnum.param_error);
   			   }
   			   CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
   			   if(!checkUserSafe(crRpcResult)){
   			       return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
   			   }
           	   
   			   //2.查询数据
   			   return  invoiceFileService.taxInfo(invoiceFileReq);
   		} catch (Exception e) {
   			e.printStackTrace();
   			log.error("系统异常:"+e);
   			return new JsonResult().errorResponse(ResultEnum.system_error);
   		}
     }  
     
     /**
    	 * 税号初始化接口
    	 *
    	 * @param invoiceFileReq
    	 * @return
    	 */
   @RequestMapping(value ="/taxInit" , method = RequestMethod.POST)
   @LogT(LogT.LOG_VIEW_PART)
   public JsonResult<String> taxInit(@RequestBody InvoiceFileReq invoiceFileReq){
      try {
    	       //调用方未对接新功能，暂时不校验操作类型
    	       if(StringUtil.isEmpty(invoiceFileReq.getOptType())){
    	    	   invoiceFileReq.setOptType("0");
    	       }
    	       
 			   //1.校验
 			   if(!ObjectUtil.checkData(invoiceFileReq.getTaxno(),invoiceFileReq.getZoneCode())){
 			       return new JsonResult().errorResponse(ResultEnum.param_error);
 			   }
 			   CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
 			   if(!checkUserSafe(crRpcResult)){
 			       return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
 			   }
         	   
 			   //2.查询数据
 			   return  invoiceFileService.taxInit(invoiceFileReq);
 		} catch (Exception e) {
 			e.printStackTrace();
 			log.error("系统异常:"+e);
 			return new JsonResult().errorResponse(ResultEnum.system_error);
 		}
   } 
       
       
    /**
   	 * 发票下载获取文件
   	 *
   	 * @param fileName 文件空间/名称
   	 * @param response
   	 * @return
   	 */
   	@GetMapping("/file/{fileName}")
    @LogT(LogT.LOG_VIEW_PART)
   	public void file(@PathVariable String fileName, HttpServletResponse response) {
   		String[] nameArray = StrUtil.split(fileName, StrUtil.DASHED);
   		String key = nameArray[1]+StrUtil.DOT+CommonConstants.EXT_NAME;
   		try (InputStream inputStream = minioTemplate.getObject(nameArray[0], key)) {
   			response.setContentType("application/octet-stream; charset=UTF-8");
   			response.setHeader("Content-Disposition", "attachment;fileName="+key);   
   			IoUtil.copy(inputStream, response.getOutputStream());
   		} catch (Exception e) {
   			log.error("文件读取异常", e);
   		}
   		
   	}
   	
    /**
	 * 获取发票下载的税号信息
	 *
	 * @param invoiceFileReq
	 * @return
	 */
	@RequestMapping(value ="/getTaxInfo" , method = RequestMethod.POST)
    @LogT(LogT.LOG_VIEW_PART)
	public JsonResult<String> getTaxInfo(@RequestBody InvoiceFileReq invoiceFileReq){
	  try {
		   //1.校验
		   if(!ObjectUtil.checkData(invoiceFileReq.getTaxno())){
			   return new JsonResult().errorResponse(ResultEnum.param_error);
		   }
		   CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
		   if(!checkUserSafe(crRpcResult)){
			   return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
		   }

		   //2.查询数据
		   return  invoiceFileService.getTaxInfo(invoiceFileReq);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("getTaxInfo系统异常:", e);
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
	}
	
	    /**
	   	 * 税号管理接口
	   	 *
	   	 * @param invoiceFileReq
	   	 * @return
	   	 */
	  @RequestMapping(value ="/taxManage" , method = RequestMethod.POST)
      @LogT(LogT.LOG_VIEW_PART)
	  public JsonResult<String> taxManage(@RequestBody InvoiceFileTaxManageReq invoiceFileReq){
	     try {
               //1.校验
               if(!ObjectUtil.checkData(invoiceFileReq.getTaxno(),invoiceFileReq.getZoneCode())){
                   return new JsonResult().errorResponse(ResultEnum.param_error);
               }

               CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
               if(!checkUserSafe(crRpcResult)){
                  return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
               }

               //2.查询数据
               return  invoiceFileService.taxManage(invoiceFileReq);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("taxManage系统异常:", e);
				return new JsonResult().errorResponse(ResultEnum.system_error);
			}
	  } 
   	
   	/**
   	 * 获取文件URL
   	 *
   	 * @param fileName 文件空间/名称
   	 * @param response
   	 * @return
   	 */
   	@GetMapping("/url/{fileName}")
   	public JsonResult<String> url(@PathVariable String fileName, HttpServletResponse response) {
   		String[] nameArray = StrUtil.split(fileName, StrUtil.DASHED);//7 * 24 * 3600
   		String url = minioTemplate.getObjectURL(nameArray[0], nameArray[1]+StrUtil.DOT+CommonConstants.EXT_NAME, CommonConstants.EXPIRES);
   		return new JsonResult<String>(url);
   	}


    @RequestMapping(value ="/turnOn" , method = RequestMethod.POST)
    public JsonResult<String> turnOn(@RequestBody InvoiceFileTaxManageReq invoiceFileReq){
        try {
            //1.校验
            if(!ObjectUtil.checkData(invoiceFileReq.getTaxno())){
                return new JsonResult().errorResponse(ResultEnum.param_error);
            }

            CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
           if(!checkUserSafe(crRpcResult)){
              return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
           }

            //2.查询数据
            return  invoiceFileService.taxManage(invoiceFileReq);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("系统异常:"+e);
            return new JsonResult().errorResponse(ResultEnum.system_error);
        }
    }

	@RequestMapping(value ="/queryErrorFileList" , method = RequestMethod.POST)
	public JsonResult<List<InvoiceApplyRes>> queryErrorFileList(@RequestBody QueryFileReqModel queryFileReqModel){
		String timeFlag = UUIDGenerator.generate();
		JsonResult jsonResult = new JsonResult();
		try {
			//1.校验
			CrRpcResult crRpcResult = userClient.isSafe(queryFileReqModel);
			if(!checkUserSafe(crRpcResult)){
				jsonResult.error(crRpcResult.getCode(),crRpcResult.getMessage());
			} else {
				TkTaxUser taxUser = UserUtils.getTaxUserBytaxno(queryFileReqModel.getAccessKeyID(), queryFileReqModel.getTaxno());
				if(null != taxUser && taxUser.getUserStatus().equals(TkTaxUser.TAX_STATUS_NORMAL)) {
					jsonResult = invoiceFileService.queryErrorFileList(timeFlag, taxUser, queryFileReqModel);
				} else {
					if(null == taxUser ) {
						jsonResult.errorResponse(ResultEnum.user_taxno_not_exist);
					} else {
						jsonResult.errorResponse(ResultEnum.user_taxno_temp_stop);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(timeFlag + " 系统异常:" + e.getMessage());
			jsonResult.errorResponse(ResultEnum.system_error);
		}
		return jsonResult;
	}

	@RequestMapping(value ="/flushExpCacheByTaxno" , method = RequestMethod.POST)
    @LogT(LogT.LOG_VIEW_PART)
	public JsonResult<String> flushExpCacheByTaxno(@RequestBody InvoiceFileReq invoiceFileReq){
		try {
            String uuidFlag = UUIDGenerator.generate();
			return  invoiceFileService.flushExpCacheByTaxno(uuidFlag, invoiceFileReq);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("系统异常:"+e);
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
	}

	@RequestMapping(value ="/flushUserUrlCacheByUserName" , method = RequestMethod.POST)
	@LogT(LogT.LOG_VIEW_PART)
	public JsonResult<String> flushUserUrlCacheByUserName(@RequestBody InvoiceFileReq invoiceFileReq){
		try {
            JsonResult jsonResult = new JsonResult();
            jsonResult.setData(tkUserUrlService.flushUserUrlCache(invoiceFileReq.getAccessKeyID()));
			return  jsonResult;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("系统异常:"+e);
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
	}

	@RequestMapping(value ="/flushUserUrlCache" , method = RequestMethod.POST)
	@LogT(LogT.LOG_VIEW_PART)
	public JsonResult<String> flushUserUrlCache(@RequestBody InvoiceFileReq invoiceFileReq){
		try {
			JsonResult jsonResult = new JsonResult();
            List<String> userList = userClient.queryUserList();
            String result = "";
            for(String userName:userList) {
                int flushNum = tkUserUrlService.flushUserUrlCache(userName);
                result += userName + "=" + flushNum + ";";
            }
			jsonResult.setData(result);
			return  jsonResult;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("系统异常:"+e);
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
	}

	/**
	 * 税号批量管理接口
	 *
	 * @param invoiceFileTaxBatchManageReq
	 * @return
	 */
	@RequestMapping(value ="/batchTaxManage" , method = RequestMethod.POST)
	@LogT(LogT.LOG_VIEW_PART)
	public JsonResult<String> batchTaxManage(@RequestBody InvoiceFileTaxBatchManageReq invoiceFileTaxBatchManageReq){
		try {
			return  invoiceFileService.batchTaxManage(invoiceFileTaxBatchManageReq);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("batchTaxManage系统异常:", e.getMessage());
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
	}
}
