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

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import liquibase.pro.packaged.P;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.pl.product.entity.ProductEntity;
import org.springblade.modules.pl.product.service.IProductService;
import org.springblade.modules.pl.productBatch.entity.ProductBatchEntity;
import org.springblade.modules.pl.productBatch.vo.ProductBatchVO;
import org.springblade.modules.pl.productBatch.excel.ProductBatchExcel;
import org.springblade.modules.pl.productBatch.mapper.ProductBatchMapper;
import org.springblade.modules.pl.productBatch.service.IProductBatchService;
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.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.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 产品入库批次表 服务实现类
 *
 * @author BladeX
 * @since 2023-12-05
 */
@Service
public class ProductBatchServiceImpl extends BaseServiceImpl<ProductBatchMapper, ProductBatchEntity> implements IProductBatchService {

	@Resource
	private  IProductModelService productModelService;

	@Resource
	private  IProductService productService;

	@Resource
	private IProductProcessService productProcessService;

	@Override
	public IPage<ProductBatchVO> selectProductBatchPage(IPage<ProductBatchVO> page, ProductBatchVO productBatch) {
		return page.setRecords(baseMapper.selectProductBatchPage(page, productBatch));
	}


	@Override
	public List<ProductBatchExcel> exportProductBatch(Wrapper<ProductBatchEntity> queryWrapper) {
		List<ProductBatchExcel> productBatchList = baseMapper.exportProductBatch(queryWrapper);
		//productBatchList.forEach(productBatch -> {
		//	productBatch.setTypeName(DictCache.getValue(DictEnum.YES_NO, ProductBatch.getType()));
		//});
		return productBatchList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R submit(ProductBatchVO productBatch) {
		BladeUser user = AuthUtil.getUser();
		if(user.getUserCategory()==2){
			productBatch.setFactoryId(user.getFactoryId());
		}
		if(productBatch.getId()==null){
			ProductModelEntity productModel = productModelService.getById(productBatch.getProductModelId());
			if(productBatch.getDetails().size()>productModel.getInStockNum()){
				return R.fail("入库产品数据不符要求，请检查后在试");
			}

			for(ProductEntity productEntity : productBatch.getDetails()){
				ProductEntity product = productService.getOne(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getFactoryId,productBatch.getFactoryId()).eq(ProductEntity::getQrCode,productEntity.getQrCode()));
				if(productModel.getIsDirectStorage()==0){
					if(product == null){
						return R.fail("产品二维码："+productEntity.getQrCode()+"不存在，请更换产品");
					}
					if(product.getStatus()!=2){
						return R.fail("产品二维码："+productEntity.getQrCode()+"无法入库，请更换产品");
					}
					if(product.getAiStatus()==0||product.getAiStatus()==1){
						return R.fail("产品二维码："+productEntity.getQrCode()+"AI识别未处理，无法入库，请更换产品");
					}
					if(!Objects.equals(product.getProductModelId(), productBatch.getProductModelId())){
						return R.fail("产品二维码："+productEntity.getQrCode()+"与当前批次的型号不符，请更换产品");
					}
//					if(StringUtil.isBlank(productEntity.getColdQrCode())){
//						return R.fail("产品二维码："+productEntity.getQrCode()+"的冷板二维码不能为空");
//					}
//					if(productModel.getIsEnableProcess()==1){
//						long count = productProcessService.count(Wrappers.<ProductProcessEntity>lambdaQuery().eq(ProductProcessEntity::getProductId,productEntity.getId()));
//
//					}
					productEntity.setId(product.getId());
				}else{
					if(product != null){
//						return R.fail("产品二维码："+productEntity.getQrCode()+"已存在，无法直接入库");
						if(product.getStatus()!=2){
							return R.fail("产品二维码："+productEntity.getQrCode()+"无法入库，请更换产品");
						}
						if(product.getAiStatus()==0||product.getAiStatus()==1){
							return R.fail("产品二维码："+productEntity.getQrCode()+"AI识别未处理，无法入库，请更换产品");
						}
						if(!Objects.equals(product.getProductModelId(), productBatch.getProductModelId())){
							return R.fail("产品二维码："+productEntity.getQrCode()+"与当前批次的型号不符，请更换产品");
						}
						productEntity.setId(product.getId());
					}else{
						productEntity.setSource(2);
					}
					productEntity.setFactoryId(productModel.getFactoryId());
					productEntity.setProductModelId(productModel.getId());
					productEntity.setProductName(productModel.getProductName());
					productEntity.setProductModel(productModel.getProductModel());

				}
				productEntity.setScanDate(DateUtil.formatDate(new Date()));
				productEntity.setInStockDate(new Date());
				productEntity.setStatus(3);
			}
			String batchNo = productBatch.getDetails().get(0).getQrCode().substring(0,21)+DateUtil.format(new Date(),"yyyyMMdd")+"00001";
			ProductBatchEntity productBatchEntity = new ProductBatchEntity();
			productBatchEntity.setFactoryId(productBatch.getFactoryId());
			productBatchEntity.setBatchNo(batchNo);
			productBatchEntity.setProductModelId(productModel.getId());
			productBatchEntity.setProductName(productModel.getProductName());
			productBatchEntity.setProductModel(productModel.getProductModel());
			productBatchEntity.setClientId(productBatch.getClientId());
			productBatchEntity.setOrderNo(productBatch.getOrderNo());
			this.save(productBatchEntity);

			for(ProductEntity productEntity : productBatch.getDetails()){
				productEntity.setBatchId(productBatchEntity.getId());
				productEntity.setBatchNo(productBatchEntity.getBatchNo());
				productEntity.setClientId(productBatch.getClientId());
				productEntity.setOrderNo(productBatchEntity.getOrderNo());
				productService.saveOrUpdate(productEntity);
			}

			return R.success("操作成功·");
		}else{
			ProductModelEntity productModel = productModelService.getById(productBatch.getProductModelId());

			for(ProductEntity productEntity : productBatch.getDetails()){
				if(productEntity.getId() == null){
					return R.fail("产品数据异常，请联系管理员");
				}
				ProductEntity product = productService.getById(productEntity.getId());
				if(product == null){
					return R.fail("产品二维码："+productEntity.getQrCode()+"不存在，请更换产品");
				}
				if(!Objects.equals(product.getProductModelId(), productBatch.getProductModelId())){
					return R.fail("产品二维码："+productEntity.getQrCode()+"与当前批次的型号不符，请更换产品");
				}
				if(product.getStatus()!=3){
					return R.fail("产品二维码："+productEntity.getQrCode()+"未入库，无法修改");
				}
				productEntity.setId(product.getId());
				productEntity.setFactoryId(productModel.getFactoryId());
				productEntity.setProductModelId(productModel.getId());
				productEntity.setProductName(productModel.getProductName());
				productEntity.setProductModel(productModel.getProductModel());
				productEntity.setScanDate(DateUtil.formatDate(new Date()));
				productEntity.setInStockDate(new Date());
				productEntity.setStatus(3);
			}
//			String batchNo = productBatch.getDetails().get(0).getQrCode().substring(0,21)+DateUtil.format(new Date(),"yyyyMMdd")+"00001";
			ProductBatchEntity productBatchEntity = new ProductBatchEntity();
			productBatchEntity.setId(productBatch.getId());
//			productBatchEntity.setFactoryId(productBatch.getFactoryId());
//			productBatchEntity.setBatchNo(batchNo);
//			productBatchEntity.setProductModelId(productModel.getId());
//			productBatchEntity.setProductName(productModel.getProductName());
//			productBatchEntity.setProductModel(productModel.getProductModel());
			productBatchEntity.setClientId(productBatch.getClientId());
			productBatchEntity.setOrderNo(productBatch.getOrderNo());
			this.updateById(productBatchEntity);

			for(ProductEntity productEntity : productBatch.getDetails()){
//				productEntity.setBatchId(productBatchEntity.getId());
//				productEntity.setBatchNo(productBatchEntity.getBatchNo());
				productEntity.setClientId(productBatch.getClientId());
				productEntity.setOrderNo(productBatchEntity.getOrderNo());
				productService.updateById(productEntity);
			}

			return R.success("操作成功·");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R change(ProductBatchVO productBatch) {
		ProductModelEntity productModel = productModelService.getById(productBatch.getProductModelId());
		List<ProductEntity> changeProductList = new ArrayList<>();
		for(ProductEntity productEntity : productBatch.getDetails()){
			if(productEntity.getId() == null){
				return R.fail("产品数据异常，请联系管理员");
			}
			if(StringUtil.isNotBlank(productEntity.getNewQrCode())){
				if(productEntity.getNewQrCode().equals(productEntity.getQrCode())){
					return R.fail("产品二维码："+productEntity.getNewQrCode()+"不能与原二维码相同");
				}
				ProductEntity product = productService.getOne(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getFactoryId,productBatch.getFactoryId()).eq(ProductEntity::getQrCode,productEntity.getNewQrCode()));
				if(product == null){
					return R.fail("产品二维码："+productEntity.getNewQrCode()+"不存在，请更换产品");
				}
				if(!Objects.equals(product.getProductModelId(), productBatch.getProductModelId())){
					return R.fail("产品二维码："+productEntity.getNewQrCode()+"与当前批次的型号不符，请更换产品");
				}
				if(product.getStatus()!=2){
					return R.fail("产品二维码："+productEntity.getNewQrCode()+"无法入库，无法变更");
				}
				changeProductList.add(productEntity);
			}
		}
		if(changeProductList.size()==0){
			return R.fail("请填写需要变更的产品新二维码");
		}
		ProductBatchEntity productBatchEntity = this.getById(productBatch.getId());
		if(productBatchEntity==null){
			return R.fail("数据异常，请联系管理员");
		}
		for(ProductEntity productEntity : changeProductList){
			ProductEntity oldProduct = productService.getOne(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getFactoryId,productBatch.getFactoryId()).eq(ProductEntity::getQrCode,productEntity.getQrCode()));
			LambdaUpdateWrapper<ProductEntity> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.set(ProductEntity::getScanDate,null);
			updateWrapper.set(ProductEntity::getInStockDate,null);
			updateWrapper.set(ProductEntity::getStatus,2);
			updateWrapper.set(ProductEntity::getBatchId,null);
			updateWrapper.set(ProductEntity::getBatchNo,null);
			updateWrapper.set(ProductEntity::getClientId,null);
			updateWrapper.set(ProductEntity::getOrderNo,null);
			updateWrapper.set(ProductEntity::getWaterCooling,null);
			updateWrapper.set(ProductEntity::getAirtight,null);
			updateWrapper.set(ProductEntity::getColdQrCode,null);
			updateWrapper.eq(ProductEntity::getId,oldProduct.getId());
			productService.update(updateWrapper);


			ProductEntity newProduct = productService.getOne(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getFactoryId,productBatch.getFactoryId()).eq(ProductEntity::getQrCode,productEntity.getNewQrCode()));
			productEntity.setOldQrCode(productEntity.getQrCode());
			productEntity.setQrCode(productEntity.getNewQrCode());
			productEntity.setId(newProduct.getId());
			productEntity.setFactoryId(productModel.getFactoryId());
			productEntity.setProductModelId(productModel.getId());
			productEntity.setProductName(productModel.getProductName());
			productEntity.setProductModel(productModel.getProductModel());
			productEntity.setScanDate(DateUtil.formatDate(new Date()));
			productEntity.setInStockDate(new Date());
			productEntity.setStatus(3);
			productEntity.setBatchId(productBatchEntity.getId());
			productEntity.setBatchNo(productBatchEntity.getBatchNo());
			productEntity.setClientId(productBatch.getClientId());
			productEntity.setOrderNo(productBatchEntity.getOrderNo());
			productService.updateById(productEntity);
		}

		return null;
	}

}
