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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.redisson.api.RedissonClient;
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.BeanUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.pl.client.service.IClientService;
import org.springblade.modules.pl.process.entity.ProcessEntity;
import org.springblade.modules.pl.process.entity.ProcessItemEntity;
import org.springblade.modules.pl.process.service.IProcessItemService;
import org.springblade.modules.pl.process.service.IProcessService;
import org.springblade.modules.pl.processConfig.entity.ProcessConfigEntity;
import org.springblade.modules.pl.processConfig.service.IProcessConfigService;
import org.springblade.modules.pl.product.entity.ProductEntity;
import org.springblade.modules.pl.product.service.IProductService;
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.entity.ProductProcessItemEntity;
import org.springblade.modules.pl.productProcess.service.IProductProcessItemService;
import org.springblade.modules.pl.productProcess.vo.ProductProcessItemVO;
import org.springblade.modules.pl.productProcess.vo.ProductProcessSubmitVO;
import org.springblade.modules.pl.productProcess.vo.ProductProcessVO;
import org.springblade.modules.pl.productProcess.excel.ProductProcessExcel;
import org.springblade.modules.pl.productProcess.mapper.ProductProcessMapper;
import org.springblade.modules.pl.productProcess.service.IProductProcessService;
import org.springblade.modules.pl.productProcess.wrapper.ProductProcessWrapper;
import org.springblade.modules.pl.productRework.entity.ProductReworkEntity;
import org.springblade.modules.pl.productRework.service.IProductReworkService;
import org.springblade.modules.pl.productRework.vo.ProductReworkVO;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品工序记录表 服务实现类
 *
 * @author BladeX
 * @since 2024-04-21
 */
@Service
public class ProductProcessServiceImpl extends BaseServiceImpl<ProductProcessMapper, ProductProcessEntity> implements IProductProcessService {
	@Resource
	private IProductService productService;
	@Resource
	private IProductModelService productModelService;
	@Resource
	private IProductReworkService productReworkService;
	@Resource
	private IProcessConfigService processConfigService;
	@Resource
	private IProcessService processService;
	@Resource
	private IProcessItemService processItemService;
	@Resource
	private IProductProcessItemService productProcessItemService;

	@Override
	public IPage<ProductProcessExcel> selectProductProcessPage(IPage<ProductProcessExcel> page, Map<String, Object> productProcess) {
		return page.setRecords(baseMapper.selectProductProcessPage(page, productProcess));
	}


	@Override
	public List<ProductProcessExcel> exportProductProcess(Map<String, Object> productProcess) {
		List<ProductProcessExcel> productProcessList = baseMapper.exportProductProcess(productProcess);
		//productProcessList.forEach(productProcess -> {
		//	productProcess.setTypeName(DictCache.getValue(DictEnum.YES_NO, ProductProcess.getType()));
		//});
		return productProcessList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R processSubmit(ProductProcessSubmitVO productProcess) {
		String qrCode = productProcess.getQrCode();
		BladeUser user = AuthUtil.getUser();

		ProductEntity productEntity = productService.getOne(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getQrCode,qrCode).eq(ProductEntity::getFactoryId,user.getFactoryId()),false);
		if(productEntity==null){
			//产品不存在，新产品未启动工序
			if(qrCode.length()<18){
				return R.fail("产品二维码不能小于18位数");
			}
			String code = qrCode.substring(8,12);
			ProductModelEntity productModel = productModelService.getOne(Wrappers.<ProductModelEntity>lambdaQuery().eq(ProductModelEntity::getProductSpec,code).eq(ProductModelEntity::getFactoryId,user.getFactoryId()),false);
			if(productModel==null){
				return R.fail("未找到型号码为'"+code+"'的数据");
			}
			if(productModel.getIsEnableProcess()==0){
				return R.fail("当前产品型号未启用工序");
			}
			ProcessConfigEntity processConfigEntity = processConfigService.getById(productModel.getProcessConfigId());
			if(processConfigEntity==null){
				return R.fail("获取产品型号的工序配置异常");
			}
			String[] processIds = processConfigEntity.getProcessIds().split(",");
			for(int i=0;i<processIds.length;i++){
				String processId = processIds[i];
				ProcessEntity processEntity = processService.getById(processId);
				if(i==0){
					if(!processEntity.getId().equals(productProcess.getProductProcess().getProcessId())){
						return R.fail("型号工序已变动，请重新追溯");
					}
				}
			}
			ProductProcessVO productProcessVO = productProcess.getProductProcess();
			if(productProcessVO.getIsStandards()==0){
				if(StringUtil.isBlank(productProcess.getImages())){
					return R.fail("追溯不达标，请重新提交并上传图片");
				}
				if(StringUtil.isBlank(productProcess.getProblemDesc())){
					return R.fail("追溯不达标，请填写错误原因");
				}
			}
			productEntity = new ProductEntity();
			productEntity.setTenantId(productModel.getTenantId());
			productEntity.setFactoryId(productModel.getFactoryId());
			productEntity.setProductModelId(productModel.getId());
			productEntity.setProductName(productModel.getProductName());
			productEntity.setProductModel(productModel.getProductModel());
			productEntity.setQrCode(productProcess.getQrCode());
			productEntity.setStatus(-1);
			productEntity.setSource(4);
			productService.save(productEntity);
			if(productProcessVO.getIsStandards()==0){
				productEntity.setStatus(1);
				productService.updateById(productEntity);
				//未达标发起维修
				ProductReworkEntity productReworkEntity = new ProductReworkEntity();
				productReworkEntity.setFactoryId(productEntity.getFactoryId());
				productReworkEntity.setProductId(productEntity.getId());
				productReworkEntity.setQrCode(productEntity.getQrCode());
				productReworkEntity.setProductModelId(productEntity.getProductModelId());
				productReworkEntity.setProductName(productEntity.getProductName());
				productReworkEntity.setProductModel(productEntity.getProductModel());
				productReworkEntity.setRepairsImgs(productProcess.getImages());
				productReworkEntity.setProblemDesc(productProcess.getProblemDesc());
				productReworkEntity.setStatus(1);
				productReworkEntity.setCreatePersonName(user.getNickName());
				productReworkService.save(productReworkEntity);
			}
			for(int i=0;i<processIds.length;i++){
				if(i==0){
					productProcessVO = productProcess.getProductProcess();
					productProcessVO.setId(null);
					productProcessVO.setProductId(productEntity.getId());
					productProcessVO.setSort(i);
					productProcessVO.setStatus(1);
					productProcessVO.setOperatorName(user.getNickName());
					this.save(productProcessVO);
					if(productProcessVO.getIsRetrospect()==1){
						List<ProductProcessItemEntity>details = productProcess.getProductProcess().getDetails();
						for(ProductProcessItemEntity productProcessItem : details){
							productProcessItem.setId(null);
							productProcessItem.setProductProcessId(productProcessVO.getId());
							productProcessItem.setStatus(1);
						}
						productProcessItemService.saveBatch(details);
					}
				}else{
					String processId = processIds[i];
					ProcessEntity processEntity = processService.getById(processId);
					productProcessVO = BeanUtil.copy(processEntity, ProductProcessVO.class);
					productProcessVO.setId(null);
					productProcessVO.setProcessId(processEntity.getId());
					productProcessVO.setProcessName(processEntity.getName());
					productProcessVO.setProcessCode(processEntity.getCode());
					productProcessVO.setProcessType(processEntity.getType());
					productProcessVO.setProductId(productEntity.getId());
					productProcessVO.setSort(i);
					productProcessVO.setStatus(0);
					this.save(productProcessVO);
					if(productProcessVO.getIsRetrospect()==1){
						List<ProcessItemEntity>detailList = processItemService.list(Wrappers.<ProcessItemEntity>lambdaUpdate().eq(ProcessItemEntity::getProcessId,processEntity.getId()));
						List<ProductProcessItemEntity>details = new ArrayList<>();
						for(ProcessItemEntity processItem : detailList){
							ProductProcessItemEntity productProcessItem = new ProductProcessItemVO();
							productProcessItem.setId(null);
							productProcessItem.setProductProcessId(productProcessVO.getId());
							productProcessItem.setProcessItemId(processItem.getId());
							productProcessItem.setProcessItemName(processItem.getName());
							productProcessItem.setProcessItemValue(processItem.getValue());
							productProcessItem.setValueType(processItem.getValueType());
							productProcessItem.setMaxValue(processItem.getMaxValue());
							productProcessItem.setMinValue(processItem.getMinValue());
							productProcessItem.setUnit(processItem.getUnit());
							productProcessItem.setStatus(1);
							details.add(productProcessItem);
						}
						productProcessItemService.saveBatch(details);
					}
				}
			}

			return R.success("操作成功");
		}else{
			//产品存在，查询工序数据
			long count = this.count(Wrappers.<ProductProcessEntity>lambdaQuery().eq(ProductProcessEntity::getProductId,productEntity.getId()));
			if(count==0){
				return R.fail("产品工序数据异常");
			}
			ProductProcessEntity processEntity = this.getOne(Wrappers.<ProductProcessEntity>lambdaQuery()
				.eq(ProductProcessEntity::getProductId,productEntity.getId())
				.eq(ProductProcessEntity::getStatus,0)
				.orderByAsc(ProductProcessEntity::getSort),false);
			if(processEntity==null){
				return R.fail("已完成全部工序");
			}
			ProductProcessVO productProcessVO = productProcess.getProductProcess();
			if(productProcessVO.getId()==null){
				return R.fail("数据异常");
			}
			productProcessVO.setStatus(1);
			productProcessVO.setOperatorName(user.getNickName());
			this.updateById(productProcessVO);
			if(processEntity.getIsRetrospect()==1){
				productProcessItemService.updateBatchById(productProcess.getProductProcess().getDetails());
			}
			if(productProcessVO.getIsStandards()==0){
				productEntity.setStatus(1);
				productService.updateById(productEntity);
				//未达标发起维修
				ProductReworkEntity productReworkEntity = new ProductReworkEntity();
				productReworkEntity.setFactoryId(productEntity.getFactoryId());
				productReworkEntity.setProductId(productEntity.getId());
				productReworkEntity.setQrCode(productEntity.getQrCode());
				productReworkEntity.setProductModelId(productEntity.getProductModelId());
				productReworkEntity.setProductName(productEntity.getProductName());
				productReworkEntity.setProductModel(productEntity.getProductModel());
				productReworkEntity.setRepairsImgs(productProcess.getImages());
				productReworkEntity.setProblemDesc(productProcess.getProblemDesc());
				productReworkEntity.setStatus(1);
				productReworkEntity.setCreatePersonName(user.getNickName());
				productReworkService.save(productReworkEntity);
			}
			return R.success("操作成功");
		}
	}

}
