/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.warehouse.ledger.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import com.jeeplus.common.utils.DateUtil;
import com.jeeplus.modules.warehouse.ledger.Utils.ExcelStyleUtils;
import com.jeeplus.modules.warehouse.ledger.dto.CountLedgerInfo;
import com.jeeplus.modules.warehouse.materialtype.entity.MaterialType;
import com.jeeplus.modules.warehouse.materialtype.mapper.MaterialTypeMapper;
import com.jeeplus.modules.warehouse.materialtype.service.MaterialTypeService;
import com.jeeplus.modules.warehouse.outbound.entity.OutboundInfo;
import com.jeeplus.modules.warehouse.outbound.mapper.OutboundInfoMapper;
import com.jeeplus.modules.warehouse.qrcode.entity.QrCode;
import com.jeeplus.modules.warehouse.qrcode.mapper.QrCodeMapper;
import com.jeeplus.modules.warehouse.shelves.entity.Shelves;
import com.jeeplus.modules.warehouse.shelves.utils.ShelvesUtil;
import com.jeeplus.modules.warehouse.storage.dto.CountStorageInfo;
import com.jeeplus.modules.warehouse.storage.entity.StorageInfo;
import com.jeeplus.modules.warehouse.storage.mapper.StorageInfoMapper;
import com.jeeplus.modules.warehouse.storage.mapper.StorageMapper;
import com.jeeplus.modules.warehouse.storage.service.StorageService;
import com.jeeplus.modules.warehouse.warehouse.entity.Warehouse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.warehouse.ledger.entity.Ledger;
import com.jeeplus.modules.warehouse.ledger.mapper.LedgerMapper;
import com.jeeplus.modules.warehouse.ledger.entity.LedgerInfo;
import com.jeeplus.modules.warehouse.ledger.mapper.LedgerInfoMapper;

import javax.servlet.http.HttpServletResponse;

/**
 * 台账信息Service
 * @author huyi
 * @version 2023-02-13
 */
@Service
@Transactional(readOnly = true)
public class LedgerService extends CrudService<LedgerMapper, Ledger> {

	@Autowired
	private LedgerInfoMapper ledgerInfoMapper;
	@Autowired
	private QrCodeMapper qrCodeMapper;
	@Autowired
	private MaterialTypeMapper materialTypeMapper;
	@Autowired
	private StorageInfoMapper storageInfoMapper;
	@Autowired
	private OutboundInfoMapper outboundInfoMapper;



	
	public Ledger get(String id) {
		Ledger ledger = super.get(id);
		List<LedgerInfo> ledgerInfoList = ledgerInfoMapper.findList(new LedgerInfo(ledger));
		ledger.setLedgerInfoList(ledgerInfoList);
		for (LedgerInfo li : ledgerInfoList) {
			List<Shelves> shelvesList = ShelvesUtil.getShelvesListByIds(li.getShelvesIds());
			li.setShelvesList(shelvesList);
			List<Warehouse> warehouseList = ShelvesUtil.getWarehouseListByIds(li.getWarehouseIds());
			li.setWarehouseList(warehouseList);
		}
		return ledger;
	}

	
	public List<Ledger> findList(Ledger ledger) {
		return super.findList(ledger);
	}
	
	public Page<Ledger> findPage(Page<Ledger> page, Ledger ledger) {
		return super.findPage(page, ledger);
	}

	public Page<LedgerInfo> findInfoPage(Page<LedgerInfo> page, LedgerInfo ledgerInfo) {
		dataRuleFilter(ledgerInfo);
		ledgerInfo.setPage(page);
		page.setList(ledgerInfoMapper.findList(ledgerInfo));
		return page;
	}

	@Transactional(readOnly = false)
	public void save(Ledger ledger) {
		Ledger oldLeger = mapper.findByTypeAndModel(ledger);
		// 判断是否存在同名称、同类型、同型号的台账，如果不存在，做新增操作，如果存在，则做修改操作
		if (null == oldLeger || StringUtils.isBlank(oldLeger.getId())) {
			super.save(ledger);
		} else {
			int num = ledger.getNum();
			BigDecimal sum = ledger.getSum();

			oldLeger.setNum(oldLeger.getNum() + num);
			oldLeger.setSum(oldLeger.getSum().add(sum));
			List<LedgerInfo> oldLedgerInfos = oldLeger.getLedgerInfoList();
			if (null != oldLedgerInfos) {
				List<LedgerInfo> newLedgerInfos = new ArrayList<>();
				newLedgerInfos.addAll(oldLedgerInfos);
				newLedgerInfos.addAll(ledger.getLedgerInfoList());
				oldLeger.setLedgerInfoList(newLedgerInfos);
			}

			oldLeger.preUpdate();
			mapper.update(oldLeger);
			ledger = oldLeger;
		}
		for (LedgerInfo ledgerInfo : ledger.getLedgerInfoList()){
			if (ledgerInfo.getId() == null){
				continue;
			}
			if (LedgerInfo.DEL_FLAG_NORMAL.equals(ledgerInfo.getDelFlag())){
				if (StringUtils.isBlank(ledgerInfo.getId())){
					QrCode qrCode = ledgerInfo.getQr();
					QrCode qc = qrCodeMapper.get(qrCode);
					qc.setState("2");
					qrCodeMapper.update(qc);
					ledgerInfo.setLedger(ledger);
					ledgerInfo.preInsert();
					ledgerInfoMapper.insert(ledgerInfo);
				}else{
					ledgerInfo.preUpdate();
					ledgerInfoMapper.update(ledgerInfo);
				}
			}else{
				ledgerInfoMapper.delete(ledgerInfo);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Ledger ledger) {
		super.delete(ledger);
		ledgerInfoMapper.delete(new LedgerInfo(ledger));
	}
	/*
	* 张吕涛
	* 领用后下账,更新台账货架信息
	* */
	@Transactional(readOnly = false)
	public void lowerLedger(Ledger ledger) {
		/*List<String> shelvesListByLedgerId = mapper.findShelvesListByLedgerId(ledger.getId());
		if(shelvesListByLedgerId == null || shelvesListByLedgerId.size() == 0){
			ledger.setShelvesIds(null);
		}else {
			String shelvesIds = String.join(",", shelvesListByLedgerId);
			ledger.setShelvesIds(shelvesIds);
		}*/
		mapper.update(ledger);
	}
	@Transactional(readOnly = false)
	public LedgerInfo findByQrOrCode(LedgerInfo ledgerInfo) {
		List<LedgerInfo> ledgerInfoList = ledgerInfoMapper.findListByQrIdAndCode(ledgerInfo);
		if (null != ledgerInfoList && ledgerInfoList.size() > 0) {
			return ledgerInfoList.get(0);
		} else {
			return null;
		}
	}


	public void ledgerStreamWater(String typeId, String beginTime, String endTime, HttpServletResponse respons) {
		typeId = "4657ffc36fcf4feb922eb571231234b0";
		beginTime = "2023-01-01 00:00:00";
		endTime = "2023-12-01 00:00:00";
		Date bTime = DateUtil.parseStrToDate(beginTime, "yyyy-MM-dd HH:mm:ss");
		Date eTime = DateUtil.parseStrToDate(endTime, "yyyy-MM-dd HH:mm:ss");

		MaterialType materialType = materialTypeMapper.get(typeId);
		StorageInfo temSi = new StorageInfo();
		temSi.setType(materialType);
		temSi.setBeginTime(bTime);
		temSi.setEndTime(eTime);
		List<StorageInfo> storageInfoList = storageInfoMapper.findList(temSi);



		LedgerInfo temLi = new LedgerInfo();
		temLi.setType(materialType);

		OutboundInfo outboundInfo = new OutboundInfo();
		outboundInfo.setLedgerInfo(temLi);
		outboundInfo.setBeginTime(bTime);
		outboundInfo.setEndTime(eTime);
		List<OutboundInfo> outboundInfoList = outboundInfoMapper.findList(outboundInfo);

		int sunRowNum = 5 + storageInfoList.size() + outboundInfoList.size();
		// 创建工作薄
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 创建工作表
		XSSFSheet sheet = workbook.createSheet("被装物资库房帐");

		CellStyle oneStyle = ExcelStyleUtils.topOneCellStyle(workbook);
		CellStyle twoStyle = ExcelStyleUtils.topTwoCellStyle(workbook);
		CellStyle threeStyle = ExcelStyleUtils.topThreeCellStyle(workbook);



		//设置数据
		for (int row = 0; row < sunRowNum; row++) {
			XSSFRow sheetRow = sheet.createRow(row);
			if (0 == row) {
				sheetRow.setHeightInPoints(30);
				for (int i = 0; i < 22; i ++) {
					if (0 == i) {
						XSSFCell cell = sheetRow.createCell(i);
						cell.setCellValue("被  装  物  资  库  房  帐");
						cell.setCellStyle(oneStyle);
					} else {
						XSSFCell cell = sheetRow.createCell(i);
						cell.setCellStyle(oneStyle);
					}
				}
			}
			if (1 == row) {
				sheetRow.setHeightInPoints(20);
				for (int i = 0; i < 22; i ++) {
					if (0 == i) {
						XSSFCell cell = sheetRow.createCell(i);
						cell.setCellValue("品名代码：" + materialType.getCode());
						cell.setCellStyle(twoStyle);
					} else if (4 == i) {
						XSSFCell cell1 = sheetRow.createCell(i);
						cell1.setCellValue("品名：" + materialType.getName());
						cell1.setCellStyle(twoStyle);
					} else if (12 == i) {
						XSSFCell cell2 = sheetRow.createCell(i);
						cell2.setCellValue("计量单位：" + materialType.getUnit());
						cell2.setCellStyle(twoStyle);
					} else {
						XSSFCell cell2 = sheetRow.createCell(i);
						cell2.setCellStyle(twoStyle);
					}
				}

			}
			if (2 == row) {
				sheetRow.setHeightInPoints(15);
				for (int i = 0; i < 22; i ++) {
					if (0 == i) {
						XSSFCell cell = sheetRow.createCell(i);
						cell.setCellValue(DateUtil.getYear(eTime) + " 年");
						cell.setCellStyle(threeStyle);

					} else if (2 == i) {
						XSSFCell cell1 = sheetRow.createCell(i);
						cell1.setCellValue("凭证批号");
						cell1.setCellStyle(threeStyle);
					} else if (3 == i) {
						XSSFCell cell2 = sheetRow.createCell(i);
						cell2.setCellValue("摘要");
						cell2.setCellStyle(threeStyle);
					} else if (4 == i) {
						XSSFCell cell3 = sheetRow.createCell(i);
						cell3.setCellValue("收入");
						cell3.setCellStyle(threeStyle);
					} else if (5 == i) {
						XSSFCell cell4 = sheetRow.createCell(i);
						cell4.setCellValue("支出");
						cell4.setCellStyle(threeStyle);
					} else if (6 == i) {
						XSSFCell cell5 = sheetRow.createCell(i);
						cell5.setCellValue("结存");
						cell5.setCellStyle(threeStyle);
					} else if (21 == i) {
						XSSFCell cell6 = sheetRow.createCell(i);
						cell6.setCellValue("摘要");
						cell6.setCellStyle(threeStyle);
					} else {
						XSSFCell cell6 = sheetRow.createCell(i);
						cell6.setCellStyle(threeStyle);
					}
				}
			}
			if (3 == row) {
				sheetRow.setHeightInPoints(15);
				for (int i = 0; i < 22; i ++) {
					if (0 == i) {
						XSSFCell cell = sheetRow.createCell(i);
						cell.setCellValue("月");
						cell.setCellStyle(ExcelStyleUtils.topThreeCellStyle(workbook));
					} else if (1 == i) {
						XSSFCell cell1 = sheetRow.createCell(i);
						cell1.setCellValue("日");
						cell1.setCellStyle(ExcelStyleUtils.topThreeCellStyle(workbook));
					} else if (6 == i) {
						XSSFCell cell2 = sheetRow.createCell(i);
						cell2.setCellValue("数量");
						cell2.setCellStyle(ExcelStyleUtils.topThreeCellStyle(workbook));
					} else if (7 == i) {
						XSSFCell cell3 = sheetRow.createCell(i);
						cell3.setCellValue("号型");
						cell3.setCellStyle(ExcelStyleUtils.topThreeCellStyle(workbook));
					} else {
						XSSFCell cell3 = sheetRow.createCell(i);
						cell3.setCellStyle(ExcelStyleUtils.topThreeCellStyle(workbook));
					}
				}



			}
			// 设置列宽  sheet.setColumnWidth(0, 16 * 256); 第一个参数为第几个单元格，第二个为16个字符宽度
		}
		sheet.addMergedRegion(new CellRangeAddress(0,0,0,21));
		sheet.addMergedRegion(new CellRangeAddress(1,1,0,3));
		sheet.addMergedRegion(new CellRangeAddress(1,1,4,11));
		sheet.addMergedRegion(new CellRangeAddress(1,1,12,21));

		sheet.addMergedRegion(new CellRangeAddress(2,3,0,1));
		sheet.addMergedRegion(new CellRangeAddress(2,4,2,2));
		sheet.addMergedRegion(new CellRangeAddress(2,4,3,3));
		sheet.addMergedRegion(new CellRangeAddress(2,4,4,4));
		sheet.addMergedRegion(new CellRangeAddress(2,4,5,5));
		sheet.addMergedRegion(new CellRangeAddress(2,2,6,20));
		sheet.addMergedRegion(new CellRangeAddress(2,4,21,21));

		sheet.addMergedRegion(new CellRangeAddress(3,4,6,6));
		sheet.addMergedRegion(new CellRangeAddress(3,3,7,20));
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(new File("D:/excel.xlsx"));
			workbook.write(out);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != out) {
					out.flush();
					out.close();
				}
				workbook.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}