package com.dhcc.finance.main.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.dhcc.common.RestStatus;
import com.dhcc.common.Shift;
import com.dhcc.common.constant.TaStatusCode;
import com.dhcc.finance.main.model.FileUploadRequest;
import com.dhcc.finance.util.FinanceExcelUtil;
import com.dhcc.finance.main.model.ChroAccountExportParam;
import com.dhcc.finance.main.model.CwChroAccountInfo;
import com.dhcc.finance.main.model.CwGlReportInfo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import brave.Tracer;
import com.dhcc.common.constant.FinanceStatusCode;
import com.dhcc.common.constant.SysConstants;
import com.dhcc.common.constant.SysStatusCode;
import com.dhcc.common.model.CurrencyMeta;
import com.dhcc.common.model.SysUserInfo;
import com.dhcc.common.model.response.RestfulResponse;
import com.dhcc.common.util.CacheDataUtil;
import com.dhcc.common.util.ExcelUtils;
import com.dhcc.finance.constant.FinanceDictConsts;
import com.dhcc.finance.main.dao.CwBdReportlockMapper;
import com.dhcc.finance.main.dao.CwGlWeightedDetailMapper;
import com.dhcc.finance.main.dao.CwGlWeightedMapper;
import com.dhcc.finance.main.dao.FinancialStatementsMapper;
import com.dhcc.finance.main.domain.CwBdReportlock;
import com.dhcc.finance.main.service.FinancialStatementsService;
import com.dhcc.finance.util.FinanceDateUtil;
import com.dhcc.finance.util.MetaDataUtil;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.dhcc.finance.main.dao.CwBdProductcellDetailMapper;

/**
 * 功能描述：财务报表
 * @author dml
 * @date 2019年7月28日 下午3:34:27
 * @修改日志：
 */
@Slf4j
@Service
public class FinancialStatementsServiceImple implements FinancialStatementsService{
	@Autowired
	private Tracer tracer;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	FinancialStatementsMapper financialStatementsMapper;// 报表相关Mapper
	
	@Autowired
	CwGlWeightedDetailMapper cwGlWeightedDetailMapper;// 项目加权规模明细表
	
	@Autowired
	CwGlWeightedMapper cwGlWeightedMapper;// 项目加权规模表

	@Autowired
	public FastFileStorageClient fastFileStorageClient;
	
	@Autowired
    CwBdReportlockMapper cwBdReportlockMapper;
	
	@Autowired
	CwBdProductcellDetailMapper cwBdProductcellDetailMapper;

//	@Value("${template.path}")
//	private String templateExcelPath;

	@Value("${fdfsUrl.pre}")
	private String preUrl;

	private static final String MSG = "其他报表生成中，请稍后查询";
	/*
	 * (非 Javadoc)  
	 * Title: insertInitBalanceSheet 
	 * Description:初始化报表数据
	 * @param reportDate
	 * @param searchType
	 * @param param
	 * @param reportType
	 * @return  
	 * @see com.dhcc.finance.main.service.FinancialStatementsService#insertInitBalanceSheet(java.lang.String, java.lang.String, java.lang.String, java.lang.String)    
	 * @author dml
	 * @date 2019年11月14日 上午9:29:29
	 * @修改日志：
	 */
	@Override
	public RestfulResponse<Object, CurrencyMeta> insertInitBalanceSheet(String reportDate, String searchType,String param,
			String reportType) {
		//boolean flag =false;
		try {
		    String lockPeriodMax = null;
		    String lockPeroid = reportDate.substring(0, 4)+"-"+reportDate.substring(4, 6);
		    CwBdReportlock cwBdReportlocks= cwBdReportlockMapper.selectMaxLockPeroid();
	        if(cwBdReportlocks != null ) {
	             lockPeriodMax = cwBdReportlocks.getLockPeriodMax();
	        }
	        if (lockPeroid.compareTo(lockPeriodMax) <= 0) {
	            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.PERIOD_LOCKED.message()
	                    ,MetaDataUtil.getMeta(tracer,FinanceStatusCode.PERIOD_LOCKED));
	        }
			//long startTime=System.currentTimeMillis();
			// 资产负债表
			//Long selectCountTemp = financialStatementsMapper.selectCountTemp();
			if (selectCountTemp>0) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysConstants.DEFAULT_MESSAGE.OPERATION_FAIL,
						MSG,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
			}
			cwBdProductcellDetailMapper.updateProductcellDetail();
			// 日期所在会计期间
			String period = FinanceDateUtil.getPeriodByDatestr(reportDate, "yyyyMMdd");
			if (FinanceDictConsts.REPORT_TYPE.ZCFZB.equals(reportType)) {
				// 账套查询
				if (FinanceDictConsts.SEARCH_TYPE.ZTCX.equals(searchType)) {
					// 查询账套是否需要重新生成
//					List<String> selectIsInit = financialStatementsMapper.selectIsInitZt(reportDate, param, reportType, period,searchType);
//					if (selectIsInit.size()>0) {
						flag = true;
						// 重新生成临时表
						int insertBalanceTempZcfzbZt = financialStatementsMapper.insertBalanceTempZcfzbZt(reportDate, param);
						if (insertBalanceTempZcfzbZt>0) {
							// 删除之前的报表数据
							financialStatementsMapper.deleteCwGlReport(reportDate, reportType);
							//  重跑报表数据
							financialStatementsMapper.insertBalanceSheet(reportDate);
						}
					//}
				}
				
				// 项目查询 产品单元查询
				if (FinanceDictConsts.SEARCH_TYPE.XMCX.equals(searchType)  || FinanceDictConsts.SEARCH_TYPE.CPDYCX.equals(searchType)) {
					// 查询项目是否需要重跑
//					List<String> selectIsInitXtxm = financialStatementsMapper.selectIsInitXtxm(reportDate, param, reportType, period,searchType);
//					if (selectIsInitXtxm.size()>0) {
						flag = true;
						int insertBalanceTempZcfzbXtxm = financialStatementsMapper.insertBalanceTempZcfzbXtxm(reportDate);
						if (insertBalanceTempZcfzbXtxm>0) {
							financialStatementsMapper.deleteCwGlReport(reportDate, reportType);
							financialStatementsMapper.insertBalanceSheet(reportDate);
						}
//					}
				}
			}
			//利润表
			if (FinanceDictConsts.REPORT_TYPE.LRB.equals(reportType)) {
				// 查询账套是否需要重新生成
//				List<String> selectIsInit = financialStatementsMapper.selectIsInitZt(reportDate, param, reportType, period,searchType);
//				if (selectIsInit.size()>0) {
					flag = true;
					// 重新生成临时表
					int insertBalanceTempZcfzbZt = financialStatementsMapper.insertBalanceTempLrbZt(reportDate);
					if (insertBalanceTempZcfzbZt>0) {
						// 删除之前的报表数据
						financialStatementsMapper.deleteCwGlReport(reportDate, reportType);
						//  重跑报表数据
						financialStatementsMapper.insertProfitStatement(reportDate);
					}
//				}
			}
			long endTime=System.currentTimeMillis();
		    float excTime=(float)(endTime-startTime)/1000;
		    log.info("执行时间："+excTime+"s");
		} catch (Exception e) {
			log.error("报表数据初始化失败>>>>>>",e);
			return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysConstants.DEFAULT_MESSAGE.OPERATION_FAIL,
					MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_FAIL));
		} finally {
			// 最后清空临时表
			if (flag) {
				financialStatementsMapper.deleteBalanceTemp();
			}
		}
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
				MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));	
	}
	/**
	 * (非 Javadoc)  
	 * Title: initJqDetail 
	 * Description:初始化/查询加权信息
	 * @param endDate
	 * @param beginDate
	 * @param isInit
	 * @return  
	 * @see com.dhcc.finance.main.service.FinancialStatementsService#initJqDetail(java.lang.String, java.lang.String, java.lang.Boolean)    
	 * @author dml
	 * @date 2020年1月7日 上午9:50:37
	 * @修改日志：
	 */
	@Override
	public RestfulResponse<Object, CurrencyMeta> initJqDetail(String endDate, String beginDate, Boolean isInit) {
		SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
		if (isInit) {
			Boolean res = false;
			try {
				res = initData(endDate, beginDate,sysUserInfo);
			} catch (Exception e) {
				log.error("初始化每天余额异常>>>>>>",e);
			}
			if (!res) {
				return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysConstants.DEFAULT_MESSAGE.OPERATION_FAIL,
						MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_FAIL));
			}
		}
		// 先清空表
		cwGlWeightedMapper.deleteAll();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("startDate", beginDate);
		map.put("endDate", endDate);
		map.put("createUser", sysUserInfo==null? null:sysUserInfo.getUserId());
		map.put("useState", FinanceDictConsts.Syzt.EFFECTIVE);
		cwGlWeightedMapper.initCwGlWeighted(map);
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
				MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));	
	}


	/**
	 * @param reportDate
	 * @return com.dhcc.common.model.response.RestfulResponse<java.lang.String,com.dhcc.common.model.CurrencyMeta>
	 * @description: 校验报表信息
	 * @author lxj
	 * @date 2020-07-20 14:26
	 * @modify
	 */
	@Override
	public RestfulResponse<String, CurrencyMeta> checkReport(String reportDate) {
		boolean flag = true;

		List<Integer> sum = financialStatementsMapper.getReportNum(reportDate);
		if (sum != null && sum.get(0) != 0 && sum.get(1) != 0) {

			StringBuffer sb = new StringBuffer();
			// 资产 =负债+所有者权益
			BigDecimal diff1 = financialStatementsMapper.checkBalanceSheet(reportDate);
			if (diff1 != null && diff1.compareTo(new BigDecimal(0)) != 0) {
				flag = false;
				sb.append("资产不等于负债和所有者权益之和：");
				List<String> strings = financialStatementsMapper.checkBalanceSheetSingle(reportDate);
				strings.forEach(sb::append);
			}
			// 期初未分配 = 上期期末未分配
			BigDecimal diff2 = financialStatementsMapper.checkIncomeStatements(reportDate);
			if (diff2 != null && diff2.compareTo(new BigDecimal(0)) != 0) {
				flag = false;

				sb.append("期初未分配不等于上期期末未分配：");
				List<String> strings = financialStatementsMapper.checkIncomeStatementsSingle(reportDate);
				strings.forEach(sb::append);
			}
			// 期末未分配 = 损益平准金+未分配利润
			BigDecimal diff3 = financialStatementsMapper.checkBalanceSheetAndIncomeStatements(reportDate);
			if (diff3 != null && diff3.compareTo(new BigDecimal(0)) != 0) {
				flag = false;
				sb.append("期初未分配不等于损益平准金和未分配利润之和：");
				List<String> strings = financialStatementsMapper.checkBalanceSheetAndIncomeStatementsSingle(reportDate);
				strings.forEach(sb::append);
			}
			if (flag) {
				return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.SUCCESS, SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
						MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
			}
			return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.FAIL, sb.toString(),
					MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
		} else {
			return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.FAIL, FinanceStatusCode.TABLE_DATA_NOT_INITIALIZATION.message(),
					MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
		}


	}
	/**

	/*
	 * Title: exportExcelInfo
	 * Description: 导出资产负债表或利润表数据
	 * @param param
	 * @param reportDate
	 * @param reportType
	 * @param searchType
	 * @return org.springframework.http.ResponseEntity<org.springframework.core.io.FileSystemResource>
	 * @Author jiangyoushun
	 * @Date 2020/7/14 11:34
	 * @修改日志:
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseEntity<FileSystemResource> exportExcelInfo(String param,String reportDate, String reportType,String searchType) {

		// 获取存储模板地址
		String fileLocal = null;
		if (FinanceDictConsts.REPORT_TYPE.ZCFZB.equals(reportType)) {
			fileLocal = financialStatementsMapper.searchExportTemplate(TemplateName.ZCFZBMB);
		} else {
			fileLocal = financialStatementsMapper.searchExportTemplate(TemplateName.LRBMB);
		}
		StorePath storePath = StorePath.praseFromUrl(preUrl+fileLocal);
		// 导出文件
		File file = null;
		XSSFWorkbook workbook = null;
		try {
			byte[] content = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
			// 获取导出模板文件
			InputStream input = new ByteArrayInputStream(content);
			workbook = new XSSFWorkbook(input);
		} catch (Exception e) {
			log.error("读取模板文件异常"+ e);
		}
		Sheet sheet = workbook.getSheetAt(0);
		// 查询期末
		List<CwGlReportInfo> list = financialStatementsMapper.selectCwGlReportInfo(param, reportDate, reportType, searchType);

		// 获取期初时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String lastMonth = null;
		try {
			Date date = sdf.parse(reportDate);
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			c.add(Calendar.MONTH, -1);
			c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
			Date date1 = c.getTime();
			lastMonth = sdf.format(date1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 查询期初
		List<CwGlReportInfo> lastMonthList = financialStatementsMapper.selectCwGlReportInfo(param, lastMonth, reportType, searchType);

		// 资产负债表特殊处理年初
		List<CwGlReportInfo> lastYearList = null;
		if (FinanceDictConsts.REPORT_TYPE.ZCFZB.equals(reportType)) {
			// 获取年初时间
			SimpleDateFormat sdfY = new SimpleDateFormat("yyyyMMdd");
			String lastYear = null;
			try {
				Date date = sdfY.parse(reportDate);
				Calendar c = Calendar.getInstance();
				c.setTime(date);
				c.add(Calendar.YEAR, -1);
				c.set(Calendar.MONTH, 11);
				Date date1 = c.getTime();
				lastYear = sdfY.format(date1);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 查询年初
			lastYearList = financialStatementsMapper.selectCwGlReportInfo(param, lastYear, reportType, searchType);
		}

		// 将不同月份的数据添加进map集合
		Map<String, List<CwGlReportInfo>> map = new HashMap<>();
		map.put("nowMonth", list);
		map.put("lastMonth", lastMonthList);
		if (FinanceDictConsts.REPORT_TYPE.ZCFZB.equals(reportType)) {
			map.put("lastYear", lastYearList);
		}
		try {
			if (FinanceDictConsts.REPORT_TYPE.ZCFZB.equals(reportType)) {
				file = FinanceExcelUtil.writeBalanceSheet(map, sheet, workbook, searchType);
			} else {
				file = FinanceExcelUtil.writeProfit(map, sheet, workbook, searchType);
			}
		} catch (Exception e) {
			log.error("导出表错误" + e);
			Shift.fatalThrow(TaStatusCode.DO_EXPORT_FAIL);
		}

		FileSystemResource fileSystemResource = new FileSystemResource(file);
		//设置HttpHeaders,使得浏览器响应下载
		HttpHeaders headers = new HttpHeaders();
		//通知浏览器以attachment
		headers.setContentDispositionFormData("attachment", new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime()) + "." + FilenameUtils.getExtension(file.getName()));
		//application/octet-stream ： 二进制流数据（最常见的文件下载）
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		//把文件以字节流写回
		return new ResponseEntity<FileSystemResource>(fileSystemResource, headers, HttpStatus.CREATED);
	}

	/*
	 * Title: importExcelInfo
	 * Description: 导入资产负债表或利润表数据
	 * @param fileUploadRequest
	 * @param param
	 * @param reportDate
	 * @param reportType
	 * @param searchType
	 * @return com.dhcc.common.model.response.RestfulResponse<java.lang.Object,com.dhcc.common.model.CurrencyMeta>
	 * @Author jiangyoushun
	 * @Date 2020/7/14 11:35
	 * @修改日志:
	 **/
    @Override
    public RestfulResponse<Object, CurrencyMeta> importExcelInfo(FileUploadRequest fileUploadRequest, String param,String reportDate, String reportType,String searchType) {
        // 当前登录用户
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate,
                SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        RestStatus code = checkBeforeImport(sysUserInfo, fileUploadRequest);
        if (code != null) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, code.message(), null, MetaDataUtil.getMeta(tracer, code));
        }
	    MultipartFile[] files = fileUploadRequest.getFiles();
        List<CwGlReportInfo> list = null;
        try {
            MultipartFile multipartFile = files[0];
            String fileRealName = multipartFile.getOriginalFilename();
            int pointIndex = fileRealName.lastIndexOf('.');
            String fileSuffix = fileRealName.substring(pointIndex); // 截取文件后缀

            File excelFile = File.createTempFile("tmp_", fileSuffix);
            multipartFile.transferTo(excelFile);

            // 解析出导入文件的数据
			list = FinanceExcelUtil.readExcel(excelFile, reportType);
        } catch (Exception e) {
            log.error("数据流操作异常");
            code = TaStatusCode.READ_EXCEL_FILE_FAIL;
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, code.message(), null, MetaDataUtil.getMeta(tracer, code));
        }
        if (list == null) {
            code = TaStatusCode.READ_EXCEL_FILE_FAIL;
        } else if (list.size() <= 0) {
            code = TaStatusCode.NO_IMPORT_DATA_ERROR;
        }
        if (code != null) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL, code.message(), null, MetaDataUtil.getMeta(tracer, code));
        }

		Date updateTime = new Date();
        String updateUser = sysUserInfo.getUserId();
		financialStatementsMapper.updateBalanceSheetInfo(list,param,reportDate,updateTime,updateUser);
		log.debug("批量修改成功");
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
    }

    private RestStatus checkBeforeImport(SysUserInfo sysUserInfo, FileUploadRequest fileUploadRequest) {
        RestStatus code = null;
        if (sysUserInfo == null) {
            code = SysStatusCode.USER_LOGOUT_ERROR;
        } else if (fileUploadRequest == null) {
            code = TaStatusCode.IMPORT_DATA_READ_FAIL;
        }
        return code;
    }


    /**
	 * 功能描述：初始化每天余额
	 * @param endDate
	 * @param beginDate
	 * @return Boolean
	 * @author dml
	 * @throws Exception 
	 * @date 2020年1月7日 上午9:54:45
	 * @修改日志：
	 */
	private Boolean initData(String endDate, String beginDate, SysUserInfo sysUserInfo) throws Exception {
		cwGlWeightedDetailMapper.deleteByDay(beginDate, endDate);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date eDate = sdf.parse(endDate);
        Date bDate = sdf.parse(beginDate);
        Calendar c = Calendar.getInstance();  
        c.setTime(bDate);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("subjcode", "4001");
        map.put("useState", FinanceDictConsts.Syzt.EFFECTIVE);
        map.put("createUser", sysUserInfo==null? null:sysUserInfo.getUserId());
        while (c.getTime().compareTo(eDate)<=0) {// 从开始日期开始循环跑每天余额到截止日期为止
        	Date reportDate = c.getTime();
        	map.put("reportDate", reportDate);
        	cwGlWeightedDetailMapper.insertByDay(map);
			c.add(Calendar.DAY_OF_MONTH, 1);
		}
		return true;
	}
	
	/**
	 * 功能描述：序时账数据导出为excel
	 * @param chroAccountExportParam
	 * @return
	 * @throws ParseException
	 * @author leiyu
	 * @date 2020年7月17日 上午11:53:53
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseEntity<FileSystemResource> exportChroAccountInfo(ChroAccountExportParam chroAccountExportParam) throws ParseException {
		// 获取模板文件
        File modelFile;
        // 导出文件
        File file = null;
        XSSFWorkbook wb = null;
        List<CwChroAccountInfo> cwChroAccountInfoList = null;
    	cwChroAccountInfoList = financialStatementsMapper.selectChroAccountInfo(chroAccountExportParam);
        List<Integer> list = new ArrayList<Integer>();
        
        //获取本地存储模板地址
//        String disclosureExporttemplete = templateExcelPath + TemplateName.CHROACCOUNTEXPORTTEMPLETE;
//        modelFile = new File(disclosureExporttemplete);
//        try {
//			FileInputStream fs = FileUtils.openInputStream(modelFile);
//			wb = new XSSFWorkbook(fs);
			
        // 获取存储模板地址
        String fileLocal = financialStatementsMapper.searchExportTemplate(TemplateName.CHROACCOUNTEXPORTTEMPLETE);
        StorePath storePath = StorePath.praseFromUrl(preUrl+fileLocal);

        try {
        	byte[] content = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
            // 获取导出模板文件
            InputStream input = new ByteArrayInputStream(content);
            wb = new XSSFWorkbook(input);
            
			Sheet sheet = wb.getSheetAt(0);			
			file = ExcelUtils.writeExcelData(cwChroAccountInfoList, CwChroAccountInfo.class, sheet, null, 1, wb,list);
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        FileSystemResource fileSystemResource = new FileSystemResource(file);
        //设置HttpHeaders,使得浏览器响应下载
        HttpHeaders headers = new HttpHeaders();
        //设置响应文件
        headers.setContentDispositionFormData("attachment", Calendar.getInstance().
          getTimeInMillis() + "." + FilenameUtils.getExtension(file.getName()));
        //设置响应方式
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //把文件以字节流写回
        return new ResponseEntity<FileSystemResource>(fileSystemResource, headers, HttpStatus.CREATED);
	}

}


















