/**
 * 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.storage.entity.StorageInfo;
import com.jeeplus.modules.warehouse.storage.service.StorageService;
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;
	@Autowired
	private StorageService storageService;
	
	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);
		temQr.setState("0");

		QrCode qc = qrCodeMapper.findByGoodsInfoId(temQr);
		if (null != qc && StringUtils.isNotBlank(qc.getId())) { // 二维码已经生成过
			goodsInfo.setQrCode(qc);
			return goodsInfo;
		} else {

			// 查询物资编码
			Wzcode wzcode = wzcodeService.findByCode(goodsInfo.getType().getCode());
			int wzNum = wzcode.getIntNum();

			wzNum ++;
			wzcode.setIntNum(wzNum);
			QrCode qrCode = new QrCode();
			qrCode.setCode(wzcode.getCodeAndNum());
			qrCode.setGoodsInfo(goodsInfo);
			qrCode.setState("0");
			qrCode.setComeFlag("0");
			qrCode.preInsert();
			try {
				BuildQcUtil.buildQr(qrCode, qrImgPath + "/" + wzcode.getCodeAndNum() + "_tem_" + ".png", qrImgPath + "/" + wzcode.getCodeAndNum() + ".png"); // 生成图片
			} catch (IOException e) {
				e.printStackTrace();
			}
			qrCode.setUrl(Global.getAttachmentUrl() + "image/" + wzcode.getCodeAndNum() + ".png");

			qrCodeMapper.insert(qrCode);
			qrCode = qrCodeMapper.get(qrCode.getId());


			goodsInfo.setQrInterval(wzcode.getNum()); // 设置编码区间
			// goodsInfo.preUpdate();
			goodsInfoMapper.update(goodsInfo);
			goodsInfo.setQrCode(qrCode);

			// 更新物资编码表
			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);
		temQr.setState("0");
		QrCode qrCode = qrCodeMapper.findByGoodsInfoId(temQr);
		if (null != qrCode && StringUtils.isNotBlank(qrCode.getId())) {
			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, "0"); // 删除未入库的二维码
			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));
		List<StorageInfo> list = storageService.findInfoByGoodsInfoId(goodsInfo);
		if (null != list && list.size() > 0) {
			return null;
		}
		QrCode qrCode = qrCodeMapper.get(new QrCode(qrCodeId));
		if (null != qrCode) {
            qrCode.setGoodsInfo(goodsInfo);
        }
		return qrCode;
	}
}