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

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.io.FileUtil;
import com.jeeplus.modules.warehouse.code.util.CodeUtil;
import com.jeeplus.modules.warehouse.code.util.StaticNumSeq;
import com.jeeplus.modules.warehouse.goods.entity.GoodsInfo;
import com.jeeplus.modules.warehouse.ledger.entity.Ledger;
import com.jeeplus.modules.warehouse.ledger.entity.LedgerInfo;
import com.jeeplus.modules.warehouse.ledger.mapper.LedgerInfoMapper;
import com.jeeplus.modules.warehouse.ledger.mapper.LedgerMapper;
import com.jeeplus.modules.warehouse.ledger.service.LedgerService;
import com.jeeplus.modules.warehouse.qrcode.entity.QrCode;
import com.jeeplus.modules.warehouse.qrcode.mapper.QrCodeMapper;
import com.jeeplus.modules.warehouse.qrcode.service.QrCodeService;
import com.jeeplus.modules.warehouse.qrcode.util.BuildQcUtil;
import com.jeeplus.modules.warehouse.wzcode.entity.Wzcode;
import com.jeeplus.modules.warehouse.wzcode.service.WzcodeService;
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.profitwarehousing.entity.ProfitWarehousing;
import com.jeeplus.modules.warehouse.profitwarehousing.mapper.ProfitWarehousingMapper;
import com.jeeplus.modules.warehouse.profitwarehousing.entity.ProfitWarehousingInfo;
import com.jeeplus.modules.warehouse.profitwarehousing.mapper.ProfitWarehousingInfoMapper;

/**
 * 盘盈入库单Service
 * @author zhanglt
 * @version 2023-02-14
 */
@Service
@Transactional(readOnly = true)
public class ProfitWarehousingService extends CrudService<ProfitWarehousingMapper, ProfitWarehousing> {

	@Autowired
	private ProfitWarehousingInfoMapper profitWarehousingInfoMapper;
	@Autowired
	private LedgerMapper ledgerMapper;
	@Autowired
	private QrCodeMapper qrCodeMapper;
	@Autowired
	private LedgerInfoMapper ledgerInfoMapper;
	@Autowired
	private LedgerService ledgerService;
	@Autowired
	private QrCodeService qrCodeService;
	@Autowired
	private WzcodeService wzcodeService;

	public ProfitWarehousing get(String id) {
		ProfitWarehousing profitWarehousing = super.get(id);
		profitWarehousing.setProfitWarehousingInfoList(profitWarehousingInfoMapper.findList(new ProfitWarehousingInfo(profitWarehousing)));
		return profitWarehousing;
	}
	
	public List<ProfitWarehousing> findList(ProfitWarehousing profitWarehousing) {
		return super.findList(profitWarehousing);
	}
	
	public Page<ProfitWarehousing> findPage(Page<ProfitWarehousing> page, ProfitWarehousing profitWarehousing) {
		return super.findPage(page, profitWarehousing);
	}
	@Transactional(readOnly = false)
	public String createPYDH() {
		String pydh = CodeUtil.code("PYDH", StaticNumSeq.PYDH);
		return pydh;
	}
	/**
	 * 生成单个，盘盈入库二维码
	 */
	@Transactional(readOnly = false)
	public ProfitWarehousingInfo printQr(String infoId) {
		String qrImgPath = Global.getAttachmentDir() + "image";
		File file = new File(qrImgPath);
		if  (!file .exists()  && !file .isDirectory()) {
			System.out.println("//不存在");
			file .mkdirs();
		}
		ProfitWarehousingInfo profitWarehousingInfo = profitWarehousingInfoMapper.get(infoId);
//		String numSeq = CodeUtil.code("WZBM", StaticNumSeq.WZBM);
		Wzcode wzcode = wzcodeService.findByCode(profitWarehousingInfo.getType().getCode());
		int intNum = wzcode.getIntNum();
		intNum = intNum+1;
		wzcode.setIntNum(intNum);
		QrCode qrCode = new QrCode();
		qrCode.setProfitWarehousingInfo(profitWarehousingInfo);
		qrCode.setComeFlag("1");
		qrCode.setCode(wzcode.getCodeAndNum());
		qrCode.setState("0");
		qrCode.preInsert();
		try {
			BuildQcUtil.buildQrOne(qrCode, qrImgPath + "/" + wzcode.getCodeAndNum() + ".png", qrImgPath + "/" + wzcode.getCodeAndNum() + "_0"+ ".png"); // 生成图片
		} catch (IOException e) {
			e.printStackTrace();
		}
		qrCode.setUrl(Global.getAttachmentUrl() + "image/" + wzcode.getCodeAndNum() + "_0" + ".png");
		qrCodeMapper.insert(qrCode);
		qrCode = qrCodeMapper.get(qrCode.getId());
		profitWarehousingInfo.setQrCode(qrCode);
		profitWarehousingInfo.preUpdate();
		profitWarehousingInfoMapper.update(profitWarehousingInfo);
		// 更新物资编码表
		wzcodeService.save(wzcode);
		return profitWarehousingInfo;
	}
	/**
	 * 清除二维码
	 * @param infoId
	 */
	@Transactional(readOnly = false)
	public void cleanQr(String infoId) {
		ProfitWarehousingInfo profitWarehousingInfo = profitWarehousingInfoMapper.get(infoId);
		QrCode qrCode = qrCodeMapper.get(profitWarehousingInfo.getQrCode().getId());
		if (StringUtils.isNotBlank(qrCode.getUrl())) {
				try {
					String url = qrCode.getUrl();
					if (null != url && url.contains("image")) {
						String photo = url.split("image/")[1];
						File file = new File(Global.getAttachmentDir() + "image/" + photo);
						if (file.exists()) {
							FileUtil.deleteFile(new File(Global.getAttachmentDir() + "image/" + photo));
						} else {
							logger.info("二维码路径不存在，执行删除");
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		qrCodeMapper.delete(qrCode); // 删除二维码
		profitWarehousingInfo.setQrCode(new QrCode());
		profitWarehousingInfo.preUpdate();
		profitWarehousingInfoMapper.update(profitWarehousingInfo);

	}

	@Transactional(readOnly = false)
	public void save(ProfitWarehousing profitWarehousing) {
		super.save(profitWarehousing);
		for (ProfitWarehousingInfo profitWarehousingInfo : profitWarehousing.getProfitWarehousingInfoList()){
			profitWarehousingInfo.setProfitWarehousing(profitWarehousing);
			if (profitWarehousingInfo.getId() == null){
				continue;
			}
			if (ProfitWarehousingInfo.DEL_FLAG_NORMAL.equals(profitWarehousingInfo.getDelFlag())){
				if (StringUtils.isBlank(profitWarehousingInfo.getId())){
					profitWarehousingInfo.preInsert();
					profitWarehousingInfoMapper.insert(profitWarehousingInfo);
				}else{
					profitWarehousingInfo.preUpdate();
					profitWarehousingInfoMapper.update(profitWarehousingInfo);
				}
			}else{
				profitWarehousingInfoMapper.delete(profitWarehousingInfo);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(ProfitWarehousing profitWarehousing) {
		super.delete(profitWarehousing);
		profitWarehousingInfoMapper.delete(new ProfitWarehousingInfo(profitWarehousing));
	}
	//盘盈入库 保存 盘盈入库信息 ，并添加对应的台账信息
	@Transactional(readOnly = false)
	public void inLedgerInfo(ProfitWarehousingInfo profitWarehousingInfo) {
		QrCode qrCode = qrCodeService.get(profitWarehousingInfo.getQrCode().getId());
		Ledger ledger = new Ledger(profitWarehousingInfo.getName(),profitWarehousingInfo.getType(),profitWarehousingInfo.getMarking());
		Ledger oldLeger = ledgerMapper.findByTypeAndModel(ledger);
		LedgerInfo ledgerInfo = new LedgerInfo();
		//名称
		ledgerInfo.setName(ledger.getName());
		//类型
		ledgerInfo.setType(ledger.getType());
		//型号
		ledgerInfo.setModel(ledger.getModel());
		//物资编码
		ledgerInfo.setCode(qrCode.getCode());
		//二维码id
		ledgerInfo.setQr(qrCode);
		//货架id
		ledgerInfo.setShelves(profitWarehousingInfo.getShelves());
		//盘盈入库单编码
		ledgerInfo.setBatchNum(profitWarehousingInfo.getProfitWarehousing().getNumber());
		//单价
		ledgerInfo.setAmount(profitWarehousingInfo.getAmount());
		//查询 台账中是否有 该类型的物资
		if(oldLeger != null){
			//有台账 直接在该物资下加入一条明细，并更新台账
			//台账主表id
			ledgerInfo.setLedger(oldLeger);
			BigDecimal sum = oldLeger.getSum();
			sum = sum.add(profitWarehousingInfo.getAmount());
			oldLeger.setSum(sum);
			oldLeger.setNum(oldLeger.getNum()+1);
			List<String> shelvesList = ledgerMapper.findShelvesListByLedgerId(oldLeger.getId());
			if(!shelvesList.contains(ledgerInfo.getShelves().getId())){
				shelvesList.add(ledgerInfo.getShelves().getId());
			}
			String shelvesIds = String.join(",", shelvesList);
			oldLeger.setShelvesIds(shelvesIds);

			oldLeger.preUpdate();
			ledgerMapper.update(oldLeger);

			ledgerInfo.preInsert();
			ledgerInfoMapper.insert(ledgerInfo);
		}else {
			ledger.setShelvesIds(ledgerInfo.getShelves().getId());
			ledger.setNum(1);
			ledger.setSum(ledgerInfo.getAmount());

			ledger.preInsert();
			ledgerMapper.insert(ledger);

			ledgerInfo.setLedger(ledger);

			ledgerInfo.preInsert();
			ledgerInfoMapper.insert(ledgerInfo);
		}
		//设置二维码状态为 入库并入帐
		qrCode.setState("2");
		qrCodeService.save(qrCode);
	}
}