/**
 *
 */
package org.springblade.finance.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 org.springblade.finance.entity.DateRangeAccount;
import org.springblade.finance.entity.IntOdrangeAccountSubView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @author wookvn
 *
 *	导出PDF
 */
@Component
public class PdfExportWXService {

	@Autowired
	private IIntOdrangeAccountSubViewService intOdrangeAccountSubViewService;


	private List<IntOdrangeAccountSubView> getSubList(Long sid){
		return intOdrangeAccountSubViewService.list(new LambdaQueryWrapper<IntOdrangeAccountSubView>()
			.eq(IntOdrangeAccountSubView::getSid, sid)
		);
	}

	/**
	 * 导出第一次结算金额 - PDF文件
	 * @param dateRangeAccount
	 * @return
	 * @throws Exception
	 */
	public void createOnePdf(DateRangeAccount dateRangeAccount, ByteArrayOutputStream baos) throws Exception {
		List<IntOdrangeAccountSubView> subList = getSubList(dateRangeAccount.getSid());
		Document document = new Document();
		PdfWriter.getInstance(document, baos);
		document.open();

		String theMonthStr = dateRangeAccount.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");
//		InputStream stream = cpr.getInputStream();
//		byte[] st1 = new byte[stream.available()];
//		stream.read(st1);
//		BaseFont bf = BaseFont.createFont("simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, BaseFont.NOT_CACHED, st1, st1);
		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%s月预结金额确认单》", year, 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.甲方为推广其产品或服务，同意按照本协议的规定在乙方渠道推广其产品或服务，按合作结算渠道推广费用。\n" +
				"2.本统计表自双方签署盖章之日起生效。\n" +
				"3.本统计表一式贰份，双方各执壹份。\n" +
				"4.请乙方收到此单据后  3  日予以确认。", 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("乙方：" + dateRangeAccount.getCompany(), 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(String.format("%s 年 %s 月", year, month), 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.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("产品名称", titleFont));
		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.setPadding(10f);
		table.addCell(cell);

		if(subList != null && subList.size() > 0){
			for (IntOdrangeAccountSubView detail : subList) {
				cell = new PdfPCell(new Phrase(detail.getChannelname(), titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getSpname(), titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getVuserOndaterange() + "", titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getMoney1Real() + "" ,titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				/*cell = new PdfPCell(new Phrase(detail.getMoney1() + "" ,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("总金额", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(dateRangeAccount.getMoneyOne().setScale(2,BigDecimal.ROUND_HALF_UP)+"", 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(dateRangeAccount.getMoneyOneDiscountTotal().setScale(2,BigDecimal.ROUND_HALF_UP)+"", 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(dateRangeAccount.getMoneyOneReal().setScale(2,BigDecimal.ROUND_HALF_UP)+"", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);


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


		// 配置行间距
		cell.addElement(new Paragraph(24,
				"乙方： \n" +
				"\n" +
				"盖章：\n" +
				"\n" +
				"日期：",
				titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);
		document.add(table);
		document.close();
	}

	/**
	 * 导出第二次结算金额 - PDF文件
	 * @param dateRangeAccount
	 * @return
	 */
	public void createTwoPdf(DateRangeAccount dateRangeAccount, ByteArrayOutputStream baos) throws Exception {
		List<IntOdrangeAccountSubView> subList = getSubList(dateRangeAccount.getSid());
		Document document = new Document();
		PdfWriter.getInstance(document, baos);
		document.open();

		String theMonthStr = dateRangeAccount.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%s月清算金额确认单》", year, 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.甲方为推广其产品或服务，同意按照本协议的规定在乙方渠道推广其产品或服务，按合作结算渠道推广费用。\n" +
				"2.本统计表自双方签署盖章之日起生效。\n" +
				"3.本统计表一式贰份，双方各执壹份。\n" +
				"4.请乙方收到此单据后  3  日予以确认。", 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("乙方：" + dateRangeAccount.getCompany(), 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(String.format("%s 年 %s 月", year, month), 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.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase("产品名称", titleFont));
		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.setPadding(10f);
		table.addCell(cell);

		if(subList != null && subList.size() > 0){
			for (IntOdrangeAccountSubView detail : subList) {
				cell = new PdfPCell(new Phrase(detail.getChannelname(), titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getSpname(), titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getVuserOndaterange() + "", titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				cell = new PdfPCell(new Phrase(detail.getMoney2Real() + "" ,titleFont));
				cell.setPadding(10f);
				table.addCell(cell);
				/*cell = new PdfPCell(new Phrase(detail.getMoney2() + "" ,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("总金额", titleFont));
		cell.setColspan(2);
		cell.setPadding(10f);
		table.addCell(cell);
		cell = new PdfPCell(new Phrase(dateRangeAccount.getMoneyTwo().setScale(2,BigDecimal.ROUND_HALF_UP)+"", 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(dateRangeAccount.getMoneyTwoDiscount().setScale(2,BigDecimal.ROUND_HALF_UP)+"", 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(dateRangeAccount.getMoneyTwoReal().setScale(2,BigDecimal.ROUND_HALF_UP)+"", titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);

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


		// 配置行间距
		cell.addElement(new Paragraph(24,
				"乙方： \n" +
				"\n" +
				"盖章：\n" +
				"\n" +
				"日期：",
				titleFont));
		cell.setColspan(4);
		cell.setPadding(10f);
		table.addCell(cell);
		document.add(table);
		document.close();
	}

	/**
	 *
	 * @param list
	 * @param baos
	 * @throws Exception
	 * ByteArrayOutputStream
	 */
	public void createReadyPdf(List<DateRangeAccount> list, ByteArrayOutputStream baos) throws Exception {
		Document document = new Document();
		Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
        pageSize.rotate();
        document.setPageSize(pageSize);
		PdfWriter.getInstance(document, baos);
		document.open();

		// 使用语言包字体
		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);

		//设置没列的宽度
		float[] widths = new float[] {20f, 60f, 70f, 35f, 40f, 50f, 50f, 40f, 45f, 45f, 39f, 50f, 39f};
		PdfPTable table = new PdfPTable(13);
		double totalWidth = IntStream.range(0, widths.length).mapToDouble(i -> Double.valueOf(widths[i])).sum();
		table.setTotalWidth(Double.valueOf(totalWidth).floatValue() + 200f); // + 250f
		table.setLockedWidth(true);
		table.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.setWidths(widths);

		PdfPCell cell = new PdfPCell();
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		cell.setColspan(13);
		cell.setPaddingBottom(10f);
		cell.setBorder(0);
		Paragraph paragraph = new Paragraph("畅视事业部   渠道结算明细表", new Font(abf, 13, Font.BOLD));
		paragraph.setAlignment(Paragraph.ALIGN_CENTER);
		cell.addElement(paragraph);
		table.addCell(cell);

		String[] tableFieldList = new String[] {"序号", "合作伙伴名称", "结算类型（T+1预结/T+5清算）", "账期", "产品名称", "预结有效用户数",
				"PRM有效用户数", "400扣款金额", "客服退赔付费", "省份违约扣款", "调账金额", "不规范定制处罚费", "结算金额"};

		for(String tableField : tableFieldList) {
			cell = new PdfPCell(new Phrase(tableField, titleFont));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}

		for(int i = 0; i < list.size(); i++) {
			DateRangeAccount data = list.get(i);
			cell = new PdfPCell(new Phrase(String.valueOf(i+1), titleFont));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getCompany(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getReadyTypeStr(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getTheMonth().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getSpname(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getOnDateRange().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getAccountUsers().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getMoneyOneDiscount().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getMoneyTwoDiscount1().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getMoneyTwoDiscount2().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getMoneyTwoDiscount3().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase(data.getMoneyTwoDiscount4().toString(), titleFont));
			table.addCell(cell);

			cell = new PdfPCell(new Phrase("T+1预结".equals(data.getReadyTypeStr()) ? data.getMoneyOneReal().toString() : data.getMoneyTwoReal().toString(), titleFont));
			table.addCell(cell);
		}

		//统计总数
		cell = new PdfPCell(new Phrase("总计：", titleFont));
		cell.setColspan(5);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(list.stream().map(DateRangeAccount::getOnDateRange).reduce(BigDecimal.ZERO, BigDecimal::add).toString(), titleFont));
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(list.stream().map(DateRangeAccount::getAccountUsers).reduce(BigDecimal.ZERO, BigDecimal::add).toString(), titleFont));
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(list.stream().map(DateRangeAccount::getMoneyOneDiscount).reduce(BigDecimal.ZERO, BigDecimal::add).toString(), titleFont));
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(list.stream().map(DateRangeAccount::getMoneyTwoDiscount1).reduce(BigDecimal.ZERO, BigDecimal::add).toString(), titleFont));
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(list.stream().map(DateRangeAccount::getMoneyTwoDiscount2).reduce(BigDecimal.ZERO, BigDecimal::add).toString(), titleFont));
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(list.stream().map(DateRangeAccount::getMoneyTwoDiscount3).reduce(BigDecimal.ZERO, BigDecimal::add).toString(), titleFont));
		table.addCell(cell);

		cell = new PdfPCell(new Phrase(list.stream().map(DateRangeAccount::getMoneyTwoDiscount4).reduce(BigDecimal.ZERO, BigDecimal::add).toString(), titleFont));
		table.addCell(cell);

		BigDecimal totalRealMoney = list.stream().map(f -> {
			if("T+1预结".equals(f.getReadyTypeStr())) {
				return f.getMoneyOneReal();
			}else {
				return f.getMoneyTwoReal();
			}
		}).reduce(BigDecimal.ZERO, BigDecimal::add);
		cell = new PdfPCell(new Phrase(totalRealMoney.toString(), titleFont));
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("经办人确认：", titleFont));
		cell.setColspan(13);
		cell.setBorder(0);
		cell.setPaddingTop(50);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("业务组确认：", titleFont));
		cell.setColspan(13);
		cell.setBorder(0);
		cell.setPaddingTop(15);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("数字化运营中心确认：", titleFont));
		cell.setColspan(13);
		cell.setBorder(0);
		cell.setPaddingTop(15);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("质量管控中心确认：", titleFont));
		cell.setColspan(13);
		cell.setBorder(0);
		cell.setPaddingTop(15);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("财务支撑中心确认：", titleFont));
		cell.setColspan(13);
		cell.setBorder(0);
		cell.setPaddingTop(15);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("部门负责人确认：", titleFont));
		cell.setColspan(13);
		cell.setBorder(0);
		cell.setPaddingTop(15);
		table.addCell(cell);

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



}
