/*
 *      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.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import liquibase.pro.packaged.E;
import org.apache.http.client.utils.HttpClientUtils;
import org.springblade.common.utils.PostGet;
import org.springblade.core.http.util.HttpUtil;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.FileUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.pl.equipment.entity.EquipmentEntity;
import org.springblade.modules.pl.factory.entity.FactoryEntity;
import org.springblade.modules.pl.product.entity.ProductEntity;
import org.springblade.modules.pl.product.entity.ProductImageRecordEntity;
import org.springblade.modules.pl.product.service.IProductService;
import org.springblade.modules.pl.product.vo.ProductImageRecordVO;
import org.springblade.modules.pl.product.excel.ProductImageRecordExcel;
import org.springblade.modules.pl.product.mapper.ProductImageRecordMapper;
import org.springblade.modules.pl.product.service.IProductImageRecordService;
import org.springblade.modules.pl.product.wrapper.ProductImageRecordWrapper;
import org.springblade.modules.pl.productModel.entity.ProductModelEntity;
import org.springblade.modules.pl.productModel.service.IProductModelService;
import org.springblade.modules.pl.productProcess.entity.ProductProcessEntity;
import org.springblade.modules.pl.productProcess.service.IProductProcessService;
import org.springblade.modules.resource.builder.OssBuilder;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品表 服务实现类
 *
 * @author BladeX
 * @since 2023-12-07
 */
@Service
public class ProductImageRecordServiceImpl extends BaseServiceImpl<ProductImageRecordMapper, ProductImageRecordEntity> implements IProductImageRecordService {

	@Resource
	private IProductService productService;
	@Resource
	private IProductModelService productModelService;
	@Resource
	private IProductProcessService productProcessService;

	@Resource
	private OssBuilder ossBuilder;

	@Value("${blade.ai.url}")
	private String aiUrl;

	@Override
	public IPage<ProductImageRecordVO> selectProductImageRecordPage(IPage<ProductImageRecordVO> page, ProductImageRecordVO productImageRecord) {
		return page.setRecords(baseMapper.selectProductImageRecordPage(page, productImageRecord));
	}


	@Override
	public List<ProductImageRecordExcel> exportProductImageRecord(Wrapper<ProductImageRecordEntity> queryWrapper) {
		List<ProductImageRecordExcel> productImageRecordList = baseMapper.exportProductImageRecord(queryWrapper);
		//productImageRecordList.forEach(productImageRecord -> {
		//	productImageRecord.setTypeName(DictCache.getValue(DictEnum.YES_NO, ProductImageRecord.getType()));
		//});
		return productImageRecordList;
	}

	@Override
	public ProductImageRecordVO submit(String productCode, EquipmentEntity equipmentEntity, ProductImageRecordEntity productImageRecord, BladeFile bladeFile, FactoryEntity factory) {
		ProductEntity productEntity = null;
		ProductModelEntity productModel = null;
		//ai识别状态 -1无需识别 0未识别 1ng 2ok 3人工ok
		int aiStatus = -1;
		productImageRecord.setEquipmentId(equipmentEntity.getId());
		productImageRecord.setEqSn(equipmentEntity.getEqSn());
		if(productCode.length()<25){
			productImageRecord.setStatus(2);
			productImageRecord.setMessage("产品码'"+productCode+"'小于18位");
		}else{
			String code = productCode.substring(8,12);
			productModel = productModelService.getOne(Wrappers.<ProductModelEntity>lambdaQuery().eq(ProductModelEntity::getProductSpec,code).eq(ProductModelEntity::getFactoryId,equipmentEntity.getFactoryId()),false);
			if(productModel==null){
				productImageRecord.setStatus(2);
				productImageRecord.setMessage("未找到型号码为'"+code+"'的数据");
			}else{
				productEntity = productService.getOne(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getQrCode,productCode).eq(ProductEntity::getFactoryId,equipmentEntity.getFactoryId()),false);
				if(productModel.getIsEnableProcess()==1){
					if(productEntity ==null){
						productImageRecord.setStatus(2);
						productImageRecord.setMessage("产品不存在，请通过工序进行建档");
					}else if(productEntity.getStatus()!=2 && productEntity.getStatus()!=-1 ){
						productImageRecord.setStatus(2);
						productImageRecord.setMessage("产品"+(productEntity.getStatus()==1?"正在维修中,":(productEntity.getStatus()==0?"已作废,":"已入库,"))+"无法下线");
					}else if( productEntity.getAiStatus()!=null && (productEntity.getAiStatus()==0 || productEntity.getAiStatus()==1) ){
						productImageRecord.setStatus(2);
						productImageRecord.setMessage("产品"+(productEntity.getAiStatus()==0 ?"AI未识别-待处理,":(productEntity.getAiStatus()==1?"NG待处理,":""))+"无法下线");
					}else{
						long count = productProcessService.count(Wrappers.<ProductProcessEntity>lambdaQuery().eq(ProductProcessEntity::getProductId,productEntity.getId()));
						if(count>0){
							ProductProcessEntity processEntity = productProcessService.getOne(Wrappers.<ProductProcessEntity>lambdaQuery()
								.eq(ProductProcessEntity::getProductId,productEntity.getId())
								.eq(ProductProcessEntity::getStatus,0)
								.orderByAsc(ProductProcessEntity::getSort),false);
							if(processEntity!=null){
								if(processEntity.getIsPhotograph()==1){
									if(processEntity.getIsDownline()==1){
										//下线拍照
										if(productModel.getIsAi()==1){
											aiStatus = 0;
											try {
												JSONObject param = new JSONObject();
												param.put("action","detect");
												param.put("type",productModel.getProductModel()+(productEntity==null?"-1":"-0"));
												param.put("path",bladeFile.getLink());
												String result = PostGet.getResult(aiUrl+"/ws_init",param.toJSONString(),true);
												JSONObject jsonObject = JSONObject.parseObject(result);
												if(jsonObject.get("status")!=null && jsonObject.getInteger("status")==200){
													String filePath = jsonObject.getString("path");
													File file = new File(filePath);
													if(file.exists()){
														aiStatus = "OK".equals(jsonObject.get("result"))?2:1;
														String fileName= "upload/"+(factory==null?"000000":factory.getCode())+"/" + DateUtil.today() + "/"+productCode+"/" + StringUtil.randomUUID() + "." + FileUtil.getFileExtension(file.getName());
														BladeFile aiFile = ossBuilder.template(equipmentEntity.getTenantId(),"minio").putFile(fileName, Files.newInputStream(Paths.get(filePath)));
														productImageRecord.setProductAiImage(aiFile.getLink());
														file.delete();
													}
													else{
														productImageRecord.setStatus(2);
														productImageRecord.setMessage("拍照成功,AI识别接口调用异常-文件不存在");
													}
												}else{
													productImageRecord.setStatus(2);
													productImageRecord.setMessage("拍照成功,AI识别接口调用失败"+jsonObject.get("result"));
												}
											}catch (Exception e){
												e.printStackTrace();
												log.error("AI识别接口调用异常",e);
												productImageRecord.setStatus(2);
												productImageRecord.setMessage("拍照成功,AI识别接口调用异常");
											}
										}
										if(StringUtil.isBlank(productEntity.getBackImg())){
											productEntity.setBackImg(productImageRecord.getProductImage());
											productEntity.setBackAiImg(productImageRecord.getProductAiImage());
											productEntity.setStatus(2);
											productEntity.setAiStatus(aiStatus);

											processEntity.setImages((StringUtil.isBlank(processEntity.getImages())?"":processEntity.getImages()+",")+productImageRecord.getProductImage());
										}else{
											productEntity.setFrontImg(productImageRecord.getProductImage());
											productEntity.setFrontAiImg(productImageRecord.getProductAiImage());
											productEntity.setStatus(2);
											productEntity.setAiStatus(aiStatus);

											processEntity.setImages((StringUtil.isBlank(processEntity.getImages())?"":processEntity.getImages()+",")+productImageRecord.getProductImage());
											processEntity.setStatus(1);
										}

									}else{
										//工序拍照
										processEntity.setImages((StringUtil.isBlank(processEntity.getImages())?"":processEntity.getImages()+",")+productImageRecord.getProductImage());
										processEntity.setStatus(1);
									}

									productService.updateById(productEntity);
									productProcessService.updateById(processEntity);
									if(aiStatus==0 ||  aiStatus==1){
										productImageRecord.setStatus(2);
									}

									productImageRecord.setProductId(productEntity.getId());
									if(aiStatus==-1){
										productImageRecord.setMessage("工序拍照成功");
									}else if(aiStatus==1 || aiStatus==2){
										productImageRecord.setMessage("工序拍照成功，产品识别"+(aiStatus==2?"OK":"NG"));
									}
								}else{
									productImageRecord.setStatus(2);
									productImageRecord.setMessage("该产品当前执行工序非拍照工序，请前往小程序进行操作");
								}
							}else{
								productImageRecord.setStatus(2);
								productImageRecord.setMessage("已完成全部工序");
							}
						}else{
							productImageRecord.setStatus(2);
							productImageRecord.setMessage("产品工序数据异常");
						}


					}


				}else{
					if(productEntity!=null && productEntity.getStatus()!=2){
						productImageRecord.setStatus(2);
						productImageRecord.setMessage("产品"+(productEntity.getStatus()==1?"正在维修中,":(productEntity.getStatus()==0?"已作废,":"已入库,"))+"无法下线");
					}else if(productEntity!=null && productEntity.getAiStatus()!=null && (productEntity.getAiStatus()==0 || productEntity.getAiStatus()==1) ){
						productImageRecord.setStatus(2);
						productImageRecord.setMessage("产品"+(productEntity.getAiStatus()==0 ?"AI未识别-待处理,":(productEntity.getAiStatus()==1?"NG待处理,":""))+"无法下线");
					}else{
						if(productModel.getIsAi()==1){
							aiStatus = 0;
							try {
//						Map<String,Object> param = new HashMap<>();
//						param.put("action","detect");
//						param.put("type",productEntity==null?"origin-background":"origin-front");
//						param.put("path",bladeFile.getLink());
								JSONObject param = new JSONObject();
								param.put("action","detect");
								param.put("type",productModel.getProductModel()+(productEntity==null?"-1":"-0"));
								param.put("path",bladeFile.getLink());

//							String result = HttpUtil.postJson("http://127.0.0.1:3300/ws_init",param.toJSONString());
								String result = PostGet.getResult(aiUrl+"/ws_init",param.toJSONString(),true);
								JSONObject jsonObject = JSONObject.parseObject(result);
								if(jsonObject.get("status")!=null && jsonObject.getInteger("status")==200){
									String filePath = jsonObject.getString("path");
									File file = new File(filePath);
									if(file.exists()){
										aiStatus = "OK".equals(jsonObject.get("result"))?2:1;
										String fileName= "upload/"+(factory==null?"000000":factory.getCode())+"/" + DateUtil.today() + "/"+productCode+"/" + StringUtil.randomUUID() + "." + FileUtil.getFileExtension(file.getName());
										BladeFile aiFile = ossBuilder.template(equipmentEntity.getTenantId(),"minio").putFile(fileName, Files.newInputStream(Paths.get(filePath)));
										productImageRecord.setProductAiImage(aiFile.getLink());
										file.delete();
									}
									else{
										productImageRecord.setStatus(2);
										productImageRecord.setMessage("拍照成功,AI识别接口调用异常-文件不存在");
									}
								}else{
									productImageRecord.setStatus(2);
									productImageRecord.setMessage("拍照成功,AI识别接口调用失败"+jsonObject.get("result"));
								}
							}catch (Exception e){
								e.printStackTrace();
								log.error("AI识别接口调用异常",e);
								productImageRecord.setStatus(2);
								productImageRecord.setMessage("拍照成功,AI识别接口调用异常");
							}
						}
					}
					if(productImageRecord.getStatus()==2 && aiStatus==-1){
						this.save(productImageRecord);
						ProductImageRecordVO productImageRecordVO = ProductImageRecordWrapper.build().entityVO(productImageRecord);
						productImageRecordVO.setAiStatus(aiStatus);
//					productImageRecordVO.setProductEntity(productEntity);
						return productImageRecordVO;
					}
					if(aiStatus==0 ||  aiStatus==1){
						productImageRecord.setStatus(2);
					}

					if(productEntity==null){
						productEntity = new ProductEntity();
						productEntity.setTenantId(productModel.getTenantId());
						productEntity.setFactoryId(productModel.getFactoryId());
//								productEntity.setClientId(productModel.getClientId());
						productEntity.setProductModelId(productModel.getId());
						productEntity.setProductName(productModel.getProductName());
						productEntity.setProductModel(productModel.getProductModel());
						productEntity.setBackImg(productImageRecord.getProductImage());
						productEntity.setBackAiImg(productImageRecord.getProductAiImage());
						productEntity.setQrCode(productCode);
						productEntity.setStatus(2);
						productEntity.setAiStatus(aiStatus);
						productEntity.setSource(1);
						productService.save(productEntity);
					}else{
						if(productEntity.getStatus()==2){
							productEntity.setFrontImg(productImageRecord.getProductImage());
							productEntity.setFrontAiImg(productImageRecord.getProductAiImage());
							productEntity.setStatus(2);
							productEntity.setAiStatus(aiStatus);
							productService.updateById(productEntity);
						}
					}
					productImageRecord.setProductId(productEntity.getId());
					if(aiStatus==-1){
						productImageRecord.setMessage("拍照成功");
					}else if(aiStatus==1 || aiStatus==2){
						productImageRecord.setMessage("拍照成功，产品识别"+(aiStatus==2?"OK":"NG"));
					}
				}
			}
		}
		if(productEntity!=null && productModel!=null && productModel.getIsPushTripartite()==1){
			if(productEntity.getAiStatus()==-1 || productEntity.getAiStatus()==2){
				productService.pushTripartite(productCode,productEntity.getAiStatus()==-1?productImageRecord.getProductImage():productImageRecord.getProductAiImage(),productModel,"OK");
			}
		}
		this.save(productImageRecord);
		ProductImageRecordVO productImageRecordVO = ProductImageRecordWrapper.build().entityVO(productImageRecord);
		productImageRecordVO.setAiStatus(aiStatus);
//		productImageRecordVO.setProductEntity(productEntity);
		return productImageRecordVO;
	}

	public static void main(String[] args) throws Exception {
		Map<String,String> param = new HashMap<>();
		param.put("action","detect");
		param.put("type","294AD-250A-0");
		param.put("path","https://ai.my-123.cn/pic/product-line/upload/cs/20240329/000020009528-010010142308/a14cb318fc9a82a4f873fcde9d607226.jpg");
		String result = PostGet.getResult("http://124.220.190.147:3300/ws_init",JSONObject.toJSONString(param),true);
		System.out.println(result);
	}
}
