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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springblade.core.oss.model.BladeFile;
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.modules.pl.equipment.entity.EquipmentEntity;
import org.springblade.modules.pl.product.entity.ProductEntity;
import org.springblade.modules.pl.product.entity.ProductImageRecordEntity;
import org.springblade.modules.pl.product.service.IProductImageRecordService;
import org.springblade.modules.pl.product.service.IProductService;
import org.springblade.modules.pl.productModel.entity.ProductModelEntity;
import org.springblade.modules.pl.productModel.service.IProductModelService;
import org.springblade.modules.pl.productRework.entity.ProductReworkEntity;
import org.springblade.modules.pl.productRework.vo.ProductReworkVO;
import org.springblade.modules.pl.productRework.excel.ProductReworkExcel;
import org.springblade.modules.pl.productRework.mapper.ProductReworkMapper;
import org.springblade.modules.pl.productRework.service.IProductReworkService;
import org.springframework.beans.factory.annotation.Autowired;
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.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 产品返修表 服务实现类
 *
 * @author BladeX
 * @since 2023-12-05
 */
@Service
public class ProductReworkServiceImpl extends BaseServiceImpl<ProductReworkMapper, ProductReworkEntity> implements IProductReworkService {

	@Resource
	private IProductService productService;
	@Resource
	private RedissonClient redissonLock;
	@Resource
	private IProductModelService productModelService;

	@Override
	public IPage<ProductReworkVO> selectProductReworkPage(IPage<ProductReworkVO> page, ProductReworkVO productRework) {
		return page.setRecords(baseMapper.selectProductReworkPage(page, productRework));
	}

	public List<ProductReworkExcel> exportProductRework(Wrapper<ProductReworkEntity> queryWrapper) {
		List<ProductReworkExcel> productReworkList = baseMapper.exportProductRework(queryWrapper);
		//productReworkList.forEach(productRework -> {
		//	productRework.setTypeName(DictCache.getValue(DictEnum.YES_NO, ProductRework.getType()));
		//});
		return productReworkList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R add(ProductReworkVO productRework)throws InterruptedException {
		String productCode = productRework.getQrCode();

		BladeUser user = AuthUtil.getUser();
		// 获取可重入锁, 指定锁的名称
		RLock lock = redissonLock.getLock("lock:cameraUploadImg:"+productRework.getQrCode());
		// 尝试获取锁
		// 参数1：获取锁的最大等待时间（期间会多次重试获取锁）
		// 参数2：锁自动释放时间
		// 参数3：时间单位
		boolean isGetLock = lock.tryLock(50, 60, TimeUnit.SECONDS);
		if (isGetLock) {
			try {
				if(productCode.length()<25){
					return R.fail("产品码'"+productCode+"'小于25位");
				}
				ProductEntity productEntity = productService.getOne(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getQrCode,productRework.getQrCode()).eq(ProductEntity::getFactoryId,user.getFactoryId()),false);
				if(productEntity!=null && productEntity.getStatus()!=3){
					return R.fail("产品已下线或在维修中，无法发起维修");
				}

				String code = productCode.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+"'的数据");
				}else{
					if(productEntity==null){
						productEntity = new ProductEntity();
						productEntity.setSource(3);
					}
					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.setQrCode(productCode);
					productEntity.setStatus(1);
					productService.saveOrUpdate(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(productRework.getRepairsImgs());
					productReworkEntity.setProblemDesc(productRework.getProblemDesc());
					productReworkEntity.setStatus(1);
					productReworkEntity.setCreatePersonName(user.getNickName());
					this.save(productReworkEntity);
				}
			} finally {
				lock.unlock();
			}
		}
		return R.success("操作成功");
	}

}
