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.InvoiceFileReq;
import com.tax.file.model.InvoiceFileTaxManageReq;
import com.tax.file.service.api.InvoiceFileService;
import com.yxcheng.tax.fs.minio.service.MinioTemplate;
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.JsonResult;
import com.yxcheng.token.utils.ObjectUtil;
import com.yxcheng.token.utils.StringUtil;
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.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;
    

    /**
	 * 发票文件下载
	 *
	 * @param invoiceFileReq
	 * @return
	 */
    @RequestMapping(value ="/download" , method = RequestMethod.POST)
    public JsonResult<Map> download(@RequestBody InvoiceFileReq invoiceFileReq){
    	try {
			//1.校验
			CrRpcResult crRpcResult = userClient.isSafe(invoiceFileReq);
			if(!checkUserSafe(crRpcResult)){
			    return JsonResult.errorResult(crRpcResult.getCode(),crRpcResult.getMessage());
			}

			//2.获取数据
			return  invoiceFileService.download(invoiceFileReq);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("系统异常:"+e);
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
    }
    
    /**
   	 * 发票文件下载反馈
   	 *
   	 * @param invoiceFileReq
   	 * @return
   	 */
       @RequestMapping(value ="/downloadRes" , method = RequestMethod.POST)
       public JsonResult<Map> downloadRes(@RequestBody InvoiceFileReq invoiceFileReq){
           try {
			//1.校验
			   if(!ObjectUtil.checkData(invoiceFileReq.getTaskno())){
			       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.downloadRes(invoiceFileReq);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("系统异常:"+e);
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
       }
       /**
      	 * 获取税号信息
      	 *
      	 * @param invoiceFileReq
      	 * @return
      	 */
     @RedisLimit(count = 10,unitTime = 60)
     @RequestMapping(value ="/taxInfo" , method = RequestMethod.POST)
     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)
   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}")
   	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)
	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("系统异常:"+e);
			return new JsonResult().errorResponse(ResultEnum.system_error);
		}
	}
	
	    /**
	   	 * 税号管理接口
	   	 *
	   	 * @param invoiceFileReq
	   	 * @return
	   	 */
	  @RequestMapping(value ="/taxManage" , method = RequestMethod.POST)
	  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("系统异常:"+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);
        }
    }

}
