/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.pl.inspectionRecords.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.json.JSONArray;
import org.springblade.api.utils.BaidubceUtils;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.pl.equipment.entity.EquipmentEntity;
import org.springblade.modules.pl.goods.entity.GoodsEntity;
import org.springblade.modules.pl.goods.entity.GoodsMaterialEntity;
import org.springblade.modules.pl.goods.service.IGoodsMaterialService;
import org.springblade.modules.pl.goods.service.IGoodsService;
import org.springblade.modules.pl.inspectionRecords.entity.InspectionDetailsEntity;
import org.springblade.modules.pl.inspectionRecords.entity.InspectionRecordsEntity;
import org.springblade.modules.pl.inspectionRecords.service.IInspectionDetailsService;
import org.springblade.modules.pl.inspectionRecords.vo.InspectionRecordsVO;
import org.springblade.modules.pl.inspectionRecords.excel.InspectionRecordsExcel;
import org.springblade.modules.pl.inspectionRecords.mapper.InspectionRecordsMapper;
import org.springblade.modules.pl.inspectionRecords.service.IInspectionRecordsService;
import org.springblade.modules.pl.productModel.entity.ProductModelEntity;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 点检记录 服务实现类
 *
 * @author BladeX
 * @since 2024-02-03
 */
@Service
public class InspectionRecordsServiceImpl extends BaseServiceImpl<InspectionRecordsMapper, InspectionRecordsEntity> implements IInspectionRecordsService {

	@Resource
	IGoodsService goodsService;
	@Resource
	IGoodsMaterialService goodsMaterialService;
	@Resource
	IInspectionDetailsService inspectionDetailsService;

	@Override
	public IPage<InspectionRecordsVO> selectInspectionRecordsPage(IPage<InspectionRecordsVO> page, InspectionRecordsVO inspectionRecords) {
		return page.setRecords(baseMapper.selectInspectionRecordsPage(page, inspectionRecords));
	}


	@Override
	public List<InspectionRecordsExcel> exportInspectionRecords(Wrapper<InspectionRecordsEntity> queryWrapper) {
		List<InspectionRecordsExcel> inspectionRecordsList = baseMapper.exportInspectionRecords(queryWrapper);
		//inspectionRecordsList.forEach(inspectionRecords -> {
		//	inspectionRecords.setTypeName(DictCache.getValue(DictEnum.YES_NO, InspectionRecords.getType()));
		//});
		return inspectionRecordsList;
	}

	@Override
	public InspectionRecordsEntity submit(String goodsCode, String link, EquipmentEntity equipmentEntity) {
		GoodsEntity goods = goodsService.getOne(Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getGoodsCode,goodsCode).eq(GoodsEntity::getFactoryId,equipmentEntity.getFactoryId()),false);
		List<GoodsMaterialEntity> goodsMaterialEntities = new ArrayList<>();
		List<String> submaterialList = new ArrayList<>();
		InspectionRecordsEntity inspectionRecords = new InspectionRecordsEntity();
		inspectionRecords.setFactoryId(equipmentEntity.getFactoryId());
		inspectionRecords.setEquipmentId(equipmentEntity.getId());
		inspectionRecords.setEqSn(equipmentEntity.getEqSn());
		inspectionRecords.setStatus(2);
		inspectionRecords.setGoodsImage(link);
		if(goods==null){
			inspectionRecords.setGoodsCode(goodsCode);
			inspectionRecords.setOcrResult("商品不存在");
		}else{
			inspectionRecords.setGoodsId(goods.getId());
			inspectionRecords.setGoodsName(goods.getGoodsName());
			inspectionRecords.setGoodsCode(goods.getGoodsCode());
			try {
				goodsMaterialEntities = goodsMaterialService.list(Wrappers.<GoodsMaterialEntity>lambdaQuery().eq(GoodsMaterialEntity::getGoodsId,goods.getId()));
				Map<String,String> goodsMaterialDict =goodsMaterialEntities.stream().collect(Collectors.toMap(GoodsMaterialEntity::getCode, GoodsMaterialEntity::getName));
				//调用ocr获取结果
				try {
					JSONArray ocrResult = BaidubceUtils.imageOcr(link);
					for(int i=0;i<ocrResult.length();i++){
						String words = ocrResult.getJSONObject(i).getString("words");
						//将符合规则的物料code添加到待校验物料List中
						if(verifyOcrBarCode(words,goodsMaterialEntities)){
							submaterialList.add(words);
						}
					}
					inspectionRecords.setOcrDetails(ocrResult.toString());

					if(submaterialList.size()>0){
						StringBuilder ocrSuccess = new StringBuilder();
						StringBuilder ocrFail = new StringBuilder();
						for(String code:submaterialList){
							if(goodsMaterialDict.get(code)!=null){
								//正确识别的物料
								ocrSuccess.append(goodsMaterialDict.get(code)).append(":").append(code).append("；");
								goodsMaterialDict.remove(code);
							}else{
								//未识别的物料码值
								ocrFail.append("错误" + ":").append(code).append("；");
							}
						}
						String resutl = String.join(",", goodsMaterialDict.values());
						inspectionRecords.setOcrSuccess(ocrSuccess.toString());
						inspectionRecords.setOcrFail(ocrFail.toString());
						inspectionRecords.setOcrResult(StringUtil.isNotBlank(resutl)?resutl+"物料未匹配":"物料匹配成功");
						inspectionRecords.setStatus(StringUtil.isNotBlank(resutl)?2:1);
					}else{
						inspectionRecords.setOcrResult("未检测到物料");
					}
				}catch (Exception e){
					inspectionRecords.setOcrResult(e.getMessage());
				}

			}catch (Exception e){
				inspectionRecords.setOcrResult(e.getMessage());
			}
		}
		this.save(inspectionRecords);
		if(goodsMaterialEntities.size()>0){
			List<InspectionDetailsEntity> detailsEntities = new ArrayList<>();
			String submaterialCodes = ","+String.join(",", submaterialList)+",";
			for(GoodsMaterialEntity goodsMaterial : goodsMaterialEntities){
				InspectionDetailsEntity inspectionDetailsEntity = new InspectionDetailsEntity();
				inspectionDetailsEntity.setInspectionRecordsId(inspectionRecords.getId());
				inspectionDetailsEntity.setMaterialId(goodsMaterial.getId());
				inspectionDetailsEntity.setMaterialName(goodsMaterial.getName());
				inspectionDetailsEntity.setStatus(2);
				if(submaterialCodes.contains(","+goodsMaterial.getCode()+",")){
					inspectionDetailsEntity.setMaterialCode(goodsMaterial.getCode());
					inspectionDetailsEntity.setStatus(1);
				}
				detailsEntities.add(inspectionDetailsEntity);
			}
			inspectionDetailsService.saveBatch(detailsEntities);
		}
		return inspectionRecords;
	}

	public static void main(String[] args) {
		Map<String,String> goodsMaterialDict = new HashMap<>();
		System.out.println( String.join(",", goodsMaterialDict.values()));
		goodsMaterialDict.put("123123","dasd撒旦");
		System.out.println( String.join(",", goodsMaterialDict.values()));
		goodsMaterialDict.remove("123123");
		System.out.println( String.join(",", goodsMaterialDict.values()));

	}


	private boolean verifyOcrBarCode(String value,List<GoodsMaterialEntity> goodsMaterialEntities){
		if(value.length()==12 || value.length()==13 || value.length()==15){
			if(!value.contains("-")){
				for (GoodsMaterialEntity goodsMaterialEntity : goodsMaterialEntities) {
					String barCode = goodsMaterialEntity.getCode();
					String code = barCode.substring(0, 2);
					System.out.println(value + "," + code);
					if (value.indexOf(code) == 0) {
						return true;
					}
				}
			}
		}
		return false;
	}

}
