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

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
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.qrcode.entity.QrCode;
import com.jeeplus.modules.warehouse.qrcode.mapper.QrCodeMapper;
import com.jeeplus.modules.warehouse.qrcode.util.BuildQcUtil;
import com.jeeplus.modules.warehouse.qrcode.util.DrawQrcodeUtil;
import com.jeeplus.modules.warehouse.qrcode.util.TwoDimensionCode;
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.goods.entity.Goods;
import com.jeeplus.modules.warehouse.goods.mapper.GoodsMapper;
import com.jeeplus.modules.warehouse.goods.entity.GoodsInfo;
import com.jeeplus.modules.warehouse.goods.mapper.GoodsInfoMapper;

/**
 * 货品模块Service
 * @author huyi
 * @version 2023-02-13
 */
@Service
@Transactional(readOnly = true)
public class GoodsService extends CrudService<GoodsMapper, Goods> {

	@Autowired
	private GoodsInfoMapper goodsInfoMapper;
	@Autowired
	private QrCodeMapper qrCodeMapper;
	
	public Goods get(String id) {
		Goods goods = super.get(id);
		goods.setGoodsInfoList(goodsInfoMapper.findList(new GoodsInfo(goods)));
		return goods;
	}
	
	public List<Goods> findList(Goods goods) {
		return super.findList(goods);
	}
	
	public Page<Goods> findPage(Page<Goods> page, Goods goods) {
		return super.findPage(page, goods);
	}
	
	@Transactional(readOnly = false)
	public void save(Goods goods) {
		super.save(goods);
		for (GoodsInfo goodsInfo : goods.getGoodsInfoList()){
			if (goodsInfo.getId() == null){
				continue;
			}
			if (GoodsInfo.DEL_FLAG_NORMAL.equals(goodsInfo.getDelFlag())){
				if (StringUtils.isBlank(goodsInfo.getId())){
					goodsInfo.setGoods(goods);
					goodsInfo.preInsert();
					goodsInfoMapper.insert(goodsInfo);
				}else{
					goodsInfo.preUpdate();
					goodsInfoMapper.update(goodsInfo);
				}
			}else{
				goodsInfoMapper.delete(goodsInfo);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Goods goods) {
		super.delete(goods);
		goodsInfoMapper.delete(new GoodsInfo(goods));
	}

	/**
	 * 生成二维码
	 */
	@Transactional(readOnly = false)
	public GoodsInfo printQr(String infoId) {
        String qrImgPath = Global.getAttachmentDir() + "image";
        File file = new File(qrImgPath);
        if  (!file .exists()  && !file .isDirectory()) {
            System.out.println("//不存在");
            file .mkdirs();
        }

		GoodsInfo goodsInfo = goodsInfoMapper.get(infoId);
        QrCode temQr = new QrCode();
        GoodsInfo temGi = new GoodsInfo();
		temGi.setId(infoId);
		temQr.setGoodsInfo(temGi);
		List<QrCode> qrCodeList = qrCodeMapper.findByGoodsInfoId(temQr);
		if (null != qrCodeList && qrCodeList.size() > 0) { // 二维码已经生成过
			goodsInfo.setQrCodeList(qrCodeList);
			return goodsInfo;
		} else {
			qrCodeList = new ArrayList<>();
			int num = goodsInfo.getNum();
			String beginNumSeq = "";
			String endNumSeq = "";
			for (int i = 0; i < num; i++) {
				String numSeq = CodeUtil.code("WZBM", StaticNumSeq.WZBM);
				if (0 == i) {
					beginNumSeq = numSeq;
				}
				if ((num - 1) == i) {
					endNumSeq = numSeq;
				}
				QrCode qrCode = new QrCode();
				qrCode.setCode(numSeq);
				qrCode.setGoodsInfo(goodsInfo);
				qrCode.setState("0");

				qrCode.preInsert();
				try {
					BuildQcUtil.buildQr(qrCode, qrImgPath + "/" + numSeq + ".png", qrImgPath + "/" + numSeq + "_" + i + ".png"); // 生成图片
				} catch (IOException e) {
					e.printStackTrace();
				}
				qrCode.setUrl(Global.getAttachmentUrl() + "image/" + numSeq + "_" + i + ".png");

				qrCodeMapper.insert(qrCode);
				qrCode = qrCodeMapper.get(qrCode.getId());
				qrCodeList.add(qrCode);
			}

			String qrInterval = "";
			if (beginNumSeq.equals(endNumSeq)) {
				qrInterval = beginNumSeq;
			} else {
				qrInterval = beginNumSeq + "_" + endNumSeq.substring(13,17);
			}
			goodsInfo.setQrInterval(qrInterval); // 设置编码区间
			// goodsInfo.preUpdate();
			goodsInfoMapper.update(goodsInfo);
			goodsInfo.setQrCodeList(qrCodeList);
			return goodsInfo;
		}
	}

	/**
	 * 清除二维码
	 * @param infoId
	 */
	@Transactional(readOnly = false)
	public void cleanQr(String infoId) {
		GoodsInfo goodsInfo = goodsInfoMapper.get(infoId);
		QrCode temQr = new QrCode();
		GoodsInfo temGi = new GoodsInfo();
		temGi.setId(infoId);
		temQr.setGoodsInfo(temGi);
		List<QrCode> qrCodeList = qrCodeMapper.findByGoodsInfoId(temQr);
		if (null != qrCodeList && qrCodeList.size() > 0) {
            for (QrCode qrCode : qrCodeList) {
                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.deleteByGoodInfoId(infoId); // 删除二维码
            goodsInfo.setQrInterval("");
            goodsInfo.preUpdate();
            goodsInfoMapper.update(goodsInfo);
        }
	}

	/**
	 * 通过goods信息查询goodsInfo信息(批次号)
	 * @param goods
	 * @return
	 */
	@Transactional(readOnly = false)
	public Goods findGoodsInfoByGoods(Goods goods) {
		goods = mapper.findByPc(goods);
		GoodsInfo temGI = new GoodsInfo();
		temGI.setGoods(goods);
		List<GoodsInfo> goodsInfoList = goodsInfoMapper.findList(temGI);
		goods = mapper.findByPc(goods);
		goods.setGoodsInfoList(goodsInfoList);
		return goods;
	}

	public QrCode getGIAndQCByTwoId(String goodsInfoId, String qrCodeId) {
		GoodsInfo goodsInfo = goodsInfoMapper.get(new GoodsInfo(goodsInfoId));
		QrCode qrCode = qrCodeMapper.get(new QrCode(qrCodeId));
		if (null != qrCode) {
            qrCode.setGoodsInfo(goodsInfo);
        }
		return qrCode;
	}
}