package org.springblade.finance.controller;


import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.finance.dto.DateRangeFileDTO;
import org.springblade.finance.entity.DateRangeAccount;
import org.springblade.finance.entity.IntOndaterangeAccountFile;
import org.springblade.finance.service.DateRangeAccountService;
import org.springblade.finance.service.IIntOndaterangeAccountFileService;
import org.springblade.finance.vo.DateRangeAccountBgfdzVO;
import org.springblade.finance.vo.DateRangeAccountFzzVO;
import org.springblade.finance.vo.DateRangeAccountKftpVO;
import org.springblade.finance.vo.DateRangeAccountSfwyVO;
import org.springblade.finance.vo.DateRangeAccountTzjeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zbc
 * @since 2021-11-29
 */
@RestController
@RequestMapping("finance/ondaterangeAccount")
@Api(value = "结算表文件上传", tags = "结算表文件上传接口")
@Slf4j
public class IntOndaterangeAccountFileController {


	@Autowired
	private IIntOndaterangeAccountFileService intOndaterangeAccountFileService;

	@Autowired
	private DateRangeAccountService dateRangeAccountService;

	@Value("${blade.file.uploadPath}")
	private String picDir;

	@PostMapping("/uploadFile")
	@ApiOperation("结算表文件上传")
	public R uploadFile(DateRangeFileDTO d){
		if (null == d || d.getFile() == null || d.getSid() == null) {
			return R.fail("参数异常");
		}
		//图片上传
		String oFileName = d.getFile().getOriginalFilename();
		String fileSuffix = oFileName.substring(oFileName.lastIndexOf("."));

		if (!".jpg".equalsIgnoreCase(fileSuffix) &&
			!".jpeg".equalsIgnoreCase(fileSuffix) &&
			!".gif".equalsIgnoreCase(fileSuffix) &&
			!".png".equalsIgnoreCase(fileSuffix) &&
			!".pdf".equalsIgnoreCase(fileSuffix) &&
			!".doc".equalsIgnoreCase(fileSuffix) &&
			!".docx".equalsIgnoreCase(fileSuffix) &&
			!".xls".equalsIgnoreCase(fileSuffix) &&
			!".xlsx".equalsIgnoreCase(fileSuffix)
		) {
			return R.fail("只能上传jpg/jpeg/gif/png/pdf/doc/xls类型的文件");
		}
		String tempFileName = UUID.randomUUID().toString() + fileSuffix;
		File f = new File(picDir + tempFileName);
		try {
			FileUtils.copyInputStreamToFile(d.getFile().getInputStream(), f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String path = "uploads/" + tempFileName;

		BladeUser bladeUser = AuthUtil.getUser();
		IntOndaterangeAccountFile accountFile = new IntOndaterangeAccountFile();
		accountFile.setSid(d.getSid());
		accountFile.setFileName(d.getFile().getOriginalFilename());
		accountFile.setFilePath(path);
		accountFile.setUploadUser(bladeUser.getUserName());
		accountFile.setUploadTime(new Date());
		accountFile.setFileCode(RandomUtil.randomString(20));
		return R.data(intOndaterangeAccountFileService.save(accountFile));
	}


	@PostMapping("/removeFile")
	@ApiOperation("删除结算表上传文件")
	public R removeFile(String fileCode){
		if(StringUtils.isBlank(fileCode)){
			return R.fail("文件编码不能为空");
		}
		return R.data(intOndaterangeAccountFileService.remove(new LambdaQueryWrapper<IntOndaterangeAccountFile>()
			.eq(IntOndaterangeAccountFile::getFileCode,fileCode))
		);
	}



	@GetMapping("/statementDownload")
	@ApiOperation("下载结算单明细-5类")
	public void statementDownload(String sid, HttpServletResponse response) throws IOException {
		if(StringUtils.isBlank(sid)){
			log.info("statementDownload ---- sid = {}",sid);
		}
		DateRangeAccount rangeAccount = dateRangeAccountService.getOne(new LambdaQueryWrapper<DateRangeAccount>()
			.eq(DateRangeAccount::getSid, sid));

		if(rangeAccount == null){
			log.info("statementDownload ---- rangeAccount = {}",rangeAccount);
		}
		String tempFileName = rangeAccount.getTheMonth().toString()+"渠道用户扣罚明细数据-" + rangeAccount.getSid();

		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		String fileName = URLEncoder.encode(tempFileName, "utf-8");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

		//String filePath = "D:/boyuan/bladexmaster/jar/" + tempFileName;
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

		//400扣罚明细数据
		List<DateRangeAccountFzzVO> fzzList = intOndaterangeAccountFileService.getFzzDetail(sid);
		WriteSheet writeSheet = EasyExcel.writerSheet(0, "400扣罚（明细）").head(DateRangeAccountFzzVO.class).build();
		excelWriter.write(fzzList,writeSheet);

		//客服退赔
		List<DateRangeAccountKftpVO> kftpList = intOndaterangeAccountFileService.getKftpDetail(sid);
		WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "客服退赔").head(DateRangeAccountKftpVO.class).build();
		excelWriter.write(kftpList,writeSheet1);

		//省分违约（明细）
		List<DateRangeAccountSfwyVO> sfwyList = intOndaterangeAccountFileService.getDfwyDetail(sid);
		WriteSheet writeSheet2 = EasyExcel.writerSheet(2, "省分违约（明细）").head(DateRangeAccountSfwyVO.class).build();
		excelWriter.write(sfwyList,writeSheet2);

		//调账金额
		List<DateRangeAccountTzjeVO> tzjeList = intOndaterangeAccountFileService.getTzjeDetail(sid);
		WriteSheet writeSheet3 = EasyExcel.writerSheet(3,"调账金额").head(DateRangeAccountTzjeVO.class).build();
		excelWriter.write(tzjeList,writeSheet3);

		//不规范定制（明细）
		List<DateRangeAccountBgfdzVO> bgfdzList = intOndaterangeAccountFileService.getBgfdzDetail(sid);
		WriteSheet writeSheet4 = EasyExcel.writerSheet(4,"不规范定制（明细）").head(DateRangeAccountBgfdzVO.class).build();
		excelWriter.write(bgfdzList,writeSheet4);
		excelWriter.finish();
		//return R.success("year"+tempFileName);
	}



}

