/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-02-24
 * 描述            ：质保书数据主表（质保书编号、合同信息、订收单位、车号、明细号....等信息）
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Qms.qcm.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import market.Api.Mes.impl.MesApiServiceImpl;
import market.Com.mapper.ComBasePhyMapper;
import market.Com.mapper.PbModelDbMapper;
import market.Com.vo.ComBasePhy;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Qms.common.DataHelper;
import market.Qms.common.MergeHSSFSheet;
import market.Qms.common.ReturnMsg;
import market.Qms.metallurgy.mapper.ComBaseStdMapper;
import market.Qms.metallurgy.vo.ComBaseStd;
import market.Qms.qcm.mapper.QcmJhyElementsMapper;
import market.Qms.qcm.mapper.QcmJhyPhyresultMapper;
import market.Qms.qcm.mapper.QcmJhySampleConsignMMapper;
import market.Qms.qcm.mapper.QcmJudgePhysicalUtmDMapper;
import market.Qms.qcm.mapper.QcmPhyJudgeResultMapper;
import market.Qms.qcm.mapper.QcmZbsBillMapper;
import market.Qms.qcm.mapper.QcmZbsCeDMapper;
import market.Qms.qcm.mapper.QcmZbsCeMMapper;
import market.Qms.qcm.mapper.QcmZbsDataCicMapper;
import market.Qms.qcm.mapper.QcmZbsDataMatMapper;
import market.Qms.qcm.mapper.QcmZbsDataOrdMapper;
import market.Qms.qcm.mapper.QcmZbsDataPicMapper;
import market.Qms.qcm.mapper.QcmZbsDataPrtMapper;
import market.Qms.qcm.mapper.QcmZbsTmplCicMapper;
import market.Qms.qcm.mapper.QcmZbsTmplMapper;
import market.Qms.qcm.mapper.QcmZbsTmplPicMapper;
import market.Qms.qcm.mapper.QcmZbsTmplSchMapper;
import market.Qms.qcm.service.QcmZbsDataOrdService;
import market.Qms.qcm.vo.QcmJhyElements;
import market.Qms.qcm.vo.QcmJhyPhyresult;
import market.Qms.qcm.vo.QcmJudgePhysicalUtmD;
import market.Qms.qcm.vo.QcmPhyJudgeResult;
import market.Qms.qcm.vo.QcmZbsBill;
import market.Qms.qcm.vo.QcmZbsCeD;
import market.Qms.qcm.vo.QcmZbsCeM;
import market.Qms.qcm.vo.QcmZbsDataCic;
import market.Qms.qcm.vo.QcmZbsDataMat;
import market.Qms.qcm.vo.QcmZbsDataOrd;
import market.Qms.qcm.vo.QcmZbsDataPic;
import market.Qms.qcm.vo.QcmZbsDataPrt;
import market.Qms.qcm.vo.QcmZbsOrdObject;
import market.Qms.qcm.vo.QcmZbsTmpl;
import market.Qms.qcm.vo.QcmZbsTmplCic;
import market.Qms.qcm.vo.QcmZbsTmplPic;
import market.Qms.qcm.vo.QcmZbsTmplSch;
import market.Qms.slmord.mapper.SlmOrdDesignAdditionalMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdPicMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdPicSmpMapper;
import market.Qms.slmord.vo.SlmOrdDesignAdditional;
import market.Qms.slmord.vo.SlmOrdDesignStdCic;
import market.Qms.slmord.vo.SlmOrdDesignStdPic;
import market.Qms.slmord.vo.SlmOrdDesignStdPicSmp;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.transaction.annotation.Transactional;

import com.aspose.cells.License;
import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path = "QcmZbsDataOrdService")
public class QcmZbsDataOrdServiceImpl extends BaseServiceImpl<QcmZbsDataOrd, Object> implements QcmZbsDataOrdService {

	/**
	 * 获取已经生成的质保书信息
	 */
	public ResultModel getBookInfo(CommonPage<QcmZbsDataOrd> oci) {

		ResultModel rm = new ResultModel();

		try {
			QcmZbsDataOrd ord = oci.getObject();			 
			String material_no =ord.getMaterial_no();			 
			Integer pageIndex = oci.getPageSize() * (oci.getPageIndex() - 1);
			Integer pageSize = oci.getPageSize() * (oci.getPageIndex() - 1) + oci.getPageSize();
			
			String cret_nos=null;
			String condition = "1=1";
			if(material_no!=null && !"".equals(material_no)){
				List<String> crets=this.getMapper(QcmZbsDataOrdMapper.class).findCrets(material_no);
				if (DataHelper.checkIsNull(crets)) {
					cret_nos=DataHelper.getSetConditionList(crets);	
				}
				condition += " and t.cret_no in ("+cret_nos+")";
			}
			if (StringUtils.isNotEmpty(ord.getDeltail_no())) { //发运明细
				condition += " and t.deltail_no like '%"+ord.getDeltail_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getCret_no())) { //质保书编号
				condition += " and t.cret_no like '%"+ord.getCret_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getTrain_no())) { //车船号
				condition += " and t.train_no like '%"+ord.getTrain_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getOrder_unit_desc())) { //订货单位
				condition += " and t.order_unit_desc like '%"+ord.getOrder_unit_desc()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getContract_no())) { //合同号
				condition += " and t.contract_no like '%"+ord.getContract_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getReciver_address())) { //收货地址
				condition += " and y.RECIVER_ADDRESS like '%"+ord.getReciver_address()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getValidflag())) { //是否有效
				condition += " and t.validflag = '"+ord.getValidflag()+"'";
			}

			ReturnMsg<List<QcmZbsDataOrd>> msg = new ReturnMsg<>();
			List<QcmZbsDataOrd> ords = this.getMapper(QcmZbsDataOrdMapper.class).getBookInfo(condition, "cret_no desc", pageIndex, pageSize);
			// 重写统计方法：20230207刘侣
			int total = this.getMapper(QcmZbsDataOrdMapper.class).countOrds(condition);
			// end
			msg.setResult(ords);
			msg.setSuccess(true); 
			msg.setTotal(total);
			msg.setPageIndex(pageIndex);
			msg.setPageSize(pageSize);

			rm.setData(msg);
			rm.setState("200");

		} catch (Exception e) {
			rm.setState("500");
			e.printStackTrace();
			rm.setMsgInfo("查询失败");
			return rm;
		}

		return rm;
	}
	
	/**
	 * 质保书确认界面
	 * 获取已经确认了的质保书信息
	 */
	public ResultModel getBookSureInfo(CommonPage<QcmZbsDataOrd> oci) {

		ResultModel rm = new ResultModel();
		try {
			QcmZbsDataOrd ord = oci.getObject();
			Integer pageIndex = oci.getPageSize() * (oci.getPageIndex() - 1);
			Integer pageSize = oci.getPageSize() * (oci.getPageIndex() - 1) + oci.getPageSize();
			String condition = "1=1";			
			if (StringUtils.isNotEmpty(ord.getCret_no())) { // 质保书编号
				condition += " and cret_no like '%"+ord.getCret_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getDeltail_no())) { // 发运明细号
				condition += " and deltail_no like '%"+ord.getDeltail_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getTrain_no())) { // 车船号
				condition += " and train_no like '%"+ord.getTrain_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getOrder_unit_desc())) { // 订货单位
				condition += " and order_unit_desc like '%"+ord.getOrder_unit_desc()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getContract_no())) { // 合同号
				condition += " and contract_no like '%"+ord.getContract_no()+"%'";
			}
			if (StringUtils.isNotEmpty(ord.getValidflag())) { // 是否有效
				condition += " and validflag = '"+ord.getValidflag()+"'";
			}
			ReturnMsg<List<QcmZbsDataOrd>> msg = new ReturnMsg<>();
			List<QcmZbsDataOrd> ords = this.getMapper(QcmZbsDataOrdMapper.class).findWithCondition(null, condition, "cret_no desc", pageIndex, pageSize);
			int total = this.getMapper(QcmZbsDataOrdMapper.class).countWithCondition(null, condition);

			msg.setResult(ords);
			msg.setTotal(total);		 
			msg.setPageIndex(pageIndex);
			msg.setPageSize(pageSize);
			rm.setData(msg);
			rm.setState("200");

		} catch (Exception e) {
			rm.setState("500");
			e.printStackTrace();
			rm.setMsgInfo("查询失败");
			return rm;
		}

		return rm;
	}
	
	/**
	 * 将质保书置为已经已经确认状态
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel sureBook(CommonPage<QcmZbsDataOrd> oci) throws Exception{
		ResultModel rm=new ResultModel();
		String send_name = this.getSession().getAttribute(HomeService.SESSION_USER_NAME).toString();
		try {
			if (oci!=null) {
				List<QcmZbsDataOrd> ords=oci.getObjectList();
				if (ords!=null && ords.size()>0) {
					for (QcmZbsDataOrd ord : ords) {
						
						if (ord.getCret_no()!=null && !"".equals(ord.getCret_no())) {
							ord=this.getMapper(QcmZbsDataOrdMapper.class).findById(ord.getCret_no());
							if (ord!=null && "1".equals(ord.getValidflag())) {
								ord.setIs_send("1");
								ord.setSend_name(send_name);
								ord.setSend_time(new Date());
								this.getMapper(QcmZbsDataOrdMapper.class).update(ord);
							}	
						}
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("确认失败");
		}
		rm.setMsgInfo("确认成功");
		rm.setState("200");
		return rm;
	}

	/**
	 * 获取质保书子卷信息接口
	 * @param oci
	 * @return
	 */
	public ResultModel getBookMatInfo(CommonPage<QcmZbsDataOrd> oci) {
		ResultModel rm = new ResultModel();
		List<QcmZbsDataMat> mats = new ArrayList<QcmZbsDataMat>();
		try {
			if (oci != null) {
				QcmZbsDataOrd ord = oci.getObject();
				if (ord != null) {
					String cret_no = ord.getCret_no();
					if (cret_no != null && !"".equals(cret_no)) {
						mats = this.getMapper(QcmZbsDataMatMapper.class).findWithCondition(null,
								"CRET_NO='" + cret_no + "'", "MATERIAL_NO", 0, 0);

					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			rm.setData(mats);
			rm.setState("200");
		}

		rm.setData(mats);
		rm.setState("200");
		return rm;
	}

	/**
	 * 质保书作废按钮
	 * 
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel AbolishBook(CommonPage<QcmZbsDataOrd> oci) throws Exception {

		ResultModel rm = new ResultModel();
		String userName = this.getSession().getAttribute(HomeService.SESSION_USER_NAME).toString();
		try {
			List<QcmZbsDataOrd> ords = oci.getObjectList();
			if (ords == null || ords.size() < 1) {
				rm.setMsgInfo("请传入参数");
				rm.setState("500");
				return rm;
			}

			for (QcmZbsDataOrd qcmZbsDataOrd : ords) {

				if (qcmZbsDataOrd.getCret_no() == null || "".equals(qcmZbsDataOrd.getCret_no())) {
					rm.setMsgInfo("质保书编号不能为空");
					rm.setState("500");
					return rm;
				}

				qcmZbsDataOrd.setValidflag("0");
				qcmZbsDataOrd.setDelete_name(userName);
				qcmZbsDataOrd.setDelete_time(new Date());
				this.getMapper(QcmZbsDataOrdMapper.class).update(qcmZbsDataOrd);

				// 给定已经生成质保书标识
				this.getMapper(QcmZbsBillMapper.class).updateConditon(qcmZbsDataOrd.getDeltail_no(),
						qcmZbsDataOrd.getTrain_no(), qcmZbsDataOrd.getContract_no(), qcmZbsDataOrd.getProd_code(),
						qcmZbsDataOrd.getStd_code(), qcmZbsDataOrd.getSteel_code(), qcmZbsDataOrd.getSteel_name(),
						qcmZbsDataOrd.getReciver_unit_code(), qcmZbsDataOrd.getOrder_unit_code());

			}

			rm.setMsgInfo("作废成功");
			rm.setState("200");

		} catch (Exception e) {
			throw new Exception("作废失败！");
		}

		return rm;

	}

	/**
	 * 生成质保书
	 * 
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel createBook(CommonPage<QcmZbsBill> oci) throws Exception {

		ResultModel rm = new ResultModel();

		String userName = this.getSession().getAttribute(HomeService.SESSION_USER_NAME).toString();
		try {
			// 获取数据对象
			if (oci == null) {
				rm.setState("500");
				rm.setMsgInfo("请传入参数");
				return rm;

			}

			List<QcmZbsBill> ords = oci.getObjectList();
			if (ords == null || ords.size() < 1) {
				rm.setState("500");
				rm.setMsgInfo("请传入物料信息");
				return rm;

			}
			QcmZbsBill bill = ords.get(0);
			// 获取是否有合并项目
			// 是否区分轧批号
			String is_batch = bill.getIs_batch();
			// 是否区分宽度
			String is_width = bill.getIs_width();
			// 是否区分长度
			String is_length = bill.getIs_length();

			// 创建质保书编号
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			int count = GetMaxSerialNo("QCM_ZBS_DATA_ORD", "CRET_NO", "ZB" + sdf.format(new Date()));
			String cret_no = "ZB" + sdf.format(new Date()) + String.format("%03d", count + 1);
			// 获取模板编号
			String tmpl_no = oci.getMemo1();
			String plan_no = oci.getMemo2();

			// 获取认证机构,可以为空，为空默认检测中心
			String org_code = bill.getOrg_code();
			// ORG_NAME
			String org_name = bill.getOrg_name();

			List<QcmJhyElements> tarChem = new ArrayList<QcmJhyElements>();
			List<QcmPhyJudgeResult> tarQlty = new ArrayList<QcmPhyJudgeResult>();

			List<QcmZbsDataMat> mats = new ArrayList<QcmZbsDataMat>();
			List<QcmZbsBill> bills = new ArrayList<QcmZbsBill>();
			// 物料信息
			for (QcmZbsBill bl : ords) {

				// 质保书编号与物料信息关系表
				QcmZbsDataMat mat = new QcmZbsDataMat();
				mat.setCret_no(cret_no);
				mat.setDetail_no(bl.getBill_no());
				mat.setMaterial_no(bl.getObject_no());
				mat.setHeat_no(bl.getHeat_no());
				mat.setBatch_no(bl.getBatch_no());
				// mat.setInspection_lot(bl.geti);
				mat.setWeight(bl.getFact_weight());
				mat.setSteel_code(bl.getSteel_code());
				mat.setSteel_name(bl.getSteel_name());
				mat.setThick(bl.getThick());
				mat.setWidth(bl.getWidth());
				mat.setLength(bl.getLength());
				mats.add(mat);
				this.getMapper(QcmZbsDataMatMapper.class).insert(mat);

				// 根据试样号获取，取样编号

				boolean pass = insertInfo(rm, cret_no, org_code, bl, plan_no);

				if (!pass) {
					return rm;

				}
				// 更新状态已经生成质保书
				// 给定已经生成质保书标识
				this.getMapper(QcmZbsBillMapper.class).updateConditonSure(bl.getBill_no(), bl.getCar_no(),
						bl.getContract_no(), bl.getProd_code(), bl.getStd_code(), bl.getSteel_code(),
						bl.getSteel_name(), bl.getReciver_unit_no(), bl.getOrder_unit_no());

			}

			QcmZbsDataOrd ord = new QcmZbsDataOrd();
			ord.setCret_no(cret_no);
			ord.setCreate_time(new Date());
			ord.setCreate_name(userName);
			ord.setTmpl_no(tmpl_no);
			ord.setTrain_no(bill.getCar_no());
			ord.setDeltail_no(bill.getBill_no());
			// 明细创建日期
			ord.setCfnm_date(bill.getCreate_time());//装车时间（发货时间） == 提货单关闭时间
			ord.setContract_no(bill.getContract_no());
			ord.setProd_code(bill.getProd_code());
			ord.setProd_name(bill.getProd_name());
			ord.setSteel_code(bill.getSteel_code());
			ord.setStd_code(bill.getStd_code());
			ord.setStd_name(bill.getStd_name());
			// 订货单位
			ord.setOrder_unit_code(bill.getOrder_unit_no());
			ord.setOrder_unit_desc(bill.getOrder_unit_name());
			// 收货单位
			ord.setReciver_unit_code(bill.getReciver_unit_no());
			ord.setReciver_unit_desc(bill.getReciver_unit_name());
			// 代收单位
			this.getMapper(QcmZbsDataOrdMapper.class).insert(ord);
			rm.setState("200");
			rm.setMsgInfo("质保书生成成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("生成质保书失败");
		}

		return rm;

	}

	/**
	 * 获取流水号（对于有后缀的列不适用，如"20180815RP" 且该列去除前缀之后的值都为数字值
	 * 
	 * @author 上次修订 18/08/15
	 * @param table_name表名
	 *            colunmn列名 prefix前缀名（ 如果不存在前缀，且为数字值时可传空）
	 * @return 如果返回结果为-1 则表示表名和列名为空
	 * @throws Exception
	 */
	public int GetMaxSerialNo(String table_name, String colunmn, String prefix) {
		int result = -1;
		if (table_name != null && !"".equals(table_name) && colunmn != null && !colunmn.equals("")) {
			result = this.getMapper(QcmJhySampleConsignMMapper.class).GetMaxSerialNo(table_name, colunmn, prefix);
		}
		return result;
	}

	private boolean insertInfo(ResultModel rm, String cret_no, String org_code, QcmZbsBill bl, String plan_no) {
		// 根据成品卷号获取原料卷号
		if (bl.getObject_no() == null || "".equals(bl.getObject_no())) {
			rm.setState("500");
			rm.setMsgInfo("成品卷号不存在，请确认");
			return false;
		}

		YdmProductDetail yd = new YdmProductDetail();
		CommonPage<YdmProductDetail> cp = new CommonPage<YdmProductDetail>();
		cp.setObject(yd);
		cp.setMemo1(bl.getObject_no());
		ResultModel ym = new ResultModel();
		try {
			ym = this.getBean(MesApiServiceImpl.class).doQueryMesYdmWeb(cp);
			if (!"200".equals(ym.getState())) {

			}

			if (ym.getData() == null) {
				rm.setState("500");
				rm.setMsgInfo("物料[" + bl.getObject_no() + "]对应的原料卷号不存在，请确认");
				return false;
			}

		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询原料卷号失败");
			return false;

		}

		// 获取原料卷号
		YdmProductDetail old = (YdmProductDetail) ym.getData();
		String old_object = old.getMaterailcoilno();
		// 根据原料卷号查询实绩
		List<QcmJhyElements> elements = this.getMapper(QcmJhyElementsMapper.class).findWithCondition(null,
				"MATERIAL_NO='" + old_object + "'", null, 0, 0);
		if (elements == null || elements.size() < 1) {
			rm.setState("500");
			rm.setMsgInfo("未查询到成分实绩");
			return false;
		}

		// 根据计划号获取成分元素配置
		List<QcmZbsTmplCic> cic = this.getMapper(QcmZbsTmplCicMapper.class).findWithCondition(null,
				"TMPL_CRET_NO='" + plan_no + "'", null, 0, 0);
		if (cic == null || cic.size() < 1) {
			rm.setState("500");
			rm.setMsgInfo("未查询到成分模板[" + plan_no + "],配置的元素，请确认");
			return false;
		}

		for (int i = 0; i < elements.size(); i++) {

			for (QcmZbsTmplCic c : cic) {
				if (elements.get(i).getChem_code().equals(c.getChem_code())) {
					break;
				}

				if (i == elements.size() - 1) {
					elements.remove(i);
					i--;
				}
			}

		}
		if (elements != null && elements.size() > 0) {
			for (QcmJhyElements c : elements) {

			}
		}

		// 查询材质信息
		// 通过物料号成分结果集ID
		YdmProductDetail mtInfo = this.getMapper(YdmProductDetailMapper.class).findById(bl.getObject_no());
		if (mtInfo == null) {
			rm.setState("500");
			rm.setMsgInfo("物料[" + bl.getObject_no() + "],为查询到材质结果集id，请确认");
			return false;
		}
		String pic_id = mtInfo.getPhysresult_id();
		List<QcmJudgePhysicalUtmD> de = this.getMapper(QcmJudgePhysicalUtmDMapper.class).findWithCondition(null,
				"PIC_ID='" + pic_id + "'", null, 0, 0);
		if (de == null || de.size() < 1)

		{
			rm.setState("500");
			rm.setMsgInfo("物料[" + bl.getObject_no() + "],未查询到材质结果集id，请确认");
			return false;

		}

		List<QcmPhyJudgeResult> results = new ArrayList<QcmPhyJudgeResult>();
		for (QcmJudgePhysicalUtmD qd : de)

		{
			if (qd.getPhy_id() == null || "".equals(qd.getPhy_id())) {
				rm.setState("500");
				rm.setMsgInfo("物料[" + bl.getObject_no() + "],未查询到材质结果集phy_id，请确认");
				return false;
			}
			List<SlmOrdDesignStdPic> pics = this.getMapper(SlmOrdDesignStdPicMapper.class).findWithCondition(null,
					"DESIGN_KEY='" + qd.getDesign_key() + "' and ISQUOTE='1'", null, 0, 0);
			List<QcmPhyJudgeResult> qltys = this.getMapper(QcmPhyJudgeResultMapper.class).findWithCondition(null,
					"PHY_ID='" + qd.getPhy_id() + "'", null, 0, 0);
			for (int i = 0; i < qltys.size(); i++) {
				String oldI = qltys.get(i).getPhy_code_l() + qltys.get(i).getPhy_code_m() + qltys.get(i).getPhy_code_s()
						+ qltys.get(i).getItem_code_d() + qltys.get(i).getItem_code_s() + qltys.get(i).getItem_code_t();

				for (int j = 0; j < pics.size(); j++) {
					String newI = pics.get(j).getPhy_code_l() + pics.get(j).getPhy_code_m()
							+ pics.get(j).getPhy_code_s() + pics.get(j).getItem_code_d() + pics.get(j).getItem_code_s()
							+ pics.get(j).getItem_code_t();

					if (oldI.equals(newI)) {
						break;
					}

					if (j == pics.size() - 1) {
						qltys.remove(i);
						i--;
					}
				}

			}

			results.addAll(qltys);

		}

		// 材质判定结果显示：质保书excel试验区分那一块的数据：
		if (results != null || results.size() > 0) {
			long seq = 1;
			for (QcmPhyJudgeResult ql : results) {
				QcmZbsDataPic pic = new QcmZbsDataPic();
				pic.setCret_no(cret_no);
				pic.setBatch_no(ql.getBatch_no());
				pic.setHeat_no(ql.getHeat_no());
				pic.setInspection_lot(ql.getInspection_lot());
				pic.setDelivery_state_code(bl.getDelivery_state_code());
				pic.setDelivery_state_desc(bl.getDelivery_state_desc());
				pic.setMaterial_no(bl.getObject_no());
				pic.setSmp_no(ql.getSmp_no());
				pic.setSeq(seq++);
				pic.setPhy_code_l(ql.getPhy_code_l());
				pic.setPhy_code_m(ql.getPhy_code_m());
				pic.setPhy_code_s(ql.getPhy_code_s());
				pic.setPhy_name_l(ql.getPhy_name_l());
				pic.setPhy_name_m(ql.getPhy_name_m());
				pic.setPhy_name_s(ql.getPhy_name_s());
				pic.setItem_code_d(ql.getItem_code_d());
				pic.setItem_code_s(ql.getItem_code_s());
				pic.setItem_code_t(ql.getItem_code_t());
				pic.setItem_name_d(ql.getItem_name_d());
				pic.setItem_name_s(ql.getItem_name_s());
				pic.setItem_name_t(ql.getItem_name_t());
				pic.setVal1(ql.getVal1());
				pic.setVal2(ql.getVal2());
				pic.setVal3(ql.getVal3());
				pic.setAvg_val(ql.getAvg_val());
				// 取样位置代码
				this.getMapper(QcmZbsDataPicMapper.class).insert(pic);

			}

		}

		return true;
	}

	/**
	 * 生成质保书
	 * 
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel createBook3(CommonPage<QcmZbsOrdObject> oci) throws Exception {

		ResultModel rm = new ResultModel();

		String userName = this.getSession().getAttribute(HomeService.SESSION_USER_NAME).toString();
		try {
			// 获取数据对象
			if (oci == null) {
				rm.setState("500");
				rm.setMsgInfo("请传入参数");
				return rm;

			}

			QcmZbsOrdObject object = oci.getObject();
			// 物料信息
			List<QcmZbsBill> bills = object.getBills();
			// ord表对象
			QcmZbsDataOrd ord = object.getOrds();
			if (bills == null || bills.size() < 1) {
				rm.setState("500");
				rm.setMsgInfo("请传入物料信息");
				return rm;

			}
			// 是否区分轧批号
			String is_batch = ord.getIs_batch();
			// 是否区分宽度
			String is_width = ord.getIs_width();
			// 是否区分长度
			String is_length = ord.getIs_length();

			// 创建质保书编号
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			int count = GetMaxSerialNo("QCM_ZBS_DATA_ORD", "CRET_NO", "ZB" + sdf.format(new Date()));
			String cret_no = "ZB" + sdf.format(new Date()) + String.format("%03d", count + 1);
			// 获取模板编号
			// String tmpl_no = oci.getMemo1();
			String plan_no = ord.getPlan_no();

			// 获取认证机构,可以为空，为空默认检测中心
			String org_code = ord.getOrg_code();
			// ORG_NAME
			String org_name = ord.getOrg_name();
			if (org_code == null || "".equals(org_code)) {
				org_code = "409601";
				org_name = "检测中心";
			}
			// 数据来源
			String resource = object.getResource();

			List<QcmZbsDataCic> tarChem = new ArrayList<QcmZbsDataCic>();
			List<QcmZbsDataPic> tarQlty = new ArrayList<QcmZbsDataPic>();

			List<QcmZbsDataMat> mats = new ArrayList<QcmZbsDataMat>();
			List<QcmZbsBill> tarBill = new ArrayList<QcmZbsBill>();
			// 物料信息
			for (QcmZbsBill old : bills) {
				// List<QcmZbsBill>
				// mes=this.getMapper(QcmZbsBillMapper.class).find(old, 0,0);
				/*
				 * QcmZbsBill bl=mes.get(0); tarBill.add(old);
				 */
				// 质保书编号与物料信息关系表

				// this.getMapper(QcmZbsDataMatMapper.class).insert(mat);

				// 根据试样号获取，取样编号
				List<QcmZbsBill> mes = new ArrayList<>();
				if ("1".equals(is_batch)) {
					// 根据轧批号获取卷号

					if ("1".equals(is_length) && "1".equals(is_width)) {

						mes = this.getMapper(QcmZbsBillMapper.class).findByAllBatch(old.getBill_no(),
								ord.getSteel_code(), old.getProd_code(), old.getStd_code(), old.getReciver_unit_no(),
								old.getDelivery_state_code(), old.getContract_no(), old.getOrder_unit_no(),
								old.getOrg_code(), old.getBatch_no(), old.getThick(), old.getWidth(), old.getLength(),
								old.getCar_no());
					} else if ("1".equals(is_length)) {
						mes = this.getMapper(QcmZbsBillMapper.class).findByBatchLength(old.getBill_no(),
								ord.getSteel_code(), old.getProd_code(), old.getStd_code(), old.getReciver_unit_no(),
								old.getDelivery_state_code(), old.getContract_no(), old.getOrder_unit_no(),
								old.getOrg_code(), old.getBatch_no(), old.getThick(), old.getLength(), old.getCar_no());

					} else if ("1".equals(is_width)) {
						mes = this.getMapper(QcmZbsBillMapper.class).findByBatchWidth(old.getBill_no(),
								ord.getSteel_code(), old.getProd_code(), old.getStd_code(), old.getReciver_unit_no(),
								old.getDelivery_state_code(), old.getContract_no(), old.getOrder_unit_no(),
								old.getOrg_code(), old.getBatch_no(), old.getThick(), old.getWidth(), old.getCar_no());

					} else {
						mes = this.getMapper(QcmZbsBillMapper.class).findByBatchThick(old.getBill_no(),
								ord.getSteel_code(), old.getProd_code(), old.getStd_code(), old.getReciver_unit_no(),
								old.getDelivery_state_code(), old.getContract_no(), old.getOrder_unit_no(),
								old.getOrg_code(), old.getBatch_no(), old.getThick(), old.getCar_no());

					}

					QcmZbsBill bl = mes.get(0);
					tarBill.addAll(mes);

					QcmZbsDataMat mat = new QcmZbsDataMat();
					mat.setCret_no(cret_no);
					mat.setDetail_no(bl.getBill_no());
					mat.setMaterial_no(bl.getObject_no());
					mat.setHeat_no(bl.getHeat_no());
					mat.setBatch_no(bl.getBatch_no());
					// mat.setInspection_lot(bl.geti);
					mat.setWeight(bl.getFact_weight());
					mat.setSteel_code(bl.getSteel_code());
					mat.setSteel_name(bl.getSteel_name());
					mat.setThick(bl.getThick());
					mat.setWidth(bl.getWidth());
					mat.setLength(bl.getLength());
					mat.setCustomer_order_no(bl.getCustomer_order_no());
					mat.setDic_lv_code(bl.getDic_lv_code());
					mat.setDic_lv_desc(bl.getDic_lv_desc());
					mat.setDic_result_desc(bl.getDic_result_desc());
					mat.setDic_std_code(bl.getDic_std_code());
					mat.setDic_std_desc(bl.getDic_std_desc());
					// 总数量
					mat.setSum_cnt(String.valueOf(old.getBill_count()));
					mats.add(mat);

					bl.setObject_no(mes.get(0).getObject_no());

					boolean pass = insertInfo2(rm, cret_no, org_code, bl, plan_no, tarChem, tarQlty);

					if (!pass) {
						return rm;

					}

				} else {

					// 根据试样号获取，取样编号
					QcmZbsBill bl = this.getMapper(QcmZbsBillMapper.class).findById(old.getBill_no(),
							old.getObject_no());
					tarBill.add(bl);

					QcmZbsDataMat mat = new QcmZbsDataMat();
					mat.setCret_no(cret_no);
					mat.setDetail_no(bl.getBill_no());
					mat.setMaterial_no(bl.getObject_no());
					mat.setHeat_no(bl.getHeat_no());
					mat.setBatch_no(bl.getBatch_no());
					// mat.setInspection_lot(bl.geti);
					mat.setWeight(bl.getFact_weight());
					mat.setSteel_code(bl.getSteel_code());
					mat.setSteel_name(bl.getSteel_name());
					mat.setThick(bl.getThick());
					mat.setWidth(bl.getWidth());
					mat.setLength(bl.getLength());
					mat.setCustomer_order_no(bl.getCustomer_order_no());
					mat.setDic_lv_code(bl.getDic_lv_code());
					mat.setDic_lv_desc(bl.getDic_lv_desc());
					mat.setDic_result_desc(bl.getDic_result_desc());
					mat.setDic_std_code(bl.getDic_std_code());
					mat.setDic_std_desc(bl.getDic_std_desc());
					// 总数量
					mat.setSum_cnt(String.valueOf(old.getBill_count()));
					mats.add(mat);

					boolean pass = insertInfo2(rm, cret_no, org_code, old, plan_no, tarChem, tarQlty);

					if (!pass) {
						return rm;

					}

				}

				// boolean pass = insertInfo(rm, cret_no, org_code, bl,
				// plan_no);

			}

			if ("1".equals(resource)) {
				// 获取订单的附加要求
				String design_key = ord.getDesign_key();
				if (design_key != null && !"".equals(design_key)) {
					getAddInfo(ord, design_key);
				}

			}
			// 查询标准号获取许可证号
			if (ord.getStd_code() != null && !"".equals(ord.getStd_code())) {
				ComBaseStd base = this.getMapper(ComBaseStdMapper.class).findById(ord.getStd_code());
				if (base != null) {
					ord.setLicense_no(base.getLicense_no());
				}
			}
			double fact_weight = 0;

			// 更新bill表
			for (QcmZbsBill bl : tarBill) {
				fact_weight += Double.valueOf(bl.getFact_weight());
				// 给定已经生成质保书标识
				this.getMapper(QcmZbsBillMapper.class).updateConditonSure(bl.getBill_no(), bl.getCar_no(),
						bl.getContract_no(), bl.getProd_code(), bl.getStd_code(), bl.getSteel_code(),
						bl.getSteel_name(), bl.getReciver_unit_no(), bl.getOrder_unit_no());

			}
			for (QcmZbsDataMat mat : mats) {
				this.getMapper(QcmZbsDataMatMapper.class).insert(mat);
			}

			ord.setCret_no(cret_no);
			ord.setCreate_time(new Date());
			ord.setCreate_name(userName);
			ord.setSum_cnt(String.valueOf(bills.size()));
			ord.setSum_wgt(String.valueOf(fact_weight));
			ord.setCfnm_date(tarBill.get(0).getDetail_date());
			this.getMapper(QcmZbsDataOrdMapper.class).insert(ord);

			// 插入成分

			for (QcmZbsDataCic chem : tarChem) {
				this.getMapper(QcmZbsDataCicMapper.class).insert(chem);

			}

			// 插入材质
			for (QcmZbsDataPic qlty : tarQlty) {
				this.getMapper(QcmZbsDataPicMapper.class).insert(qlty);
			}

			rm.setState("200");
			rm.setMsgInfo("质保书生成成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("生成质保书失败");
		}

		return rm;

	}

	/**
	 * 生成质保书
	 * 
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel createBook2(CommonPage<QcmZbsDataOrd> oci) throws Exception {
		ResultModel rm = new ResultModel();
		String userName = this.getSession().getAttribute(HomeService.SESSION_USER_NAME).toString();
		// 获取数据对象
		if (oci == null) {
			rm.setState("500");
			rm.setMsgInfo("请传入参数");
			return rm;
		}
		try {
			// QcmZbsOrdObject object = oci.getObject();
			// List<QcmZbsOrdObject> objects = oci.getObjectList();
			List<QcmZbsDataOrd> objects = oci.getObjectList();
			// 目标集合
			List<QcmZbsDataOrd> tarOrds = new ArrayList<QcmZbsDataOrd>();
			List<QcmZbsDataMat> tarMats = new ArrayList<QcmZbsDataMat>();
			List<QcmZbsDataPic> tarPics = new ArrayList<QcmZbsDataPic>();
			List<QcmZbsDataCic> tarCics = new ArrayList<QcmZbsDataCic>();
			List<QcmZbsBill> tarBills = new ArrayList<QcmZbsBill>();

			// 创建质保书编号
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			int count = GetMaxSerialNo("QCM_ZBS_DATA_ORD", "CRET_NO", "ZB" + sdf.format(new Date()));

			List<QcmZbsBill> mes = new ArrayList<>();
			for (QcmZbsDataOrd ord : objects) {				
				String cret_no = "ZB" + sdf.format(new Date()) + String.format("%03d", ++count);
				// 获取EC认证编码
				List<QcmZbsCeD> ceDs = this.getMapper(QcmZbsCeDMapper.class).findWithCondition(null, "STD_CODE='" + ord.getStd_code() + "'", null, 0, 0);
				List<QcmZbsCeM> ceM = new ArrayList<QcmZbsCeM>();
				for (QcmZbsCeD ce : ceDs) {
					QcmZbsCeM cm = this.getMapper(QcmZbsCeMMapper.class).findById(ce.getCe_code());
					if (cm != null) {
						ceM.add(cm);
					}
				}

				ord.setCret_no(cret_no);
				// 获取认证机构,可以为空，为空默认检测中心
				String org_code = ord.getOrg_code();
				String org_name = ord.getOrg_name();
				if (org_code == null || "".equals(org_code)) {
					org_code = "409601";
					org_name = "检测中心";
				}

				List<QcmZbsBill> bills = new ArrayList<>();
				// 是否区分轧批号
				String is_batch = ord.getIs_batch();
				Boolean pass;

				// 重量
				double weight = 0.0;
				// 质保书类型
				String cret_type = null;
				String design_key = null;
				if ("1".equals(is_batch)) {

					List<QcmZbsBill> batchs = new ArrayList<>();
					batchs = this.getMapper(QcmZbsBillMapper.class).findGroupAll(ord);
					for (QcmZbsBill b : batchs) {
						List<QcmZbsDataPic> b_pic = new ArrayList<QcmZbsDataPic>();
						List<QcmZbsDataCic> b_cic = new ArrayList<QcmZbsDataCic>();
						bills = this.getMapper(QcmZbsBillMapper.class).findByGroupBatch(b);
						pass = findItems2(rm, bills.get(0), b_pic, b_cic, ord, org_code);
						String material_no = bills.get(0).getObject_no();
						if (!pass) {
							return rm;
						}
						tarBills.addAll(bills);
						if (design_key == null || "".equals(design_key)) {
							design_key = bills.get(0).getDesign_key();
						}

						QcmZbsDataMat mat = new QcmZbsDataMat();
						mat.setCret_no(cret_no);
						mat.setDetail_no(b.getBill_no());
						mat.setMaterial_no(material_no);
						mat.setHeat_no(b.getHeat_no());
						mat.setBatch_no(b.getBatch_no());
						// mat.setInspection_lot(bl.geti);
						mat.setWeight(b.getFact_weight());
						mat.setSteel_code(b.getSteel_code());
						mat.setSteel_name(b.getSteel_name());
						mat.setSum_cnt("1");
						//20210119 除分条机组取实际的规格，其它的都取订单的规格
						mat.setThick(b.getThick());
						mat.setWidth(b.getWidth());
						mat.setLength(b.getLength());
						mat.setDelivery_state_code(b.getDelivery_state_code());
						mat.setDelivery_state_desc(b.getDelivery_state_desc());
						mat.setCustomer_order_no(b.getCustomer_order_no());
						tarMats.add(mat);
						// 过滤CE描述
						FilterSize(b.getThick(), b.getWidth(), ceM);

						for (QcmZbsDataPic pic : b_pic) {
							pic.setCret_no(cret_no);
							pic.setMaterial_no(material_no);
							pic.setDelivery_state_code(ord.getDelivery_state_code());
							pic.setDelivery_state_desc(ord.getDelivery_state_desc());
							tarPics.add(pic);
						}

						for (QcmZbsDataCic cic : b_cic) {
							cic.setCret_no(cret_no);
							cic.setMaterial_no(material_no);
							tarCics.add(cic);
						}

						// 总量累计
						if (b.getFact_weight() != null && !"".equals(b.getFact_weight())) {
							weight += Double.valueOf(b.getFact_weight());
						}

					}

					// 数量
					if (batchs != null && batchs.size() > 0) {
						ord.setSum_cnt(String.valueOf(batchs.size()));
					}

				} else {
					// 根据条件查询对应的卷
					List<QcmZbsDataPic> ranPics = new ArrayList<QcmZbsDataPic>();
					List<QcmZbsDataCic> ranCics = new ArrayList<QcmZbsDataCic>();
					bills = this.getMapper(QcmZbsBillMapper.class).findNoCondition(ord);
					// 将需要生成质保书的卷放入目标卷集合，用于改变状态
					tarBills.addAll(bills);
					for (QcmZbsBill b : bills) {
						pass = findItems2(rm, b, ranPics, ranCics, ord, org_code);
						if (!pass) {
							return rm;
						}
						if (design_key == null || "".equals(design_key)) {
							design_key = b.getDesign_key();
						}

						QcmZbsDataMat mat = new QcmZbsDataMat();
						mat.setCret_no(cret_no);
						mat.setDetail_no(b.getBill_no());
						mat.setMaterial_no(b.getObject_no());
						mat.setHeat_no(b.getHeat_no());
						mat.setBatch_no(b.getBatch_no());
						// mat.setInspection_lot(bl.geti);
						mat.setWeight(b.getFact_weight());
						mat.setSteel_code(b.getSteel_code());
						mat.setSteel_name(b.getSteel_name());
						mat.setSum_cnt("1");
						mat.setThick(b.getThick());
						mat.setWidth(b.getWidth());
						mat.setLength(b.getLength());
						mat.setDelivery_state_code(b.getDelivery_state_code());
						mat.setDelivery_state_desc(b.getDelivery_state_desc());
						mat.setCustomer_order_no(b.getCustomer_order_no());
						tarMats.add(mat);
						// 过滤CE描述
						FilterSize(b.getThick(), b.getWidth(), ceM);
						// 总量累计
						if (b.getFact_weight() != null && !"".equals(b.getFact_weight())) {
							weight += Double.valueOf(b.getFact_weight());
						}

					}

					for (QcmZbsDataPic pic : ranPics) {
						pic.setCret_no(cret_no);
						pic.setDelivery_state_code(ord.getDelivery_state_code());
						pic.setDelivery_state_desc(ord.getDelivery_state_desc());
						tarPics.add(pic);
					}

					for (QcmZbsDataCic cic : ranCics) {
						cic.setCret_no(cret_no);
						tarCics.add(cic);

					}

					if (bills != null && bills.size() > 0) {
						ord.setSum_cnt(String.valueOf(bills.size()));
					}

				}
				// 设置CE编号
				if (ceM != null && ceM.size() > 0) {
					ord.setCe_no(ceM.get(0).getCe_code());
				}

				// 获取质保书类型
				if (design_key != null && !"".equals(design_key)) {
					// 根据design_key获取订单的附加要求
					List<SlmOrdDesignAdditional> adds = this.getMapper(SlmOrdDesignAdditionalMapper.class)
							.findWithCondition(null, "DESIGN_KEY='" + design_key + "' and ASK_SUB_ITME='12100308'",
									null, 0, 0);
					if (adds != null && adds.size() > 0) {
						cret_type = adds.get(0).getAsk_sub_itme_val_desc();
					}
				}

				// 总重量
				ord.setCret_type(cret_type);
				ord.setSum_wgt(String.valueOf(weight));
				tarOrds.add(ord);

			}

			// 插入表
			for (QcmZbsBill bill : tarBills) {
				this.getMapper(QcmZbsBillMapper.class).updateCreatBook(bill.getBill_no(), bill.getObject_no());
			}

			for (QcmZbsDataCic cic : tarCics) {
				this.getMapper(QcmZbsDataCicMapper.class).insert(cic);
			}

			

			for (QcmZbsDataPic pic : tarPics) {
				this.getMapper(QcmZbsDataPicMapper.class).insert(pic);
			}
			for (QcmZbsDataOrd ord : tarOrds) {
				ord.setCreate_time(new Date());
				ord.setCreate_name(userName);
				this.getMapper(QcmZbsDataOrdMapper.class).insert(ord);
			}
			
			for (QcmZbsDataMat mat : tarMats) {
				this.getMapper(QcmZbsDataMatMapper.class).insert(mat);
			}
			//生成质保书数据
			CommonPage<QcmZbsDataOrd> sum=new CommonPage<QcmZbsDataOrd>();
			sum.setObjectList(tarOrds);
			try {
				ResultModel results=this.getService(QcmZbsBillServiceImpl.class).printBookEdition(sum);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("生成质保书文件失败");
			}

			

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}

		rm.setMsgInfo("质保书生成成功");
		rm.setState("200");
		return rm;
	}

	/**
	 * CE标识过滤限制规格
	 */
	private void FilterSize(String thick, String width, List<QcmZbsCeM> ceM) {
		if (ceM != null && ceM.size() > 0) {
			for (int i = 0; i < ceM.size(); i++) {
				boolean pass;
				if (ceM.get(i).getThick_min() == null || "".equals(ceM.get(i).getThick_min())) {
					pass = true;
				} else {
					pass = DataHelper.checkSignAndValue(ceM.get(i).getThick_min_sign(),
							Double.valueOf(ceM.get(i).getThick_min()), thick);
				}

				if (!pass) {
					ceM.remove(i);
					i--;
					continue;
				}

				if (ceM.get(i).getThick_max() != null && "".equals(ceM.get(i).getThick_max())) {
					pass = true;
				} else {
					pass = DataHelper.checkSignAndValue(ceM.get(i).getThick_max_sign(),
							Double.valueOf(ceM.get(i).getThick_max()), thick);

				}

				if (!pass) {
					ceM.remove(i);
					i--;
					continue;
				}

				if (ceM.get(i).getWidth_min() == null || "".equals(ceM.get(i).getWidth_min())) {
					pass = true;
				} else {
					pass = DataHelper.checkSignAndValue(ceM.get(i).getWidth_min(),
							Double.valueOf(ceM.get(i).getWidth_min()), width);

				}

				if (!pass) {
					ceM.remove(i);
					i--;
					continue;
				}

				if (ceM.get(i).getWidth_max() == null || "".equals(ceM.get(i).getWidth_max())) {
					pass = true;
				} else {
					pass = DataHelper.checkSignAndValue(ceM.get(i).getWidth_max_sign(),
							Double.valueOf(ceM.get(i).getWidth_max()), width);

				}
				if (!pass) {
					ceM.remove(i);
					i--;
					continue;
				}

			}

		}

	}

	private Boolean findItems2(ResultModel rm, QcmZbsBill bl, List<QcmZbsDataPic> b_pic, List<QcmZbsDataCic> b_cic,
			QcmZbsDataOrd ord, String org_code) throws Exception {

		// 查询成分实绩
		// 如果cic_ic不为空
		// 0为原料卷

		// 有判定记录的卷，材质结果集
		List<QcmPhyJudgeResult> results = new ArrayList<QcmPhyJudgeResult>();

		List<QcmJhyElements> elsements = new ArrayList<QcmJhyElements>();
		// 判断
		List<QcmZbsTmplPic> tmplPic = new ArrayList<>();
		List<QcmZbsTmplCic> tmplCic = new ArrayList<>();
		QcmZbsTmplSch sch = new QcmZbsTmplSch();
		if (ord.getPlan_no() != null && !"".equals(ord.getPlan_no())) {
			tmplPic = this.getMapper(QcmZbsTmplPicMapper.class).findWithCondition(null, "TMPL_CRET_NO='" + ord.getPlan_no() + "' and VALIDFLAG='1'", "SEQ", 0, 0);
			sch = this.getMapper(QcmZbsTmplSchMapper.class).findById(ord.getPlan_no());
			tmplCic = this.getMapper(QcmZbsTmplCicMapper.class).findWithCondition(null, "TMPL_CRET_NO='" + ord.getPlan_no() + "' and VALIDFLAG='1'", null, 0, 0);
		}

		YdmProductDetail detail = this.getMapper(YdmProductDetailMapper.class).findById(bl.getObject_no());
		// 材质
		if ("0".equals(bl.getMat_type())) {//0原料卷、1中间卷、2成品卷
			// 查询物流的物料信息表。获取原料卷的成分材质
			if (detail != null) {
				// 获取材质试样号
				String smpno = detail.getSmpno();
				// 获取材质卷号
				String materailcoilno = detail.getMaterailcoilno();
				List<QcmPhyJudgeResult> ranResults = new ArrayList<QcmPhyJudgeResult>();
				//材质
				if (smpno != null && !"".equals(smpno) && !"无式样号".equals(smpno)) {
					List<QcmJhyPhyresult> qltys = this.getMapper(QcmJhyPhyresultMapper.class).findWithCondition(null, "SPECIMEN_NO='" + smpno + "'", "SEQ", 0, 0);
					if (qltys != null && qltys.size() > 0) {
						for (QcmJhyPhyresult ql : qltys) {
							// 统一对象，使代码可复用
							QcmPhyJudgeResult re = new QcmPhyJudgeResult();
							DataHelper.CopyEntity(ql, re);
							re.setSmp_no(smpno);
							re.setMaterial_no(bl.getObject_no());
							ranResults.add(re);
						}
						// 如果是轧机卷就不需要材质信息出现在质保书：20230227刘侣
						// 经过轧机或者退火的就不需要显示材质信息：20230510 刘侣
						
						String sql = "select count(1) from ydm_product_detail t where t.materailcoilno in ("
								+ "select ypd.materailcoilno from ydm_product_detail ypd where ypd.coilno = '"+bl.getObject_no()+"') "
								+ "and (t.coilno like '%T%'or t.coilno like '%L%') and substr(t.coilno,-1,1) not in ('B','H')";
						int count = this.getMapper(QcmZbsBillMapper.class).doQueryIsExistsTOrL(sql);
						if (count <= 0) {
							judgePlan(results, ranResults, null, sch, tmplPic);
						}
						
						// 获取材质项目
//						judgePlan(results, ranResults, null, sch, tmplPic);
						// 逻辑废除：
//						if (bl.getObject_no() != null && !bl.getObject_no().contains("L")) {
//							judgePlan(results, ranResults, null, sch, tmplPic);
//						}
						// end
					}
				}
				//  "HEAT_NO = '" + detail.getHeatno() + "'"    "MATERIAL_NO='" + materailcoilno + "'"
				// 成分：因为相同炉号的很多卷只会传一个炉号的成分信息过来，所以统一才有炉号查询成分信息，而不是使用原始卷号查询：20230510 刘侣
				if (materailcoilno != null && !"".equals(materailcoilno) && (detail.getHeatno() != null && !"".equals(detail.getHeatno()))) {
					List<QcmJhyElements> ranElements = this.getMapper(QcmJhyElementsMapper.class)
							.findWithCondition(null, "MATERIAL_NO='" + materailcoilno + "'", null, 0, 0);
					if (ranElements != null && ranElements.size() > 0) {
						judgeChem(elsements, ranElements, null, sch, tmplCic);
					} else {
						ranElements = this.getMapper(QcmJhyElementsMapper.class)
								.findWithCondition(null, "HEAT_NO = '" + detail.getHeatno() + "'", null, 0, 0);
						if (ranElements != null && ranElements.size() > 0) {
							judgeChem(elsements, ranElements, null, sch, tmplCic);
						}
					}
					
					
					// elsements.addAll(ranElements);
				}

			}

		} else {	//成品卷
			// 1.材质
			if (bl.getPic_id() != null && !"无式样号".equals(bl.getPic_id()) && !"".equals(bl.getPic_id())) {
				List<QcmJudgePhysicalUtmD> de = this.getMapper(QcmJudgePhysicalUtmDMapper.class).findWithCondition(null, "PIC_ID='" + bl.getPic_id() + "'", null, 0, 0);
				if (de != null && de.size() > 0) {
					for (QcmJudgePhysicalUtmD qd : de) {
						List<SlmOrdDesignStdPic> pics = this.getMapper(SlmOrdDesignStdPicMapper.class).
								findWithCondition(null, "DESIGN_KEY='" + qd.getDesign_key() + "' and ISQUOTE='1'", null, 0, 0);
						// 查询材质判定结果					
						List<QcmPhyJudgeResult> qltys = this.getMapper(QcmPhyJudgeResultMapper.class).
								findWithCondition(null, "PHY_ID='" + qd.getPhy_id() + "'", "SMP_NO", 0, 0);
						//判断卷子是否经过轧机或者退火，经过这两道工序会改变性能
						String coilno = bl.getObject_no().substring(0, 8);
						String sql = "select count(1) from ydm_product_detail t where t.coilno like '%"+coilno+"%' and (t.machine_name like '%退火%' or t.machine_name like '%轧机%')";
						int count = this.getMapper(PbModelDbMapper.class).doQueryCount(sql);
						if (count > 0) {
							//经过了退火或者轧机
							int i = 0;
							for (QcmPhyJudgeResult q : qltys) {
								if (StringUtils.isNotEmpty(q.getPhy_name_s()) && q.getPhy_name_s().contains("粗系")) {
									i++;
									continue;
								}
							}
							//材质信息来自新钢材质
							if (i > 0) {
								qltys = null;
								continue;
							}
						}
						
						// 如果是轧机卷就不需要材质信息出现在质保书：20230227刘侣
						// 经过轧机或者退火的就不需要显示材质信息：20230510 刘侣
						// 如果后续补充了材质信息，那么就需要显示出来：20230516刘侣
						String sqlC = "select count(1) from ydm_product_detail t where t.materailcoilno in ("
								+ "select ypd.materailcoilno from ydm_product_detail ypd where ypd.coilno = '"+bl.getObject_no()+"') "
								+ "and (t.coilno like '%T%'or t.coilno like '%L%') and substr(t.coilno,-1,1) not in ('B','H')";
						int countC = this.getMapper(QcmZbsBillMapper.class).doQueryIsExistsTOrL(sql);
						if (count <= 0) {
							judgePlan(results, qltys, pics, sch, tmplPic);
						} else {
							// 经过了轧机或者退火：后续是否补充了材质信息：
							String sqlBC = "select count(1) from QCM_JHY_SAMPLE_CONSIGN_M t "
									+ "join YDM_PRODUCT_DETAIL ypd on t.INSPECTION_LOT = ypd.INSPECTION_LOT "
									+ "where ypd.COILNO = '" + bl.getObject_no() + "'";
							int countBC = this.getMapper(QcmZbsBillMapper.class).getIsBC(sqlBC);
							if (countBC > 0) {
								// 说明重新补充了材质信息：
								judgePlan(results, qltys, pics, sch, tmplPic);
							}
						}
						
						// judgePlan(results, qltys, pics, sch, tmplPic);
//						if (bl.getObject_no() != null && !bl.getObject_no().contains("L")) {
//							judgePlan(results, qltys, pics, sch, tmplPic);
//						}
						// end
					}

				}else {
					//没经过退火和轧制的，直接取新钢过来的性能。经过退火和轧机的，取相对性的材质性能
					/*String sql = "select count(1) from ydm_product_detail t where t.materailcoilno in ("
							+ "select ypd.materailcoilno from ydm_product_detail ypd where ypd.coilno = '"+qzb.getObject_no()+"') "
							+ "and (t.coilno like '%T%'or t.coilno like '%L%') and substr(t.coilno,-1,1) not in ('B','H')";
					int count = this.getMapper(QcmZbsBillMapper.class).doQueryIsExistsTOrL(sql);
					if (count > 0) {
						continue;
					}*/
					
					
				}
			}  
			// 2.成分：因为相同炉号的很多卷只会传一个炉号的成分信息过来，所以统一才有炉号查询成分信息，而不是使用原始卷号查询：20230510 刘侣
			if (bl.getCic_id() != null && !"".equals(bl.getCic_id()) && (detail.getHeatno() != null && !"".equals(detail.getHeatno()))) {
				List<QcmJhyElements> ranElements = this.getMapper(QcmJhyElementsMapper.class).findWithCondition(null,
						"MATERIAL_NO='" + bl.getCic_id() + "'", null, 0, 0);
				if (ranElements != null && ranElements.size() > 0) {
					judgeChem(elsements, ranElements, null, sch, tmplCic);
					// elsements.addAll(ranElements);
				} else {
					ranElements = this.getMapper(QcmJhyElementsMapper.class).findWithCondition(null,
							"HEAT_NO = '" + detail.getHeatno() + "'", null, 0, 0);
					if (ranElements != null && ranElements.size() > 0) {
						judgeChem(elsements, ranElements, null, sch, tmplCic);
						// elsements.addAll(ranElements);
					}
				}
			}
		}

		// 成分转化
		if (elsements != null && elsements.size() > 0) {
			for (QcmJhyElements el : elsements) {
				QcmZbsDataCic tar = new QcmZbsDataCic();
				tar.setCret_no(ord.getCret_no());
				tar.setMaterial_no(bl.getObject_no());
				tar.setChem_code(el.getChem_code());
				tar.setChem_name(el.getChem_name());
				tar.setChem_value(el.getChem_value());
				tar.setAssay_type(el.getAssay_type());
				tar.setSmp_no(el.getSmp_no());
				tar.setBatch_no(el.getBatch_no());
				tar.setInspection_lot(el.getInspection_lot());
				tar.setSmp_no(el.getSmp_no());
				tar.setBatch_no(el.getBatch_no());
				tar.setInspection_lot(el.getInspection_lot());
				tar.setHeat_no(el.getHeat_no());
				tar.setSteel_code(el.getSteel_code());
				tar.setSteel_name(el.getSteel_name());
				b_cic.add(tar);

			}

		}

		// 材质转化
		if (results != null && results.size() > 0) {
			for (QcmPhyJudgeResult ql : results) {
				//不需要新钢过来的【A粗细。B粗细】
				if (StringUtils.isNotEmpty(ql.getPhy_name_s()) && ql.getPhy_name_s().contains("粗系")) {
					continue;
				}
				if (StringUtils.isNotEmpty(ql.getPhy_name_s()) && ql.getPhy_name_s().contains("脱碳层")) {
					continue;
				}
				QcmZbsDataPic pic = new QcmZbsDataPic();
				pic.setCret_no(ord.getCret_no());
				pic.setBatch_no(bl.getBatch_no());
				pic.setHeat_no(bl.getHeat_no());
				pic.setInspection_lot(ql.getInspection_lot());
				pic.setDelivery_state_code(bl.getDelivery_state_code());
				pic.setDelivery_state_desc(bl.getDelivery_state_desc());
				pic.setMaterial_no(bl.getObject_no());
				pic.setSmp_no(ql.getSmp_no());
				pic.setSeq(ql.getSeq());
				pic.setPhy_code_l(ql.getPhy_code_l());
				pic.setPhy_code_m(ql.getPhy_code_m());
				pic.setPhy_code_s(ql.getPhy_code_s());
				pic.setPhy_name_l(ql.getPhy_name_l());
				pic.setPhy_name_m(ql.getPhy_name_m());
				pic.setPhy_name_s(ql.getPhy_name_s());
				//System.out.println(ql.getPhy_name_s());
				//System.out.println(ql.getItem_name_s());
				pic.setItem_code_d(ql.getItem_code_d());
				pic.setItem_code_s(ql.getItem_code_s());
				pic.setItem_code_t(ql.getItem_code_t());
				pic.setItem_name_d(ql.getItem_name_d());
				pic.setItem_name_s(ql.getItem_name_s());
				pic.setItem_name_t(ql.getItem_name_t());
				pic.setVal1(ql.getVal1());
				pic.setVal2(ql.getVal2());
				pic.setVal3(ql.getVal3());
				if (StringUtils.isEmpty(ql.getVal1()) && StringUtils.isEmpty(ql.getVal2()) && StringUtils.isEmpty(ql.getVal3())) {
					continue;
				}
				// 值单位
				ComBasePhy phy = this.getMapper(ComBasePhyMapper.class).findById(ql.getPhy_code_s());
				if (phy != null) {
					pic.setPhy_unit(phy.getPhy_unit());
				}
				b_pic.add(pic);
				// 根据dk+试样组、方向、温度尺寸查取样要求
				/*String sample_key = DataHelper.GetNull(ql.getPhy_code_m()) + "_"
						+ DataHelper.GetNull(ql.getItem_code_d())+ "_" 
						+ DataHelper.GetNull(ql.getItem_code_t()) + "_" + DataHelper.GetNull(ql.getItem_code_s());
				
				// 需要考虑国标、客户、内控共有项目的取样要求不同，需要过滤；
				String condition = createItem(ql);
				List<SlmOrdDesignStdPic> picss = this.getMapper(SlmOrdDesignStdPicMapper.class).findWithCondition(null,
						condition, null, 0, 0);
				if (picss != null && picss.size() > 0) {
					String pic_sample = null;
					for (int k = 0; k < picss.size(); k++) {

						if ("1".equals(picss.get(k).getSpecl_fl())) {

							pic_sample = picss.get(k).getPic();
							break;

						} else if ("0".equals(picss.get(k).getSpecl_fl())) {
							pic_sample = picss.get(k).getPic();
						}
					}
					List<SlmOrdDesignStdPicSmp> smples = this.getMapper(SlmOrdDesignStdPicSmpMapper.class)
							.findWithCondition(null, "SAMPLE_KEY='" + sample_key + "' and DESIGN_KEY='"
									+ ql.getDesign_key() + "' and PIC='" + pic_sample + "'", null, 0, 0);
					if (smples != null && smples.size() > 0) {
						pic.setPosition_code(smples.get(0).getPosition());
						pic.setPosition_desc(smples.get(0).getDesc_position());
					}
					b_pic.add(pic);

				}*/

			}
		}

		return true;
	}

	/**
	 * 获取报出成分元素
	 * 
	 * @param elsements
	 * @param ranElements
	 * @param object
	 * @param sch
	 * @param tmplCic
	 * @throws Exception
	 */
	private void judgeChem(List<QcmJhyElements> elsements, List<QcmJhyElements> ranElements,
			List<SlmOrdDesignStdCic> cics, QcmZbsTmplSch sch, List<QcmZbsTmplCic> tmplCic) throws Exception {

		if (ranElements != null && ranElements.size() > 0) {

			List<SlmOrdDesignStdCic> itemCic = new ArrayList<>();
			if ((cics != null && cics.size() > 0) && (tmplCic != null && tmplCic.size() > 0)) {

				if ("0".equals(sch.getMod_cic())) {
					for (int i = 0; i < cics.size(); i++) {

						for (int j = 0; j < tmplCic.size(); j++) {

							if (cics.get(i).getChem_code().equals(tmplCic.get(j).getChem_code())) {
								cics.remove(i);
								i--;
								break;
							}

						}
					}
					itemCic.addAll(cics);

				} else if ("1".equals(sch.getMod_cic())) {
					for (QcmZbsTmplCic tc : tmplCic) {
						SlmOrdDesignStdCic c = new SlmOrdDesignStdCic();
						DataHelper.CopyEntity(tc, c);
						itemCic.add(c);
					}

					for (int i = 0; i < cics.size(); i++) {

						for (int j = 0; j < itemCic.size(); j++) {
							if (cics.get(i).getChem_code().equals(itemCic.get(j).getChem_code())) {
								break;
							}

							if (j == itemCic.size() - 1) {
								itemCic.add(cics.get(i));
								break;
							}

						}

					}

				}

			} else if ((cics != null && cics.size() > 0) && (tmplCic == null || tmplCic.size() < 1)) {
				itemCic.addAll(cics);
			} else if ((tmplCic != null && tmplCic.size() > 0) && (cics == null || cics.size() < 1)) {
				if ("1".equals(sch.getMod_cic())) {
					for (QcmZbsTmplCic tc : tmplCic) {
						SlmOrdDesignStdCic c = new SlmOrdDesignStdCic();
						DataHelper.CopyEntity(tc, c);
						itemCic.add(c);
					}

				}

			}

			if (itemCic != null && itemCic.size() > 0) {
				if (ranElements == null || ranElements.size() < 1) {
					return;
				}
				a: for (SlmOrdDesignStdCic item : itemCic) {
					for (int i = 0; i < ranElements.size(); i++) {
						if (ranElements.get(i).getChem_code().equals(item.getChem_code())) {
							elsements.add(ranElements.get(i));
							continue a;
						}
					}
				}
			}

		}

	}

	/**
	 * 获取报出的材质项目
	 * 
	 * @param results
	 * @param qltys
	 * @param pics
	 * @param sch
	 * @param tmplPic
	 * @throws Exception
	 */
	private void judgePlan(List<QcmPhyJudgeResult> results, List<QcmPhyJudgeResult> qltys,
			List<SlmOrdDesignStdPic> pics, QcmZbsTmplSch sch, List<QcmZbsTmplPic> tmplPic) throws Exception {
		
		// 承装报出项目
		List<SlmOrdDesignStdPic> ItemPic = new ArrayList<>();
		// 用于排序的集合
		List<QcmPhyJudgeResult> seqResults = new ArrayList<QcmPhyJudgeResult>();

		// 材质结果存在时
		if (qltys != null && qltys.size() > 0) {
			// 方案配置与标准报出同时存在时
			if ((tmplPic != null && tmplPic.size() > 0) && (pics != null && pics.size() > 0)) {
				// 材质加载质保书区分（0：不加载，1加载）
				if ("0".equals(sch.getMod_pic())) {
					for (int i = 0; i < pics.size(); i++) {
						String oldI = pics.get(i).getPhy_code_l() + pics.get(i).getPhy_code_m()
								+ pics.get(i).getPhy_code_s() + pics.get(i).getItem_code_d()
								+ pics.get(i).getItem_code_s() + pics.get(i).getItem_code_t();

						for (QcmZbsTmplPic tp : tmplPic) {
							String newI = tp.getPhy_code_l() + tp.getPhy_code_m() + tp.getPhy_code_s()
									+ tp.getItem_code_d() + tp.getItem_code_s() + tp.getItem_code_t();
							if (oldI.equals(newI)) {
								pics.remove(i);
								i--;
								break;
							}
						}
					}
					ItemPic.addAll(pics);

				} else if ("1".equals(sch.getMod_pic())) {
					for (QcmZbsTmplPic tp : tmplPic) {
						SlmOrdDesignStdPic p = new SlmOrdDesignStdPic();
						DataHelper.CopyEntity(tp, p);
						ItemPic.add(p);
					}

					for (int i = 0; i < pics.size(); i++) {
						String oldI = pics.get(i).getPhy_code_l() + pics.get(i).getPhy_code_m()
								+ pics.get(i).getPhy_code_s() + pics.get(i).getItem_code_d()
								+ pics.get(i).getItem_code_s() + pics.get(i).getItem_code_t();

						for (int j = 0; j < ItemPic.size(); j++) {
							String newI = ItemPic.get(j).getPhy_code_l() + ItemPic.get(j).getPhy_code_m()
									+ ItemPic.get(j).getPhy_code_s() + ItemPic.get(j).getItem_code_d()
									+ ItemPic.get(j).getItem_code_s() + ItemPic.get(j).getItem_code_t();

							if (oldI.equals(newI)) {
								break;

							}

							if (j == ItemPic.size() - 1) {
								ItemPic.add(pics.get(i));
								break;
							}

						}

					}

				}

			} else if ((tmplPic != null && tmplPic.size() > 0) && (pics == null || pics.size() < 1)) {
				for (QcmZbsTmplPic tp : tmplPic) {
					SlmOrdDesignStdPic p = new SlmOrdDesignStdPic();
					DataHelper.CopyEntity(tp, p);
					ItemPic.add(p);
				}

			} else if ((tmplPic == null || tmplPic.size() < 1) && (pics != null && pics.size() > 0)) {
				ItemPic.addAll(pics);

			}

			// 根据报出项目，过滤材质结果集：将code改成name试下，应为tmpl表和judgeresult表的各项code值变了，导致全部被过滤掉了；20230214刘侣
			if (ItemPic != null && ItemPic.size() > 0) {
				for (QcmPhyJudgeResult ql : qltys) {
					// 这个匹配过滤有什么用？20230214刘侣
//					String newQlty = DataHelper.GetNull(ql.getPhy_name_l()) +  DataHelper.GetNull(ql.getPhy_name_m()) +  DataHelper.GetNull(ql.getPhy_name_s()) 
//							+  DataHelper.GetNull(ql.getItem_name_d()); //+  DataHelper.GetNull(ql.getItem_code_s()) +  DataHelper.GetNull(ql.getItem_code_t());
//					System.out.println("  新："+newQlty);
//					for (SlmOrdDesignStdPic pic : ItemPic) {
//						String oldQlty =  DataHelper.GetNull(pic.getPhy_name_l()) +  DataHelper.GetNull(pic.getPhy_name_m()) +  DataHelper.GetNull(pic.getPhy_name_s())
//								+  DataHelper.GetNull(pic.getItem_name_d());// +  DataHelper.GetNull(pic.getItem_code_s()) +  DataHelper.GetNull(pic.getItem_code_t());
//						System.out.println("  老"+oldQlty);
//						if (newQlty.equals(oldQlty)) {
//							seqResults.add(ql);
//						}
//					}
					
//					seqResults.add(ql);
					// 加上匹配，不过这次是匹配的配置方案里的PHY_NAME_S 20230215刘侣
					String newQlty = DataHelper.GetNull(ql.getPhy_name_s());
//							System.out.println("  新："+newQlty);
					List<String> lll = new ArrayList<>();
					for (SlmOrdDesignStdPic pic : ItemPic) {
						String oldQlty = DataHelper.GetNull(pic.getPhy_name_s());
//						System.out.println("  老"+oldQlty);
						if (lll.contains(newQlty)) {
							continue;
						}
						if (oldQlty.contains(newQlty)) {
							seqResults.add(ql);
							lll.add(newQlty);
						}
					}
					// end
				}
			}

			Long seq = 1l;
			if (seqResults != null && seqResults.size() > 0) {
				for (QcmPhyJudgeResult s : seqResults) {
					s.setSeq(seq++);
				}
				results.addAll(seqResults);
			}

		}

	}

	private boolean insertInfo2(ResultModel rm, String cret_no, String org_code, QcmZbsBill bl, String plan_no,
			List<QcmZbsDataCic> tarChem, List<QcmZbsDataPic> tarQlty) {
		// 根据成品卷号获取原料卷号
		if (bl.getObject_no() == null || "".equals(bl.getObject_no())) {
			rm.setState("500");
			rm.setMsgInfo("成品卷号不存在，请确认");
			return false;
		}

		YdmProductDetail yd = new YdmProductDetail();
		CommonPage<YdmProductDetail> cp = new CommonPage<YdmProductDetail>();
		cp.setObject(yd);
		cp.setMemo1(bl.getObject_no());
		ResultModel ym = new ResultModel();
		try {
			ym = this.getBean(MesApiServiceImpl.class).doQueryMesYdmWeb(cp);
			if (!"200".equals(ym.getState())) {
				rm.setState("500");
				rm.setMsgInfo("物料[" + bl.getObject_no() + "]对应的原料卷号查询失败，请确认");
				return false;
			}

			if (ym.getData() == null) {
				rm.setState("500");
				rm.setMsgInfo("物料[" + bl.getObject_no() + "]对应的原料卷号不存在，请确认");
				return false;
			}

		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询原料卷号失败");
			return false;

		}

		// 获取原料卷号
		YdmProductDetail old = (YdmProductDetail) ym.getData();
		String old_object = old.getMaterailcoilno();
		if (old_object == null || "".equals(old_object)) {
			rm.setState("500");
			rm.setMsgInfo("物料[" + bl.getObject_no() + "]对应的原料卷号为空，请确认");
			return false;
		}
		// 根据原料卷号查询实绩
		List<QcmJhyElements> elements = this.getMapper(QcmJhyElementsMapper.class).findWithCondition(null,
				"MATERIAL_NO='" + old_object + "'", null, 0, 0);
		if (elements == null || elements.size() < 1) {
			/*
			 * rm.setState("500"); rm.setMsgInfo("未查询到成分实绩"); return false;
			 */
		} else {

			// 根据计划号获取成分元素配置
			List<QcmZbsTmplCic> cic = this.getMapper(QcmZbsTmplCicMapper.class).findWithCondition(null,
					"TMPL_CRET_NO='" + plan_no + "'", null, 0, 0);
			if (cic == null || cic.size() < 1) {
				rm.setState("500");
				rm.setMsgInfo("未查询到成分模板[" + plan_no + "],配置的元素，请确认");
				return false;
			}

			for (int i = 0; i < elements.size(); i++) {

				for (int j = 0; j < cic.size(); j++) {

					if (elements.get(i).getChem_code().equals(cic.get(j).getChem_code())) {
						break;
					}

					if (j == cic.size() - 1) {
						elements.remove(i);
						i--;
						break;
					}

					if (i == elements.size() - 1) {
						elements.remove(i);
						i--;
						break;
					}
				}

			}

			if (elements != null && elements.size() > 0) {
				for (QcmJhyElements el : elements) {

					QcmZbsDataCic tar = new QcmZbsDataCic();
					tar.setCret_no(cret_no);
					tar.setMaterial_no(bl.getObject_no());
					tar.setChem_code(el.getChem_code());
					tar.setChem_name(el.getChem_name());
					tar.setChem_value(el.getChem_value());
					tar.setAssay_type(el.getAssay_type());
					tar.setSmp_no(el.getSmp_no());
					tar.setBatch_no(el.getBatch_no());
					tar.setInspection_lot(el.getInspection_lot());
					tar.setSmp_no(el.getSmp_no());
					tar.setBatch_no(el.getBatch_no());
					tar.setInspection_lot(el.getInspection_lot());
					tar.setHeat_no(el.getHeat_no());
					tar.setSteel_code(el.getSteel_code());
					tar.setSteel_name(el.getSteel_name());
					tarChem.add(tar);

				}
			}

		}

		// 通过物料号成分结果集ID
		YdmProductDetail mtInfo = this.getMapper(YdmProductDetailMapper.class).findById(bl.getObject_no());
		if (mtInfo == null) {
			/*
			 * rm.setState("500"); rm.setMsgInfo("物料[" + bl.getObject_no() +
			 * "],为查询到材质结果集id，请确认"); return false;
			 */
		} else {
			String pic_id = mtInfo.getPhysresult_id();
			List<QcmJudgePhysicalUtmD> de = this.getMapper(QcmJudgePhysicalUtmDMapper.class).findWithCondition(null,
					"PIC_ID='" + pic_id + "'", null, 0, 0);
			if (de == null || de.size() < 1)

			{
				/*
				 * rm.setState("500"); rm.setMsgInfo("物料[" + bl.getObject_no() +
				 * "],未查询到材质结果集id，请确认"); return false;
				 */

			} else {
				List<QcmPhyJudgeResult> results = new ArrayList<QcmPhyJudgeResult>();
				for (QcmJudgePhysicalUtmD qd : de)

				{
					if (qd.getPhy_id() == null || "".equals(qd.getPhy_id())) {
						rm.setState("500");
						rm.setMsgInfo("物料[" + bl.getObject_no() + "],未查询到材质结果集phy_id，请确认");
						return false;
					}

					if (qd.getDesign_key() == null || "".equals(qd.getDesign_key())) {
						rm.setState("500");
						rm.setMsgInfo("物料[" + bl.getObject_no() + "],未查询到材质结果集phy_id[" + qd.getPhy_id()
								+ "]对应的 design_key，请确认");
						return false;
					}
					List<SlmOrdDesignStdPic> pics = this.getMapper(SlmOrdDesignStdPicMapper.class).findWithCondition(
							null, "DESIGN_KEY='" + qd.getDesign_key() + "' and ISQUOTE='1'", null, 0, 0);
					List<QcmPhyJudgeResult> qltys = this.getMapper(QcmPhyJudgeResultMapper.class)
							.findWithCondition(null, "PHY_ID='" + qd.getPhy_id() + "'", null, 0, 0);
					for (int i = 0; i < qltys.size(); i++) {
						String oldI = qltys.get(i).getPhy_code_l() + qltys.get(i).getPhy_code_m()
								+ qltys.get(i).getPhy_code_s() + qltys.get(i).getItem_code_d()
								+ qltys.get(i).getItem_code_s() + qltys.get(i).getItem_code_t();

						qltys.get(i).setDesign_key(qd.getDesign_key());
						for (int j = 0; j < pics.size(); j++) {
							String newI = pics.get(j).getPhy_code_l() + pics.get(j).getPhy_code_m()
									+ pics.get(j).getPhy_code_s() + pics.get(j).getItem_code_d()
									+ pics.get(j).getItem_code_s() + pics.get(j).getItem_code_t();

							if (oldI.equals(newI)) {
								break;
							}

							if (j == pics.size() - 1) {
								qltys.remove(i);
								i--;
							}
						}

					}

					results.addAll(qltys);

				}

				if (results != null || results.size() > 0) {
					long seq = 1;
					for (QcmPhyJudgeResult ql : results) {
						QcmZbsDataPic pic = new QcmZbsDataPic();
						pic.setCret_no(cret_no);
						pic.setBatch_no(bl.getBatch_no());
						pic.setHeat_no(bl.getHeat_no());
						pic.setInspection_lot(ql.getInspection_lot());
						pic.setDelivery_state_code(bl.getDelivery_state_code());
						pic.setDelivery_state_desc(bl.getDelivery_state_desc());
						pic.setMaterial_no(bl.getObject_no());
						pic.setSmp_no(ql.getSmp_no());
						pic.setSeq(seq++);
						pic.setPhy_code_l(ql.getPhy_code_l());
						pic.setPhy_code_m(ql.getPhy_code_m());
						pic.setPhy_code_s(ql.getPhy_code_s());
						pic.setPhy_name_l(ql.getPhy_name_l());
						pic.setPhy_name_m(ql.getPhy_name_m());
						pic.setPhy_name_s(ql.getPhy_name_s());
						pic.setItem_code_d(ql.getItem_code_d());
						pic.setItem_code_s(ql.getItem_code_s());
						pic.setItem_code_t(ql.getItem_code_t());
						pic.setItem_name_d(ql.getItem_name_d());
						pic.setItem_name_s(ql.getItem_name_s());
						pic.setItem_name_t(ql.getItem_name_t());
						pic.setVal1(ql.getVal1());
						pic.setVal2(ql.getVal2());
						pic.setVal3(ql.getVal3());
						// 值单位
						ComBasePhy phy = this.getMapper(ComBasePhyMapper.class).findById(ql.getPhy_code_s());
						if (phy != null) {
							pic.setPhy_unit(phy.getPhy_unit());
						}
						// 根据dk+试样组、方向、温度尺寸查取样要求
						String sample_key = DataHelper.GetNull(ql.getPhy_code_m()) + "_"
								+ DataHelper.GetNull(ql.getItem_code_d()) + "_"
								+ DataHelper.GetNull(ql.getItem_code_t()) + ""
								+ DataHelper.GetNull(ql.getItem_code_s());
						// 需要考虑国标、客户、内控共有项目的取样要求不同，需要过滤；
						String condition = createItem(ql);
						List<SlmOrdDesignStdPic> picss = this.getMapper(SlmOrdDesignStdPicMapper.class)
								.findWithCondition(null, condition, null, 0, 0);
						if (picss != null && picss.size() > 0) {
							String pic_sample = null;
							for (int k = 0; k < picss.size(); k++) {

								if ("1".equals(picss.get(k).getSpecl_fl())) {

									pic_sample = picss.get(k).getPic();
									break;

								} else if ("0".equals(picss.get(k).getSpecl_fl())) {
									pic_sample = picss.get(k).getPic();
								}
							}
							List<SlmOrdDesignStdPicSmp> smples = this.getMapper(SlmOrdDesignStdPicSmpMapper.class)
									.findWithCondition(
											null, "SAMPLE_KEY='" + sample_key + "' and DESIGN_KEY='"
													+ ql.getDesign_key() + "' and PIC='" + pic_sample + "'",
											null, 0, 0);
							if (smples != null && smples.size() > 0) {
								pic.setPosition_code(smples.get(0).getPosition());
								pic.setPosition_desc(smples.get(0).getDesc_position());
							}

						}

						tarQlty.add(pic);
						// 取样位置代码
						// this.getMapper(QcmZbsDataPicMapper.class).insert(pic);

					}

				}
			}
		}

		return true;
	}

	private void getAddInfo(QcmZbsDataOrd ord, String design_key) {

		// 牌号
		List<SlmOrdDesignAdditional> addition = this.getMapper(SlmOrdDesignAdditionalMapper.class).findWithCondition(
				null, "DESIGN_KEY='" + design_key + "' and ASK_SUB_ITME='12100313' and VALIDFLAG='1'", null, 0, 0);

		if (addition != null && addition.size() > 0) {
			ord.setSteel_code(addition.get(0).getAsk_sub_itme_val());
			ord.setSteel_name(addition.get(0).getAsk_sub_itme_val_desc());
		}
		// 质保书标准号
		addition = this.getMapper(SlmOrdDesignAdditionalMapper.class).findWithCondition(null,
				"DESIGN_KEY='" + design_key + "' and ASK_SUB_ITME='12100314' and VALIDFLAG='1'", null, 0, 0);

		if (addition != null && addition.size() > 0) {
			ord.setStd_code(addition.get(0).getAsk_sub_itme_val());
			ord.setStd_name(addition.get(0).getAsk_sub_itme_val_desc());
		}
		// 质保书合同号
		addition = this.getMapper(SlmOrdDesignAdditionalMapper.class).findWithCondition(null,
				"DESIGN_KEY='" + design_key + "' and ASK_SUB_ITME='12100315' and VALIDFLAG='1'", null, 0, 0);

		if (addition != null && addition.size() > 0) {
			ord.setContract_no(addition.get(0).getAsk_sub_itme_val_desc());
		}
		// 质保书收货单位
		addition = this.getMapper(SlmOrdDesignAdditionalMapper.class).findWithCondition(null,
				"DESIGN_KEY='" + design_key + "' and ASK_SUB_ITME='12100316' and VALIDFLAG='1'", null, 0, 0);
		if (addition != null && addition.size() > 0) {
			ord.setReciver_unit_code(addition.get(0).getAsk_sub_itme_val());
			ord.setReciver_unit_desc(addition.get(0).getAsk_sub_itme_val_desc());
		}
		// 质保书合同单位
		addition = this.getMapper(SlmOrdDesignAdditionalMapper.class).findWithCondition(null,
				"DESIGN_KEY='" + design_key + "' and ASK_SUB_ITME='12100317' and VALIDFLAG='1'", null, 0, 0);
		if (addition != null && addition.size() > 0) {
			ord.setOrder_unit_code(addition.get(0).getAsk_sub_itme_val());
			ord.setOrder_unit_desc(addition.get(0).getAsk_sub_itme_val_desc());
		}

	}

	private String createItem(QcmPhyJudgeResult ql) {
		String condition = "1=1";

		if (ql.getPhy_code_l() != null && !"".equals(ql.getPhy_code_l())) {
			condition += " and PHY_CODE_L='" + ql.getPhy_code_l() + "'";
		}

		if (ql.getPhy_code_m() != null && !"".equals(ql.getPhy_code_m())) {
			condition += " and PHY_CODE_M='" + ql.getPhy_code_m() + "'";
		}

		if (ql.getPhy_code_s() != null && !"".equals(ql.getPhy_code_s())) {
			condition += " and PHY_CODE_S='" + ql.getPhy_code_s() + "'";
		}

		if (ql.getItem_code_d() != null && !"".equals(ql.getItem_code_d())) {
			condition += " and ITEM_CODE_D='" + ql.getItem_code_d() + "'";
		}

		if (ql.getItem_code_t() != null && !"".equals(ql.getItem_code_t())) {
			//condition += " and ITEM_CODE_T='" + ql.getItem_code_t() + "'";
		}

		if (ql.getItem_code_s() != null && !"".equals(ql.getItem_code_s())) {
			//condition += " and ITEM_CODE_S='" + ql.getItem_code_s() + "'";
		}

		return condition;
	}

	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel getValue(CommonPage<QcmZbsDataOrd> oci) throws Exception {

		ResultModel rm = new ResultModel();
		try {
			if (oci == null) {
				rm.setState("500");
				rm.setMsgInfo("请传入参数");
				return rm;
			}

			QcmZbsDataOrd ord = oci.getObject();

			if (ord == null) {
				rm.setState("500");
				rm.setMsgInfo("请传入需要获取实绩的质保书编号");
				return rm;
			}

			if (ord.getCret_no() == null || "".equals(ord.getCret_no())) {
				rm.setState("500");
				rm.setMsgInfo("请传入质保书编号");
				return rm;
			}

			ord = this.getMapper(QcmZbsDataOrdMapper.class).findById(ord.getCret_no());
			if (ord == null) {
				rm.setState("500");
				rm.setMsgInfo("未查询到需要获取实绩的质保书编号");
				return rm;
			}
			// 清空成分材质
			this.getMapper(QcmZbsDataCicMapper.class).deleteByCretNo(ord.getCret_no());
			this.getMapper(QcmZbsDataPicMapper.class).deleteByCretNo(ord.getCret_no());

			List<QcmZbsDataCic> tarChem = new ArrayList<QcmZbsDataCic>();
			List<QcmZbsDataPic> tarQlty = new ArrayList<QcmZbsDataPic>();
			String cret_no = ord.getCret_no();
			String org_code = ord.getOrg_code();
			String plan_no = ord.getPlan_no();
			List<QcmZbsDataMat> mats = this.getMapper(QcmZbsDataMatMapper.class).findWithCondition(null,
					"cret_no='" + cret_no + "'", null, 0, 0);
			for (QcmZbsDataMat mat : mats) {

				QcmZbsBill bl = new QcmZbsBill();
				bl.setBill_no(mat.getMaterial_no());
				bl.setObject_no(mat.getMaterial_no());
				boolean pass = insertInfo2(rm, cret_no, org_code, bl, plan_no, tarChem, tarQlty);
				if (!pass) {
					return rm;
				}

			}

			// 插入成分

			for (QcmZbsDataCic chem : tarChem) {
				this.getMapper(QcmZbsDataCicMapper.class).insert(chem);

			}

			// 插入材质
			for (QcmZbsDataPic qlty : tarQlty) {
				this.getMapper(QcmZbsDataPicMapper.class).insert(qlty);
			}

			if ((tarChem == null || tarChem.size() < 1) && (tarQlty == null || tarQlty.size() < 1)) {
				rm.setState("200");
				rm.setMsgInfo("未获取到成分材质实绩");

			} else if (tarChem == null || tarChem.size() < 1) {
				rm.setState("200");
				rm.setMsgInfo("未获取到成分实绩");

			} else if (tarQlty == null || tarQlty.size() < 1) {
				rm.setState("200");
				rm.setMsgInfo("未获取到材质实绩");

			} else {
				rm.setState("200");
				rm.setMsgInfo("获取成功");
			}

		} catch (Exception e) {
			// 获取成分材质实绩失败
			e.printStackTrace();
			throw new Exception("获取实绩失败");

		}

		return rm;
	}

	public ResultModel printExcel(CommonPage<QcmZbsDataOrd> sum) throws Exception {

		ResultModel rm = new ResultModel();

		// 数据验证
		if (sum==null) {
			rm.setState("500");
			rm.setMsgInfo("请传入需要预览的数据");
			return rm;
		}
		List<String> roots=new ArrayList<>();
		List<QcmZbsDataOrd> ords = sum.getObjectList();
		if (ords==null || ords.size()<1) {
			rm.setState("500");
			rm.setMsgInfo("请传入需要预览的数据");
			return rm;
		}
		String path = this.getRequest().getServletContext().getRealPath("/") + "excel" + File.separator; // 临时保存路径
		File dir = new File(path);
		if (!dir.exists()) {
			new File(path).mkdir();
		}
		for (QcmZbsDataOrd ord : ords) {
			if (ord.getCret_no()==null || "".equals(ord.getCret_no())) {
				rm.setState("500");
				rm.setMsgInfo("请传入质保书编号");
				return rm;
			}
			ord=this.getMapper(QcmZbsDataOrdMapper.class).findById(ord.getCret_no());
			if (ord==null || !"1".equals(ord.getValidflag())) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]已不存在或已经作废，请确认");
				return rm;
			}
			byte[] by=ord.getCret_xls();
			if (by==null || by.length<1) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]无可打印数据，请确认");
				return rm;
			}
			String book_num = path + "第[" + ord.getCret_no() + "]号质保书.xls";
			FileOutputStream out=new FileOutputStream(book_num);
			out.write(by);
			out.flush();
			out.close();
			roots.add("/download?filename=" + "第[" + ord.getCret_no() + "]号质保书.xls");
			
			
		}

		rm.setData(roots);
		rm.setState("200");
		return rm;

	}

	/**
	 * 打印质保书为PDF形式
	 * @param sum
	 * @return
	 * @throws Exception
	 */
	public ResultModel printPdf(CommonPage<QcmZbsDataOrd> sum) throws Exception {
		ResultModel rm = new ResultModel();
		String userName = this.getSession().getAttribute(HomeService.SESSION_USER_NAME).toString();		
		// 数据验证
		if (sum==null) {
			rm.setState("500");
			rm.setMsgInfo("请传入需要预览的数据");
			return rm;
		}
		List<String> roots=new ArrayList<>();
		List<QcmZbsDataOrd> ords = sum.getObjectList();
		if (ords==null || ords.size()<1) {
			rm.setState("500");
			rm.setMsgInfo("请传入需要预览的数据");
			return rm;
		}
		String path = this.getRequest().getServletContext().getRealPath("/") + "excel" + File.separator; // 临时保存路径
		File dir = new File(path);
		if (!dir.exists()) {
			new File(path).mkdir();
		}
		for (QcmZbsDataOrd ord : ords) {
			if (ord.getCret_no()==null || "".equals(ord.getCret_no())) {
				rm.setState("500");
				rm.setMsgInfo("请传入质保书编号");
				return rm;
			}
			ord=this.getMapper(QcmZbsDataOrdMapper.class).findById(ord.getCret_no());
			if (ord==null || !"1".equals(ord.getValidflag()) ) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]已不存在或已经作废，请确认");
				return rm;
			}
			if (!"1".equals(ord.getIs_send())) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]处于未确认状态，请确认");
				return rm;
			}
			if (!getLicense()) {
		           // return;
		        }
			byte[] by=ord.getCret_pdf();
			if (by==null || by.length<1) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]无可打印数据，请确认");
				return rm;
			}
			String book_num = path + "第[" + ord.getCret_no() + "]号质保书.pdf";
			FileOutputStream out=new FileOutputStream(book_num);			
			out.write(by);
			out.flush();
			out.close();
			String num=ord.getPrint_cnt();
			int value=Integer.valueOf(num);
			value++;
			ord.setPrint_cnt(String.valueOf(value));
			ord.setPrint_flag("1");
			ord.setPrint_id(userName);
			SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String data=sDateFormat.format(new Date());
			ord.setPrint_dtime(data);
			this.getMapper(QcmZbsDataOrdMapper.class).update(ord);
			roots.add("/download?filename=" + "第[" + ord.getCret_no() + "]号质保书.pdf");
			//插入打印记录表
			QcmZbsDataPrt print=new QcmZbsDataPrt();
			print.setCret_pdf(by);
			print.setCret_no(ord.getCret_no());
			print.setCreate_name(userName);
			print.setCreate_time(new Date());
			//获取打印的最大流水号
			Long seq=this.getMapper(QcmZbsDataPrtMapper.class).findMaxSeq(ord.getCret_no());
			if (seq==null) {
				seq=1l;
			}else{
				seq++;
			}
			print.setCret_seq(seq);
			this.getMapper(QcmZbsDataPrtMapper.class).insert(print);			
		}
		rm.setData(roots);
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 打印质保书为PDF形式：打包形式
	 * @param sum
	 * @return
	 * @throws Exception
	 */
	public ResultModel printPdfPackage(CommonPage<QcmZbsDataOrd> sum) throws Exception {
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String userName = this.getSession().getAttribute(HomeService.SESSION_USER_NAME).toString();
		SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String data=sDateFormat.format(now);
		// 数据验证
		if (sum==null) {
			rm.setState("500");
			rm.setMsgInfo("请传入需要预览的数据");
			return rm;
		}
		List<String> roots=new ArrayList<>();
		List<QcmZbsDataOrd> ords = sum.getObjectList();
		if (ords==null || ords.size()<1) {
			rm.setState("500");
			rm.setMsgInfo("请传入需要预览的数据");
			return rm;
		}
		String path = this.getRequest().getServletContext().getRealPath("/") + "excel" + File.separator; // 临时保存路径
		File dir = new File(path);
		if (!dir.exists()) {
			new File(path).mkdir();
		}
		
		String zipName = userName+new SimpleDateFormat("yyyyMMdd").format(now);
		ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipName));//生成Zip的名称
		for (QcmZbsDataOrd ord : ords) {
			if (ord.getCret_no()==null || "".equals(ord.getCret_no())) {
				rm.setState("500");
				rm.setMsgInfo("请传入质保书编号");
				return rm;
			}
			ord=this.getMapper(QcmZbsDataOrdMapper.class).findById(ord.getCret_no());
			if (ord==null || !"1".equals(ord.getValidflag()) ) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]已不存在或已经作废，请确认");
				return rm;
			}
			if (!"1".equals(ord.getIs_send())) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]处于未确认状态，请确认");
				return rm;
			}
			if (!getLicense()) {
		           // return;
		    }
			byte[] by=ord.getCret_pdf();
			if (by==null || by.length<1) {
				rm.setState("500");
				rm.setMsgInfo("质保书["+ord.getCret_no()+"]无可打印数据，请确认");
				return rm;
			}			
			
			String num=ord.getPrint_cnt();
			int value=Integer.valueOf(num);
			value++;
			ord.setPrint_cnt(String.valueOf(value));
			ord.setPrint_flag("1");
			ord.setPrint_id(userName);			
			ord.setPrint_dtime(data);//打印时间
			this.getMapper(QcmZbsDataOrdMapper.class).update(ord);
			
			roots.add("/download?filename=" + "第[" + ord.getCret_no() + "]号质保书.pdf");
			//新增：打印记录表
			QcmZbsDataPrt print=new QcmZbsDataPrt();
			print.setCret_pdf(by);
			print.setCret_no(ord.getCret_no());
			print.setCreate_name(userName);
			print.setCreate_time(new Date());
			//获取打印的最大流水号
			Long seq=this.getMapper(QcmZbsDataPrtMapper.class).findMaxSeq(ord.getCret_no());
			if (seq==null) {
				seq=1l;
			}else{
				seq++;
			}
			print.setCret_seq(seq);
			this.getMapper(QcmZbsDataPrtMapper.class).insert(print);	
			//添加数据
			String book_num = path + "第[" + ord.getCret_no() + "]号质保书.pdf";
			zipOut.putNextEntry(new ZipEntry(book_num));
			
			InputStream input = new ByteArrayInputStream(by);
			input.read(by);
			zipOut.write(by);
			input.close();			
			zipOut.closeEntry();
			zipOut.flush();
		}
		zipOut.close();
		
		rm.setData("/download?filename=" + zipName + "质保书.zip");
		rm.setState("200");
		return rm;
	}

	/**
	 * 验证质保书的数据是否完整，合理
	 */
	private boolean dataValidation(QcmZbsDataOrd ord, ResultModel rm) {

		if (ord == null) {
			rm.setState("500");
			rm.setMsgInfo("请传入参数");
			return false;
		}
		if (ord.getCret_no() == null || "".equals(ord.getCret_no())) {
			rm.setState("500");
			rm.setMsgInfo("请传入质保书编号");
			return false;
		}
		ord = this.getMapper(QcmZbsDataOrdMapper.class).findById(ord.getCret_no());
		if (ord == null || !"1".equals(ord.getValidflag())) {
			rm.setState("500");
			rm.setMsgInfo("质保书[" + ord.getCret_no() + "],不存在或已经作废");
			return false;
		}

		return true;
	}

	public void test() throws IOException {
		// 模板配置数据
		Long l = System.currentTimeMillis();
		MergeHSSFSheet he = new MergeHSSFSheet();
		QcmZbsTmpl model = this.getMapper(QcmZbsTmplMapper.class).findById("B00002");
		QcmZbsTmpl model1 = this.getMapper(QcmZbsTmplMapper.class).findById("B00004");
		/*
		 * InputStream is = new ByteArrayInputStream(model.getTmpl_cert());
		 * InputStream as = new ByteArrayInputStream(model1.getTmpl_cert());
		 */
		InputStream is = new FileInputStream("D:\\a.xls");
		InputStream as = new FileInputStream("D:\\b.xls");
		HSSFWorkbook wb = new HSSFWorkbook(is);
		HSSFWorkbook wb1 = new HSSFWorkbook(as);
		// 创建HSSFSheet对象
		HSSFSheet sheet = wb.getSheetAt(0);
		HSSFSheet sheet1 = wb.getSheetAt(0);
		System.out.println("time1" + (System.currentTimeMillis() - l));
		he.mergeHSSFSheet(wb, sheet, sheet1, true, 1);
		OutputStream os = new FileOutputStream("D:\\123.xls");
		wb.setPrintArea(0, sheet.getRow(0).getFirstCellNum(), sheet.getRow(0).getLastCellNum() - 1,
				sheet.getFirstRowNum(), sheet.getLastRowNum());
		wb.write(os);
		System.out.println("time1" + (System.currentTimeMillis() - l));

	}

	/**
	 * 二维码内容查询
	 */
	public String getErCode(String id) {

		String erInfo = "新余钢铁股份有限公司    ";
		QcmZbsDataOrd ord = this.getMapper(QcmZbsDataOrdMapper.class).findById(id);
		if (ord != null) {
			List<QcmZbsDataMat> mats = this.getMapper(QcmZbsDataMatMapper.class).findWithCondition(null,
					"CRET_NO='" + id + "'", "MATERIAL_NO", 0, 0);
			for (QcmZbsDataMat mat : mats) {
				if ("1".equals(ord.getIs_batch())) {
					erInfo += mat.getBatch_no() + "/" + mat.getSteel_name() + "." + mat.getDelivery_state_desc() + "/"
							+ mat.getThick() + "*" + mat.getWidth();

				} else {
					erInfo += mat.getMaterial_no() + "/" + mat.getSteel_name() + "." + mat.getDelivery_state_desc()
							+ "/" + mat.getThick() + "*" + mat.getWidth();

				}
				if (mat.getLength() != null) {
					erInfo += "*" + mat.getLength();
				}

				SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd");
				Date cfnm_date=ord.getCfnm_date();
				
				erInfo += "/" + sDateFormat.format(cfnm_date)+"                                       ";

			}

		}
		return erInfo;
	}
	/**
	 * 质保书开具统计
	 * @param sum
	 * @return
	 */
	public List<ResultModel> getRecord(CommonPage<QcmZbsDataOrd> sum){
		List<ResultModel> listrm=new ArrayList<>();
		ResultModel rm=new ResultModel();
		ResultModel rm1=new ResultModel();
		listrm.add(rm);
		listrm.add(rm1);
		String con="";
		List<String> str=new ArrayList<>();
		QcmZbsDataOrd qzd=sum.getObject();
		try {
			if (!DataHelper.IsNullOrSpace(qzd.getCreate_name())) {
				con+= " and CREATE_NAME like '%"+qzd.getCreate_name()+"%'";
			}
			if (!DataHelper.IsNullOrSpace(sum.getStartTime())) {
				con+=" and CREATE_TIME>=to_date(concat('"+sum.getStartTime()+"',' 00:00:00'),'yyyy-MM-dd HH24:mi:ss')"; 
			}
			if (!DataHelper.IsNullOrSpace(sum.getEndTime())) {
				con+=" and CREATE_TIME<=to_date(concat('"+sum.getEndTime()+"',' 23:59:59'),'yyyy-MM-dd HH24:mi:ss') ";
			}
			List<HashMap<String, String>> listqzd=this.getMapper(QcmZbsDataOrdMapper.class).getRecord(con);
			List<String> liststr=new ArrayList<>();
            for (HashMap<String, String> qle : listqzd) {
		    	if (!str.contains(qle.get("CREATE_NAME"))) {
		    		liststr.add(qle.get("CREATE_NAME"));
		    		str.add(qle.get("CREATE_NAME"));
				}
			}
            rm1.setData(liststr);
		    rm.setState("200");
			rm.setData(listqzd);
		} catch (Exception e) {
			rm.setState("500");
			rm.setErrorInfo(e.getMessage());
		}
		return listrm;
	}
	
	public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = QcmZbsBillServiceImpl.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
	/**
	 * 质保书取消确认功能
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel quoteSure(CommonPage<QcmZbsDataOrd> sum) throws Exception{
		ResultModel rm=new ResultModel();
		try {
			if (sum==null) {
				rm.setState("500");
				rm.setMsgInfo("请传入参数");
				return rm;
			}
			List<QcmZbsDataOrd> ords=sum.getObjectList();
			if (ords==null || ords.size()<1) {
				rm.setState("500");
				rm.setMsgInfo("请传入参数");
				return rm;
			}
			for (QcmZbsDataOrd ord : ords) {
				ord=this.getMapper(QcmZbsDataOrdMapper.class).findById(ord.getCret_no());
				Long seq=this.getMapper(QcmZbsDataPrtMapper.class).findMaxSeq(ord.getCret_no());
				if (seq!=null) {
					rm.setState("500");
					rm.setMsgInfo("质保书["+ord.getCret_no()+"]已经打印，不能取消确认，请与打印人员["+ord.getPrint_id()+"]联系");
					return rm;
				}
				if ("1".equals(ord.getIs_send())) {
					ord.setIs_send("0");
					ord.setSend_name(null);
					ord.setSend_time(null);
					this.getMapper(QcmZbsDataOrdMapper.class).update(ord);
				}
				
				
				
			}
				
			
			rm.setState("200");;
			rm.setMsgInfo("取消确认成功");
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("质保书取消确认失败");
		}
		
		return rm;		
	}
	
}
