package org.springblade.finance.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.audit.entity.BladeReportTask;
import org.springblade.audit.service.IBladeReportTaskService;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.finance.dto.FinVippoolMonthDetailDTO;
import org.springblade.finance.dto.YksytAccountExcel;
import org.springblade.finance.dto.YksytAccountPdfToExcel;
import org.springblade.finance.entity.*;
import org.springblade.finance.enums.PartnerInformationEnum;
import org.springblade.finance.service.*;
import org.springblade.finance.util.ChineseYuanUtil;
import org.springblade.finance.vo.*;
import org.springblade.system.client.UserClient;
import org.springblade.system.client.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 优酷收银台渠道发展优酷20元产品的结算表
 * </p>
 *
 * @author zbc
 * @since 2022-04-06
 */
@RestController
@RequestMapping("finance/yksytAccount")
@Api(value = "其他渠道结算", tags = "其他渠道结算")
@Slf4j
public class YksytAccountController {

	@Autowired
	private IYksytAccountService yksytAccountService;

	@Autowired
	private IYksytAccountViewService yksytAccountViewService;

	@Autowired
	private IYksytChannelsService yksytChannelsService;

	@Autowired
	private ChannelSpidViewService channelSpidViewService;

	@Autowired
	private IYksytAccountFileService yksytAccountFileService;

	@Autowired
	private UserClient userService;

	@Autowired
	private PdfExportService pdfExportService;

	@Autowired
	private IBladeReportTaskService bladeReportTaskService;

	@Autowired
	private IFinVippoolMonthDetailService finVippoolMonthDetailService;

	@Autowired
	private DealUserAccountsService dealUserAccountsService;


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


	@GetMapping("/beforeChrist/export")
	@ApiOperation(value = "导出结算表BC")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "sIds", value = "多选导出传递多个sid", required = false),
		@ApiImplicitParam(name = "dealUserIds", value = "结算用户ID，逗号隔开。全部渠道传空或者不传递", required = false),
		@ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = false),
		@ApiImplicitParam(name = "dealType", value = "结算类型。1：有效用户；2：会员权益；3：出账用户； ", dataType = "Integer", required = false),
		@ApiImplicitParam(name = "startTime", value = "开始月份(格式：yyyyMM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "endTime", value = "结束月份(格式：yyyyMM)", dataType = "string", required = false)
	})
	public R beforeChristExport(String[] sIds,String[] dealUserIds, String spid,Integer dealType,String startTime,String endTime, HttpServletResponse response) throws Exception {
		LambdaQueryWrapper<YksytAccountView> queryWrapper = Wrappers.<YksytAccountView>lambdaQuery();
		if(dealUserIds != null && dealUserIds.length > 0) {
			List<String> strings = Arrays.asList(dealUserIds);
			List<String> collect = null;
			if(strings != null && strings.size() > 0){
				QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
				dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
				dealQueryWrapper.in("DEAL_USERID",strings);
				List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
				collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
			}
			queryWrapper.in(YksytAccountView::getDealAccountId, collect);
		}

		if(StringUtils.isNotEmpty(spid)) {
			queryWrapper.eq(YksytAccountView::getSpid, spid);
		}
		if(dealType != null){
			queryWrapper.eq(YksytAccountView::getDealType, dealType);
		}
		if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
			if(startTime.equals(endTime)){
				queryWrapper.eq(YksytAccountView::getThemonth,startTime);
			}else {
				queryWrapper.le(YksytAccountView::getThemonth,endTime).ge(YksytAccountView::getThemonth, startTime);
			}
		}else if(StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)){
			queryWrapper.ge(YksytAccountView::getThemonth, startTime);
		}else if(StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)){
			queryWrapper.le(YksytAccountView::getThemonth,endTime);
		}

		//不包括本月数据
		Integer thisMonth = Integer.valueOf(DateTimeFormatter.ofPattern("yyyyMM").format(LocalDate.now()));
		queryWrapper.lt(YksytAccountView::getThemonth, thisMonth);

		List<YksytAccountView> dbAccountList = null;
		if(sIds != null && sIds.length > 0) {
			dbAccountList = yksytAccountViewService.list(new LambdaQueryWrapper<YksytAccountView>()
				.in(YksytAccountView::getSid, Arrays.asList(sIds))
			);
		}else {
			dbAccountList = yksytAccountViewService.list(queryWrapper.orderByDesc(YksytAccountView::getThemonth, YksytAccountView::getChannelId));
		}

		List<YksytAccountExcel> accountList = new ArrayList<YksytAccountExcel>();
		if(dbAccountList != null && !dbAccountList.isEmpty()) {
			for (YksytAccountView yksytAccountView : dbAccountList) {
				YksytAccountExcel excel = new YksytAccountExcel();
				BeanUtil.copyProperties(yksytAccountView, excel);
				//结算类型。1：有效用户；2：会员权益；3：出账用户；4：PRM发布
				if(yksytAccountView.getDealType() == 1){
					excel.setDealType("有效用户");
				}else if(yksytAccountView.getDealType() == 2){
					excel.setDealType("会员权益");
				}else if(yksytAccountView.getDealType() == 3){
					excel.setDealType("出账用户");
				}else if(yksytAccountView.getDealType() == 4){
					excel.setDealType("PRM发布");
				}else {
					excel.setDealType("无分类");
				}
				accountList.add(excel);
			}
			/*dbAccountList.forEach(item ->
				accountList.add(BeanUtil.copy(item, YksytAccountExcel.class))
			);*/
		}

		Long userId = SecureUtil.getUserId();
		UserModel byId = userService.getById(userId);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		String format = simpleDateFormat.format(new Date());
		String tempFileName = "其他渠道-"+byId.getRealName() + "-结算表-" + format + RandomUtil.randomString(2) + ".xlsx";

		BladeReportTask bladeReportTask = new BladeReportTask();
		bladeReportTask.setReportName(tempFileName);
		bladeReportTask.setReportType(2);
		bladeReportTask.setReportStatus(1);
		bladeReportTask.setDownloadStatus(1);
		bladeReportTask.setCreateUser(userId);
		bladeReportTask.setCreateTime(new Date());
		boolean res = bladeReportTaskService.save(bladeReportTask);
		String filePath = picDir + tempFileName;
		Long beginTime = System.currentTimeMillis();
		if(res){
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						//String filePath = "D:/boyuan/work2/excel/" + tempFileName;
						EasyExcel.write(filePath, YksytAccountExcel.class).sheet().doWrite(accountList);
						Long endTime = System.currentTimeMillis();
						String opetime = (endTime - beginTime) + "ms";
						bladeReportTask.setUseTime(opetime);
						bladeReportTask.setReportUrl("uploads/" + tempFileName);
						bladeReportTask.setReportStatus(2);
						bladeReportTask.setDownloadStatus(1);
						bladeReportTaskService.updateById(bladeReportTask);
					} catch (Exception e) {
						bladeReportTask.setReportStatus(3);
						bladeReportTask.setDownloadStatus(1);
						bladeReportTaskService.updateById(bladeReportTask);
						e.printStackTrace();
					}
				}
			}).start();
		}else {
			bladeReportTask.setReportStatus(3);
			bladeReportTaskService.updateById(bladeReportTask);
			return R.fail("导出任务提交失败");
		}
		return R.success("导出任务提交成功");
	}


	@PostMapping("/percheck")
	@ApiOperation(value = "预审")
	public R reject(@RequestParam Long sid,@RequestParam Integer percheckFlag){
		Long userId = SecureUtil.getUserId();
		//todo 测试环境小强为预审人、正式换为张凯
		if(userId != 1392663744517726210L){
			return R.fail("您没有预审权限");
		}
		if(sid == null || percheckFlag == null){
			return R.fail("参数异常");
		}
		if(percheckFlag != 1 && percheckFlag != 2){
			return R.fail("预审状态错误");
		}
		YksytAccount entity = yksytAccountService.getOne(new LambdaQueryWrapper<YksytAccount>()
			.eq(YksytAccount::getSid, sid)
			.eq(YksytAccount::getPercheckFlag,0)
		);
		if(entity == null){
			return R.fail("预审数据已审核/不存在");
		}
		UserModel byId = userService.getById(userId);
		entity.setPercheckFlag(percheckFlag);
		entity.setPercheckTime(new Date());
		entity.setPerchecker(byId.getRealName());
		return R.status(yksytAccountService.update(entity,new LambdaUpdateWrapper<YksytAccount>().eq(YksytAccount::getSid,sid)));
	}


	@GetMapping("/statementDownload")
	@ApiOperation("互联网2导出-结算单明细-6类")
	public void statementDownload(String sid, HttpServletResponse response) throws IOException {
		if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(sid)){
			log.info("statementDownload ---- sid = {}",sid);
		}
		YksytAccountView yksytAccount = yksytAccountViewService.getOne(new LambdaQueryWrapper<YksytAccountView>()
				.eq(YksytAccountView::getSid, sid));

		if(yksytAccount != null){
			String tempFileName = yksytAccount.getThemonth().toString()+"互联网2渠道用户扣罚明细数据-" + yksytAccount.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");

			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

			if(yksytAccount.getDealType() == 3){
				//省分违约（明细）
				List<YksytAccountSfwyVO> sfwyList = yksytAccountViewService.getSfwyDetail(sid);
				WriteSheet writeSheet = EasyExcel.writerSheet(0, "省分违约（明细）").head(YksytAccountSfwyVO.class).build();
				excelWriter.write(sfwyList,writeSheet);

				//不规范定制（明细）
				List<YksytAccountBgfdzVO> bgfdzList = yksytAccountViewService.getBgfdzDetail(sid);
				WriteSheet writeSheet2 = EasyExcel.writerSheet(1,"不规范定制（明细）").head(YksytAccountBgfdzVO.class).build();
				excelWriter.write(bgfdzList,writeSheet2);
			}else if(yksytAccount.getDealType() == 4){

				//cp退费明细
				List<YksytAccountCptfVO> cptfList = yksytAccountViewService.getCptfDetail(sid,yksytAccount.getThemonth());
				WriteSheet writeSheet = EasyExcel.writerSheet(0, "cp退费（明细）").head(YksytAccountCptfVO.class).build();
				excelWriter.write(cptfList,writeSheet);

				//客服退赔付费
				List<YksytAccountKftpffVO> kftpffList = yksytAccountViewService.getKftpffDetail(sid);
				WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "客服退赔付费").head(YksytAccountKftpffVO.class).build();
				excelWriter.write(kftpffList,writeSheet2);

				//省分违约扣款
				List<YksytAccountSfwykkVO> sfwykkList = yksytAccountViewService.getSfwykkDetail(sid);
				WriteSheet writeSheet3 = EasyExcel.writerSheet(2, "省分违约扣款").head(YksytAccountSfwykkVO.class).build();
				excelWriter.write(sfwykkList,writeSheet3);

				//不规范定制处罚
				List<YksytAccountBgfdzcfVO> bgfdzcfList = yksytAccountViewService.getBgfdzcfDetail(sid);
				WriteSheet writeSheet4 = EasyExcel.writerSheet(3,"不规范定制处罚").head(YksytAccountBgfdzcfVO.class).build();
				excelWriter.write(bgfdzcfList,writeSheet4);
			}
			excelWriter.finish();
		}
		log.info("互联网2导出-结算单明细 statementDownload ---- yksytAccount = {}",yksytAccount);
	}


	@GetMapping("/page")
	@ApiOperation(value = "分页查询其他渠道结算数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "dealUserIds", value = "结算用户ID，逗号隔开。全部渠道传空或者不传递", required = false),
		@ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = false),
		@ApiImplicitParam(name = "dealType", value = "结算类型。1：有效用户；2：会员权益；3：出账用户；4：PRM发布 ", dataType = "Integer", required = false),
		@ApiImplicitParam(name = "startTime", value = "开始月份(格式：yyyyMM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "endTime", value = "结束月份(格式：yyyyMM)", dataType = "string", required = false)
	})
	public R<IPage<YksytAccountView>> page(String[] dealUserIds, String spid, Integer dealType, String startTime, String endTime, Query query){
		if(query.getSize() == null){
			query.setSize(5);
		}
		LambdaQueryWrapper<YksytAccountView> queryWrapper = Wrappers.<YksytAccountView>lambdaQuery();
		queryWrapper.ne(YksytAccountView::getDealType, 2);
		if(dealUserIds != null && dealUserIds.length > 0) {
			List<String> strings = Arrays.asList(dealUserIds);
			List<String> collect = null;
			if(strings != null && strings.size() > 0){
				QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
				dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
				dealQueryWrapper.in("DEAL_USERID",strings);
				List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
				collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
			}
			queryWrapper.in(YksytAccountView::getDealAccountId, collect);
		}


		if(StringUtils.isNotEmpty(spid)) {
			queryWrapper.eq(YksytAccountView::getSpid, spid);
		}
		if(dealType != null){
			queryWrapper.eq(YksytAccountView::getDealType, dealType);
		}
		if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
			if(startTime.equals(endTime)){
				queryWrapper.eq(YksytAccountView::getThemonth,startTime);
			}else {
				queryWrapper.le(YksytAccountView::getThemonth,endTime).ge(YksytAccountView::getThemonth, startTime);
			}
		}else if(StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)){
			queryWrapper.ge(YksytAccountView::getThemonth, startTime);
		}else if(StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)){
			queryWrapper.le(YksytAccountView::getThemonth,endTime);
		}

		IPage<YksytAccountView> pageResult = yksytAccountViewService.page(Condition.getPage(query), queryWrapper.orderByDesc(YksytAccountView::getThemonth));
		if(pageResult != null && pageResult.getRecords() != null) {
			pageResult.getRecords().stream().forEach(f -> {
				List<YksytAccountFile> list = yksytAccountFileService.list(new LambdaQueryWrapper<YksytAccountFile>()
					.eq(YksytAccountFile::getSid, f.getSid())
				);
				f.setFileList(list);

				BigDecimal pct = new BigDecimal(f.getMatchPct()).multiply(new BigDecimal(100)).setScale(BigDecimal.ROUND_HALF_UP,2);
				f.setMatchPct(pct.doubleValue());
				String pctStr = pct.toString().substring(0, pct.toString().indexOf("."));
				f.setMatchPctStr(pctStr+"%");
			});
		}
		return R.data(pageResult);
	}



	@PostMapping("/editFlagRender")
	@ApiOperation(value = "编辑报账状态")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sid", value = "sid唯一ID", required = true),
			@ApiImplicitParam(name = "isFlag", value = "报账状态 0：未报账；1：已报账；", dataType = "Integer", required = true)
	})
	public R edit(Long sid,Integer isFlag){
		Long userId = SecureUtil.getUserId();
		if(sid == null || (isFlag != 0 && isFlag!= 1)){
			return R.fail("参数异常");
		}
		LambdaUpdateWrapper<YksytAccount> wrapper = new LambdaUpdateWrapper<>();
		wrapper.set(YksytAccount::getRenderUser,userId);
		wrapper.set(YksytAccount::getRenderTime,new Date());
		wrapper.set(YksytAccount::getFlagRender,isFlag);
		wrapper.eq(YksytAccount::getSid,sid);
		return R.data(yksytAccountService.update(wrapper));
	}


	/**
	 * 互联网2 渠道结算明细列表
	 * @param dealUserIds
	 * @param spid
	 * @param startTime
	 * @param endTime
	 * @param isFlag
	 * @param theMonth
	 * @param query
	 * @return
	 */
	@GetMapping("/redayList")
	@ApiOperation(value = "互联网2 渠道结算明细列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "dealUserIds", value = "结算用户ID，逗号隔开。全部渠道传空或者不传递", required = false),
			@ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = false),
			@ApiImplicitParam(name = "startTime", value = "开始月份(格式：yyyy-MM)", dataType = "string", required = false),
			@ApiImplicitParam(name = "endTime", value = "结束月份(格式：yyyy-MM)", dataType = "string", required = false),
			@ApiImplicitParam(name = "isFlag", value = "是否报账标记：0：未报账；1：已报账", dataType = "Integer", required = false)
	})
	public R<IPage<YksytAccountView>> redayList(String[] dealUserIds, String spid, String startTime, String endTime, Integer isFlag, Query query){
		if(query.getSize() == null){
			query.setSize(5);
		}
		LambdaQueryWrapper<YksytAccountView> queryWrapper = Wrappers.<YksytAccountView>lambdaQuery();
		if(dealUserIds != null && dealUserIds.length > 0) {
			List<String> strings = Arrays.asList(dealUserIds);
			List<String> collect = null;
			if(strings != null && strings.size() > 0){
				QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
				dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
				dealQueryWrapper.in("DEAL_USERID",strings);
				List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
				collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
			}
			queryWrapper.in(YksytAccountView::getDealAccountId, collect);
		}
		if(StringUtils.isNotEmpty(spid)) {
			queryWrapper.eq(YksytAccountView::getSpid, spid);
		}
		if(StringUtils.isNotEmpty(startTime) && parseDateString(startTime) != 0) {
			int startDate = Integer.valueOf(startTime.replaceAll("\\-", ""));
			queryWrapper.ge(YksytAccountView::getThemonth, startDate);
		}
		if(StringUtils.isNotEmpty(endTime) && parseDateString(endTime) != 0) {
			int endDate = Integer.valueOf(endTime.replaceAll("\\-", ""));
			queryWrapper.le(YksytAccountView::getThemonth, endDate);
		}
		if(isFlag != null){
			queryWrapper.eq(YksytAccountView::getFlagRender, isFlag);
		}
		IPage<YksytAccountView> resultList = yksytAccountViewService.page(Condition.getPage(query), queryWrapper.orderByDesc(YksytAccountView::getThemonth, YksytAccountView::getChannelId));
		return R.data(resultList);
	}


    @GetMapping("/downloadRedayExcel")
    @ApiOperation(value = "下载互联网2 渠道结算明细Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "渠道ID，逗号隔开。全部渠道传空或者不传递", required = false),
            @ApiImplicitParam(name = "dealUserIds", value = "渠道ID，逗号隔开。全部渠道传空或者不传递", required = false),
            @ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = false),
            @ApiImplicitParam(name = "startTime", value = "开始月份(格式：yyyy-MM)", dataType = "string", required = false),
            @ApiImplicitParam(name = "endTime", value = "结束月份(格式：yyyy-MM)", dataType = "string", required = false),
            @ApiImplicitParam(name = "isFlag", value = "是否报账标记：0：未报账；1：已报账", dataType = "Integer", required = false)
    })
    public void downloadRedayExcel(String[] sids, String[] dealUserIds, String spid, String startTime,String endTime,Integer isFlag, HttpServletResponse response) throws Exception{
        LambdaQueryWrapper<YksytAccountView> queryWrapper = Wrappers.<YksytAccountView>lambdaQuery();
        if(sids != null && sids.length > 0){
            queryWrapper.in(YksytAccountView::getSid, Arrays.asList(sids));
        }else {
            if(dealUserIds != null && dealUserIds.length > 0) {
                List<String> strings = Arrays.asList(dealUserIds);
                List<String> collect = null;
                if(strings != null && strings.size() > 0){
                    QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
                    dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
                    dealQueryWrapper.in("DEAL_USERID",strings);
                    List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
                    collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
                }
                queryWrapper.in(YksytAccountView::getDealAccountId, collect);
            }

            if(StringUtils.isNotEmpty(spid)) {
                queryWrapper.eq(YksytAccountView::getSpid, spid);
            }
            if(StringUtils.isNotEmpty(startTime) && parseDateString(startTime) != 0) {
                int startDate = Integer.valueOf(startTime.replaceAll("\\-", ""));
                queryWrapper.ge(YksytAccountView::getThemonth, startDate);
            }
            if(StringUtils.isNotEmpty(endTime) && parseDateString(endTime) != 0) {
                int endDate = Integer.valueOf(endTime.replaceAll("\\-", ""));
                queryWrapper.le(YksytAccountView::getThemonth, endDate);
            }
			if(isFlag != null){
				queryWrapper.eq(YksytAccountView::getFlagRender, isFlag);
			}

        }

        List<YksytAccountView> resultList = yksytAccountViewService.list(queryWrapper.orderByDesc(YksytAccountView::getThemonth, YksytAccountView::getChannelId));
        List<YksytAccountPdfToExcel> accountList = new ArrayList<YksytAccountPdfToExcel>();
        if(resultList != null && !resultList.isEmpty()) {
            for (YksytAccountView yksytAccountView : resultList) {
				YksytAccountPdfToExcel excel = new YksytAccountPdfToExcel();
                BeanUtil.copyProperties(yksytAccountView,excel);
                accountList.add(excel);
            }
        }

        //response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("互联网2渠道结算明细表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .excelType(ExcelTypeEnum.XLSX).build();  //.password("123456")
        WriteSheet writeSheet = EasyExcel.writerSheet("数据").head(YksytAccountPdfToExcel.class).build();
        excelWriter.write(accountList, writeSheet);
        excelWriter.finish();
    }




    /**
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/downloadRedayPdf")
    @ApiOperation(value = "下载互联网2 渠道结算明细PDF")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "渠道ID，逗号隔开。全部渠道传空或者不传递", required = false),
            @ApiImplicitParam(name = "dealUserIds", value = "渠道ID，逗号隔开。全部渠道传空或者不传递", required = false),
            @ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = false),
            @ApiImplicitParam(name = "startTime", value = "开始月份(格式：yyyy-MM)", dataType = "string", required = false),
            @ApiImplicitParam(name = "endTime", value = "结束月份(格式：yyyy-MM)", dataType = "string", required = false),
			@ApiImplicitParam(name = "isFlag", value = "是否报账标记：0：未报账；1：已报账", dataType = "Integer", required = false)
    })
    public void downloadRedayPdf(String[] sids, String[] dealUserIds, String spid, String startTime,String endTime,Integer isFlag, HttpServletResponse response) throws Exception{
		LambdaQueryWrapper<YksytAccountView> queryWrapper = Wrappers.<YksytAccountView>lambdaQuery();
		if(sids != null && sids.length > 0){
			queryWrapper.in(YksytAccountView::getSid, Arrays.asList(sids));
		}else {
			if(dealUserIds != null && dealUserIds.length > 0) {
				List<String> strings = Arrays.asList(dealUserIds);
				List<String> collect = null;
				if(strings != null && strings.size() > 0){
					QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
					dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
					dealQueryWrapper.in("DEAL_USERID",strings);
					List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
					collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
				}
				queryWrapper.in(YksytAccountView::getDealAccountId, collect);
			}

			if(StringUtils.isNotEmpty(spid)) {
				queryWrapper.eq(YksytAccountView::getSpid, spid);
			}
			if(StringUtils.isNotEmpty(startTime) && parseDateString(startTime) != 0) {
				int startDate = Integer.valueOf(startTime.replaceAll("\\-", ""));
				queryWrapper.ge(YksytAccountView::getThemonth, startDate);
			}
			if(StringUtils.isNotEmpty(endTime) && parseDateString(endTime) != 0) {
				int endDate = Integer.valueOf(endTime.replaceAll("\\-", ""));
				queryWrapper.le(YksytAccountView::getThemonth, endDate);
			}
			if(isFlag != null){
				queryWrapper.eq(YksytAccountView::getFlagRender, isFlag);
			}

		}

		List<YksytAccountView> resultList = yksytAccountViewService.list(queryWrapper.orderByDesc(YksytAccountView::getThemonth, YksytAccountView::getChannelId));

        // Http 1.0 header
        response.setDateHeader("Expires", 0);
        response.addHeader("Pragma", "no-cache");
        // Http 1.1 header
        response.setHeader("Cache-Control", "no-cache");
        String encodedfileName = new String(("互联网2结算明细单").getBytes("GBK"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + ".pdf\"");
        response.setContentType("application/vnd.ms-pdf");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pdfExportService.createYksytReadyPdf(resultList, baos);
        response.getOutputStream().write(baos.toByteArray());
        response.getOutputStream().flush();
    }




    @GetMapping("/interestPage")
	@ApiOperation(value = "分页查询其他渠道结算数据-会员权益分类单独数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "company", value = "公司名称", dataType = "string", required = false),
		@ApiImplicitParam(name = "startTime", value = "开始月份(格式：yyyyMM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "endTime", value = "结束月份(格式：yyyyMM)", dataType = "string", required = false)
	})
	public R<IPage<YksytAccountView>> interestPage(String company, String startTime, String endTime, Query query){
		if(query.getSize() == null){
			query.setSize(5);
		}
		LambdaQueryWrapper<YksytAccountView> queryWrapper = Wrappers.<YksytAccountView>lambdaQuery();
		queryWrapper.eq(YksytAccountView::getDealType, 2);
		if(StringUtils.isNotEmpty(company)) {
			queryWrapper.eq(YksytAccountView::getCompany, company);
		}
		if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
			if(startTime.equals(endTime)){
				queryWrapper.eq(YksytAccountView::getThemonth,startTime);
			}else {
				queryWrapper.le(YksytAccountView::getThemonth,endTime).ge(YksytAccountView::getThemonth, startTime);
			}
		}else if(StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)){
			queryWrapper.ge(YksytAccountView::getThemonth, startTime);
		}else if(StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)){
			queryWrapper.le(YksytAccountView::getThemonth,endTime);
		}

		IPage<YksytAccountView> pageResult = yksytAccountViewService.page(Condition.getPage(query), queryWrapper.orderByDesc(YksytAccountView::getThemonth));
		if(pageResult != null && pageResult.getRecords() != null) {
			pageResult.getRecords().stream().forEach(f -> {
				List<YksytAccountFile> list = yksytAccountFileService.list(new LambdaQueryWrapper<YksytAccountFile>()
					.eq(YksytAccountFile::getSid, f.getSid())
				);
				f.setFileList(list);

				BigDecimal pct = new BigDecimal(f.getMatchPct()).multiply(new BigDecimal(100)).setScale(BigDecimal.ROUND_HALF_UP,2);
				f.setMatchPct(pct.doubleValue());
				String pctStr = pct.toString().substring(0, pct.toString().indexOf("."));
				f.setMatchPctStr(pctStr+"%");
			});
		}
		return R.data(pageResult);
	}



	@GetMapping("/vippool/selectList")
	@ApiOperation(value = "会员权益合作方名称列表")
	public R<List<FinVippoolMonthDetail>> selectList(){
		LambdaQueryWrapper<FinVippoolMonthDetail> queryWrapper = Wrappers.<FinVippoolMonthDetail>lambdaQuery();
		queryWrapper.select(FinVippoolMonthDetail::getCpShortname)
			.groupBy(FinVippoolMonthDetail::getCpShortname);
		return R.data(finVippoolMonthDetailService.list(queryWrapper));
	}


	@GetMapping("/vippoolDetailPage")
	@ApiOperation(value = "其他渠道结算明细（会员权益）")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "startTime", value = "月份(格式：yyyyMM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "endTime", value = "月份(格式：yyyyMM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "cpShortname", value = "合作方名称", dataType = "string", required = false)
	})
	public R<IPage<FinVippoolMonthDetail>> vippoolDetailPage(String startTime,String endTime,String cpShortname, Query query){
		if(query.getSize() == null){
			query.setSize(5);
		}
		LambdaQueryWrapper<FinVippoolMonthDetail> queryWrapper = Wrappers.<FinVippoolMonthDetail>lambdaQuery();

		if(StringUtils.isNotEmpty(startTime)) {
			queryWrapper.ge(FinVippoolMonthDetail::getThemonth, startTime);
		}
		if(StringUtils.isNotEmpty(endTime)) {
			queryWrapper.le(FinVippoolMonthDetail::getThemonth, endTime);
		}
		if(StringUtils.isNotEmpty(cpShortname)) {
			queryWrapper.like(FinVippoolMonthDetail::getCpShortname, cpShortname);
		}
		IPage<FinVippoolMonthDetail> pageResult = finVippoolMonthDetailService.page(Condition.getPage(query),queryWrapper);
		return R.data(pageResult);
	}


	@GetMapping("/vippoolDetailExport")
	@ApiOperation(value = "其他渠道结算明细（会员权益）导出")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "startTime", value = "月份(格式：yyyyMM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "endTime", value = "月份(格式：yyyyMM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "cpShortname", value = "合作方名称", dataType = "string", required = false)
	})
	public void export(String startTime,String endTime,String cpShortname, HttpServletResponse response) throws Exception {
		LambdaQueryWrapper<FinVippoolMonthDetail> queryWrapper = Wrappers.<FinVippoolMonthDetail>lambdaQuery();

		if(StringUtils.isNotEmpty(startTime)) {
			queryWrapper.ge(FinVippoolMonthDetail::getThemonth, startTime);
		}
		if(StringUtils.isNotEmpty(endTime)) {
			queryWrapper.le(FinVippoolMonthDetail::getThemonth, endTime);
		}
		if(StringUtils.isNotEmpty(cpShortname)) {
			queryWrapper.like(FinVippoolMonthDetail::getCpShortname, cpShortname);
		}
		List<FinVippoolMonthDetail> list = finVippoolMonthDetailService.list(queryWrapper);
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		String fileName = URLEncoder.encode("会员权益", "UTF-8");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.excelType(ExcelTypeEnum.XLSX).build();  //.password("123456")
		WriteSheet writeSheet = EasyExcel.writerSheet("数据").head(FinVippoolMonthDetailDTO.class).build();
		excelWriter.write(list, writeSheet);
		excelWriter.finish();
	}



	private static int parseDateString(String dateStr) {
		try {
			DateTimeFormatter.ofPattern("yyyy-MM").parse(dateStr);
			return 2;
		} catch (Exception e) {}
		return 0;
	}

	private static List<String> getMonthBetween(String startTime, String endTime) {
		ArrayList<String> result = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");// 格式化为年月
		try {
			Calendar min = Calendar.getInstance();
			Calendar max = Calendar.getInstance();

			min.setTime(sdf.parse(startTime));
			min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

			max.setTime(sdf.parse(endTime));
			max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

			Calendar curr = min;
			while (curr.before(max)) {
				result.add(sdf.format(curr.getTime()));
				curr.add(Calendar.MONTH, 1);
			}

			Collections.sort(result, new Comparator<Object>() {
				@Override
				public int compare(Object o1, Object o2) {
					String str1 = (String) o1;
					String str2 = (String) o2;
					SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
					Date date1 = null;
					Date date2 = null;
					try {
						date1 = format.parse(str1);
						date2 = format.parse(str2);
					} catch (ParseException e) {
						e.printStackTrace();
					}

					if (date2.compareTo(date1) > 0) {
						return -1;
					}
					return 1;
				}
			});
		}catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}



	/**
	 * @throws Exception
	 */
	@GetMapping("/downloadPdf")
	@ApiOperation(value = "下载优酷收银台PDF")
	@ApiImplicitParams({
	/*	@ApiImplicitParam(name = "spid", value = "产品ID", dataType = "string", required = true),
		@ApiImplicitParam(name = "dealAccountId", value = "渠道ID", dataType = "string", required = true),
		@ApiImplicitParam(name = "theMonth", value = "月份(格式：yyyyMM)", dataType = "string", required = true),*/
		@ApiImplicitParam(name = "sid", value = "序号", dataType = "Integer", required = true)
	})
	public void downloadPdf(@RequestParam String sid, HttpServletResponse response) throws Exception {
		LambdaQueryWrapper<YksytAccountView> queryWrapper = Wrappers.lambdaQuery(YksytAccountView.class).eq(YksytAccountView::getSid, sid);
		YksytAccountView yksytAccount = yksytAccountViewService.getOne(queryWrapper);
		if(yksytAccount != null) {
			/*YksytChannels yksytChannels = yksytChannelsService.getOne(new LambdaQueryWrapper<YksytChannels>()
				.eq(YksytChannels::getChannelid,yksytAccount.getChannelid()));
			if(yksytChannels != null) {
				yksytAccount.setCompany(yksytChannels.getCompany());
			}

			ChannelSpidView spidView = channelSpidViewService.getOne(new LambdaQueryWrapper<ChannelSpidView>()
				.eq(ChannelSpidView::getChannelId, yksytAccount.getChannelid())
				.eq(ChannelSpidView::getSpid, yksytAccount.getSpid())
			);
			if(spidView != null) {
				yksytAccount.setSpName(spidView.getSpname());
				yksytAccount.setChannelName(spidView.getChannelName());
			}*/

			// Http 1.0 header
			response.setDateHeader("Expires", 0);
			response.addHeader("Pragma", "no-cache");
			// Http 1.1 header
			response.setHeader("Cache-Control", "no-cache");
			String encodedfileName = new String(("有效用户确认单").getBytes("GBK"), "ISO8859-1");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + ".pdf\"");
			response.setContentType("application/vnd.ms-pdf");

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			//结算类型。1：有效用户；2：会员权益；3：出账用户；4：PRM发布
			if(yksytAccount.getDealType() == 1){
				createPdfYxyh(yksytAccount, baos);
			}
			if(yksytAccount.getDealType() == 2){
				createPdfHyqy(yksytAccount, baos);
			}
			if(yksytAccount.getDealType() == 3){
				createPdfCzyh(yksytAccount, baos);
			}
			if(yksytAccount.getDealType() == 4){
				createPdfPrm(yksytAccount, baos);
			}
			response.getOutputStream().write(baos.toByteArray());
			response.getOutputStream().flush();
		}
	}

	/**
	 * 有效用户类型PDF
	 * @param data
	 * @param baos
	 * @throws Exception
	 */
	private void createPdfYxyh(YksytAccountView data, ByteArrayOutputStream baos) throws Exception {
		Document document = new Document();
		PdfWriter.getInstance(document, baos);
		document.open();

		String theMonthStr = data.getThemonth().toString();
		String year = theMonthStr.substring(0, 4), month = theMonthStr.substring(4);

		// 使用语言包字体
		BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		// 外部字体
		ClassPathResource cpr = new ClassPathResource("/fonts/simfang.ttf");
		BaseFont bf = BaseFont.createFont(cpr.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font titleFont = new Font(bf, 12, Font.NORMAL);

		PdfPTable table = new PdfPTable(4);

		PdfPCell cell = new PdfPCell();
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		cell.setColspan(4);
		cell.setPaddingBottom(10f);
		Paragraph paragraph = new Paragraph(String.format("《%s月有效用户统计表》", month), new Font(abf, 13, Font.BOLD));
		paragraph.setAlignment(Paragraph.ALIGN_CENTER);
		cell.addElement(paragraph);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setColspan(4);
		cell.setPadding(10f);
		Paragraph para = new Paragraph(
			"1.甲方为推广其产品或服务，同意按照本协议的规定在乙方 独家代理的优酷APP收银台 渠道推广其产品或服务，按合作结算渠道推广费用。\n" +
				"2.本统计表自双方签署盖章之日起生效。\n" +
				"3.本统计表一式贰份，双方各执壹份。\n" +
				"4.请乙方收到此单据后 5个工作 日予以确认。", titleFont);
		para.setSpacingBefore(10f);
		cell.addElement(para);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("甲方：联通在线信息科技有限公司", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("乙方：" + data.getCompany(), titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("统计周期", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(String.format("%s 年 %s 月", year, month), titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("产品名称", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getSpName(), titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("新增有效用户数", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getNewuser() + "  户", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("续订有效用户数", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getOlduser() + "  户", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("结算用户数", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getTotaluser() + "  户", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("结算费用", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		String convert = "";
		if(data.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).compareTo(BigDecimal.ZERO) < 0){
			//负数金额
			convert = "负数"+ChineseYuanUtil.convert(data.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(-1)).toString());
		}else {
			convert = ChineseYuanUtil.convert(data.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
		}
		//String convert = ChineseYuanUtil.convert(data.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
		cell = new PdfPCell(new Phrase("人民币小写："+data.getMoney() + "  元 \n" +
										"人民币大写：" + convert ,titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("乙方确认意见", titleFont));
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("  ", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase(24,
			"甲方：联通在线信息科技有限公司 \n" +
				"\n" +
				"盖章：\n" +
				"\n" +
				"日期：",
			titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(24,
			"乙方：" + data.getCompany() +" \n" +
				"\n" +
				"盖章：\n" +
				"\n" +
				"日期：",
			titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);
		document.add(table);
		document.close();
	}

	/**
	 * PRM发布类型PDF
	 * @param data
	 * @param baos
	 * @throws Exception
	 */
	private void createPdfPrm(YksytAccountView data, ByteArrayOutputStream baos) throws Exception {
		Document document = new Document();
		PdfWriter.getInstance(document, baos);
		document.open();

		String theMonthStr = data.getThemonth().toString();
		String year = theMonthStr.substring(0, 4), month = theMonthStr.substring(4);

		// 使用语言包字体
		BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		// 外部字体
		ClassPathResource cpr = new ClassPathResource("/fonts/simfang.ttf");
		BaseFont bf = BaseFont.createFont(cpr.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font titleFont = new Font(bf, 12, Font.NORMAL);

		PdfPTable table = new PdfPTable(4);

		PdfPCell cell = new PdfPCell();
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		cell.setColspan(4);
		cell.setPaddingBottom(10f);
		Paragraph paragraph = new Paragraph(String.format("中国联通畅视互娱业务推广合作结算单", month), new Font(abf, 13, Font.BOLD));
		paragraph.setAlignment(Paragraph.ALIGN_CENTER);
		cell.addElement(paragraph);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("渠道名称：" + data.getChannelName(), titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("结算月份（示例2002年9月）", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(String.format("%s 年 %s 月", year, month), titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("结算金额（单位：元人民币 ）", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);

		//String convert = ChineseYuanUtil.convert(data.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
		cell = new PdfPCell(new Phrase(data.getMoney() + " 元" ,titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("业务名称：", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getSpName(), titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("业务负责人：", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("联系电话：", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("财务章：\n\n\n"+
			"\n\n\n\n", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("签字日期：", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("收款人名称（全称）：", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("收款银行（全称）：", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("银行账号：", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

		document.add(table);
		document.close();
	}


	/**
	 * 会员权益类型PDF
	 * @param data
	 * @param baos
	 * @throws Exception
	 */
	private void createPdfHyqy(YksytAccountView data, ByteArrayOutputStream baos) throws Exception {
		List<FinVippoolMonthDetail> list = null;
		if(StringUtils.isNotBlank(data.getChannelName())){
			list = finVippoolMonthDetailService.list(new LambdaQueryWrapper<FinVippoolMonthDetail>()
				.eq(FinVippoolMonthDetail::getChannelid,data.getChannelId())
				.eq(FinVippoolMonthDetail::getThemonth,data.getThemonth())
			);
		}
		Document document = new Document();
		PdfWriter.getInstance(document, baos);
		document.open();

		String theMonthStr = data.getThemonth().toString();
		String year = theMonthStr.substring(0, 4), month = theMonthStr.substring(4);

		// 使用语言包字体
		BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		// 外部字体
		ClassPathResource cpr = new ClassPathResource("/fonts/simfang.ttf");
		BaseFont bf = BaseFont.createFont(cpr.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font titleFont = new Font(bf, 12, Font.NORMAL);

		PdfPTable table = new PdfPTable(8);

		PdfPCell cell = new PdfPCell();
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		cell.setColspan(8);
		cell.setPaddingBottom(10f);
		Paragraph paragraph = new Paragraph(String.format("付款通知书", month), new Font(abf, 13, Font.BOLD));
		paragraph.setAlignment(Paragraph.ALIGN_CENTER);
		cell.addElement(paragraph);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setColspan(8);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("致：联通在线信息科技有限公司：" , titleFont));
		cell.setColspan(8);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("我公司与贵公司签订了", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(String.format("视频会员业务合作协议-%s", data.getCompany()), titleFont));
		cell.setColspan(5);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("结算明细", titleFont));
		cell.setColspan(8);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("权益名称", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("数量", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("单价：元/个", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("总计金额：元", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);

		BigDecimal totalMoney = BigDecimal.ZERO;
		if(list != null && list.size() > 0){
			for (FinVippoolMonthDetail detail : list) {
				totalMoney = totalMoney.add(detail.getMoney()).setScale(2,BigDecimal.ROUND_HALF_UP);
				cell = new PdfPCell(new Phrase(detail.getQyName(), titleFont));
				cell.setColspan(2);
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getNum().toString(), titleFont));
				cell.setColspan(2);
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getCostprice() + "", titleFont));
				cell.setColspan(2);
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getMoney() + "" ,titleFont));
				cell.setColspan(2);
				//cell.setColspan(1);
				cell.setPadding(10f);
				table.addCell(cell);
			}
		}

		cell = new PdfPCell(new Phrase("账期", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(String.format("%s 年 %s 月", year, month), titleFont));
		cell.setColspan(5);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("本次申请付款金额：", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(totalMoney + " 元", titleFont));
		cell.setColspan(5);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("收款单位信息 \n\n\n\n", titleFont));
		cell.setColspan(3);
		cell.setRowspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		String bankName = "";
		String bankCode = "";

		PartnerInformationEnum[] values = PartnerInformationEnum.values();
		for (PartnerInformationEnum value : values) {
			if(value.getPartnerName().equals(data.getCompany())){
				bankName = value.getBankName();
				bankCode = value.getBankCode();
			}
		}

		cell = new PdfPCell(new Phrase("收款单位名称", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getCompany(), titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("开户银行：", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(bankName, titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("银行账号：", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(bankCode, titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("供应商联系人", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("         ", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("供应商联系电话", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("        ", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("其他情况说明：", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("        ", titleFont));
		cell.setColspan(5);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase(24,
			"供应商单位盖章 ： \n" +
				"\n" +"\n" +"\n" +
				"年"+"\t"+"\t"+"\t"+"\t"+"月"+"\t"+"\t"+"\t"+"\t"+"日；",
			titleFont));
		cell.setColspan(8);
		cell.setPaddingRight(20f);
		//cell.setPadding(10f);
		table.addCell(cell);
		document.add(table);
		document.close();
	}

	/**
	 * 出账用户类型PDF
	 * @param data
	 * @param baos
	 * @throws Exception
	 */
	private void createPdfCzyh(YksytAccountView data, ByteArrayOutputStream baos) throws Exception {
		Document document = new Document();
		PdfWriter.getInstance(document, baos);
		document.open();

		String theMonthStr = data.getThemonth().toString();
		String year = theMonthStr.substring(0, 4), month = theMonthStr.substring(4);

		// 使用语言包字体
		BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		// 外部字体
		ClassPathResource cpr = new ClassPathResource("/fonts/simfang.ttf");
		BaseFont bf = BaseFont.createFont(cpr.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font titleFont = new Font(bf, 12, Font.NORMAL);

		PdfPTable table = new PdfPTable(6);

		PdfPCell cell = new PdfPCell();
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		cell.setColspan(6);
		cell.setPaddingBottom(10f);
		Paragraph paragraph = new Paragraph(String.format("《%s月PRM有效用户结算金额确认单》", month), new Font(abf, 13, Font.BOLD));
		paragraph.setAlignment(Paragraph.ALIGN_CENTER);
		cell.addElement(paragraph);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setColspan(6);
		cell.setPadding(10f);
		Paragraph para = new Paragraph(
				String.format("1.甲方为发展其业务，同意按照本协议的约定与乙方在 %s 开展数字媒体合作，按约定结算服务费用。\n", data.getChannelName()) +
				"2.本统计表自双方签署盖章之日起生效。\n" +
				"3.本统计表一式贰份，双方各执壹份。\n" +
				"4.请乙方收到此单据后 3 日予以确认。", titleFont);
		para.setSpacingBefore(10f);
		cell.addElement(para);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("甲方：联通在线信息科技有限公司", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("乙方：" + data.getCompany(), titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("统计周期", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(String.format("%s 年 %s 月", year, month), titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("产品名称", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getSpName(), titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("PRM新增用户数", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getNewuser() + "  户", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("PRM有效用户数", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getOlduser() + "  户", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("结算用户数", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getTotaluser() + "  户", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("结算单价", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getPrice() + " 元",titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("预估结算金额", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getMoneyReckon() + " 元",titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("总扣罚金额", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getMoneyDiscount() + " 元",titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase("结算金额", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(data.getMoney() + " 元",titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase("乙方确认意见", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("  ", titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);


		cell = new PdfPCell(new Phrase(24,
			"甲方：联通在线信息科技有限公司 \n" +
				"\n" +
				"盖章：\n" +
				"\n" +
				"日期：",
			titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(24,
			"乙方：" + data.getCompany() +" \n" +
				"\n" +
				"盖章：\n" +
				"\n" +
				"日期：",
			titleFont));
		cell.setColspan(3);
		cell.setPadding(10f);
		table.addCell(cell);
		document.add(table);
		document.close();
	}

}

