/**
 * 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.service.QrCodeService;
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 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.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;
	@Autowired
	private WzcodeService wzcodeService;
	
	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 {
			// 查询物资编码
			Wzcode wzcode = wzcodeService.findByCode(goodsInfo.getType().getCode());
			int wzNum = wzcode.getIntNum();

			qrCodeList = new ArrayList<>();
			int num = goodsInfo.getNum();
			String beginNumSeq = "";
			for (int i = 0; i < num; i++) {
				wzNum ++;
				wzcode.setIntNum(wzNum);

				if (0 == i) {
					beginNumSeq = wzcode.getCodeAndNum();
				}
				QrCode qrCode = new QrCode();
				qrCode.setCode(wzcode.getCodeAndNum());
				qrCode.setGoodsInfo(goodsInfo);
				qrCode.setState("0");

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

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

			String qrInterval = beginNumSeq + "_" + wzcode.getNum();
			goodsInfo.setQrInterval(qrInterval); // 设置编码区间
			// goodsInfo.preUpdate();
			goodsInfoMapper.update(goodsInfo);
			goodsInfo.setQrCodeList(qrCodeList);

			// 更新物资编码表
			wzcodeService.save(wzcode);
			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;
	}
}