package org.springblade.applet;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import liquibase.pro.packaged.I;
import liquibase.pro.packaged.P;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionEntityImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
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.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.pl.client.entity.ClientEntity;
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.process.vo.ProcessVO;
import org.springblade.modules.pl.process.wrapper.ProcessWrapper;
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.product.vo.ProductVO;
import org.springblade.modules.pl.product.wrapper.ProductWrapper;
import org.springblade.modules.pl.productBatch.service.IProductBatchService;
import org.springblade.modules.pl.productBatch.vo.ProductBatchVO;
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.excel.ProductProcessExcel;
import org.springblade.modules.pl.productProcess.service.IProductProcessItemService;
import org.springblade.modules.pl.productProcess.service.IProductProcessService;
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.wrapper.ProductProcessWrapper;
import org.springblade.modules.pl.productRework.entity.ProductReworkEntity;
import org.springblade.modules.pl.productRework.service.IProductReworkService;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@AllArgsConstructor
@RequestMapping("wx/product/api")
@Api(value = "产品", tags = "产品相关外放接口")
@Slf4j
public class ProductApiController {
	@Resource
	private final RedissonClient redissonLock;

	private final IProductBatchService productBatchService;

	private final IProductService productService;

	private final IProductModelService productModelService;

	private final IClientService clientService;

	private final IProductReworkService productReworkService;

	private final IProcessConfigService processConfigService;

	private final IProcessService processService;

	private final IProductProcessService productProcessService;

	private final IProcessItemService processItemService;

	private final IProductProcessItemService productProcessItemService;

	/**
	 * 产品表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入product")
	public R<IPage<ProductVO>> list(@ApiIgnore @RequestParam Map<String, Object> product, Query query) {
		query.setDescs("create_time");
		BladeUser user = AuthUtil.getUser();
		product.put("factoryId",user.getFactoryId());
		QueryWrapper<ProductEntity> wrapper = Condition.getQueryWrapper(product,ProductEntity.class);
		if("1".equals(product.get("isNg_ignore"))){
			wrapper.eq("status", 2);
			wrapper.in("ai_status", Func.toLongList("0,1"));
		}
		IPage<ProductEntity> pages = productService.page(Condition.getPage(query),wrapper);
		return R.data(ProductWrapper.build().pageVO(pages));
	}

	/**
	 * 产品表 统计
	 */
	@GetMapping("/countProduct")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入product")
	public R<Object> countProduct(@ApiIgnore @RequestParam Map<String, Object> product, Query query) {
		BladeUser user = AuthUtil.getUser();
		long countAll = productService.count(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getFactoryId,user.getFactoryId()).eq(ProductEntity::getStatus,"3"));
		product.put("factoryId",user.getFactoryId());
		QueryWrapper<ProductEntity> wrapper = Condition.getQueryWrapper(product,ProductEntity.class);
		long count = productService.count(wrapper);
		Map<String,Object> result = new HashMap<>();
		result.put("countAll",countAll);
		result.put("count",count);
		return R.data(result);
	}


	/**
	 * 产品表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入product")
	public R<ProductVO> detail(ProductEntity product) {
		BladeUser user = AuthUtil.getUser();
		product.setFactoryId(user.getFactoryId());
		ProductEntity detail = productService.getOne(Condition.getQueryWrapper(product));
		if(detail==null){
			return R.fail("未查询到产品信息");
		}
		ProductVO productVO = ProductWrapper.build().entityVO(detail);
		ProductModelEntity productModel = productModelService.getById(detail.getProductModelId());
		if(productModel!=null && productModel.getIsEnableProcess()==1){
			productVO.setIsEnableProcess(productModel.getIsEnableProcess());
			List<ProductProcessEntity> productProcesss = productProcessService.list(Wrappers.<ProductProcessEntity>lambdaQuery()
				.eq(ProductProcessEntity::getProductId,detail.getId())
				.orderByAsc(ProductProcessEntity::getSort));
			List<ProductProcessVO> productProcessList = new ArrayList<>();
			for(ProductProcessEntity processEntity : productProcesss){
				ProductProcessVO processVO = ProductProcessWrapper.build().entityVO(processEntity);
				if(processVO.getStatus() == 1 && processVO.getIsRetrospect()==1){
					processVO.setDetails(productProcessItemService.list(Wrappers.<ProductProcessItemEntity>lambdaQuery()
						.eq(ProductProcessItemEntity::getProductProcessId,processVO.getId())));
				}
				productProcessList.add(processVO);
			}
			productVO.setProductProcessList(productProcessList);
		}else{
			productVO.setIsEnableProcess(0);
		}
		return R.data(productVO);
	}


	/**
	 * 产品入库批次表 新增或修改
	 */
	@PostMapping("/batchSubmit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入productBatch")
	@ApiLog("产品入库新增")
	public R submit(@Valid @RequestBody ProductBatchVO productBatch) {
		return productBatchService.submit(productBatch);
	}



	/**
	 * 客户表 下拉框
	 */
	@GetMapping("/clientSelect")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "下拉框", notes = "传入factory")
	public R<List<ClientEntity>> select(ClientEntity factory, Query query) {
		BladeUser user = AuthUtil.getUser();
		if(user.getUserCategory()==2){
			factory.setFactoryId(user.getFactoryId());
		}
		List<ClientEntity> list = clientService.list(Condition.getQueryWrapper(factory));
		return R.data(list);
	}


	/**
	 * 产品型号表 下拉框
	 */
	@GetMapping("/modelSelect")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "下拉框", notes = "传入factory")
	public R<List<ProductModelEntity>> select(ProductModelEntity productModel) {
		BladeUser user = AuthUtil.getUser();
		productModel.setFactoryId(user.getFactoryId());
		List<ProductModelEntity> list = productModelService.list(Condition.getQueryWrapper(productModel));
		return R.data(list);
	}

	/**
	 * 产品NG或OK操作
	 */
	@GetMapping("/productNgOperate")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "产品NG或OK操作", notes = "传入productBatch")
	public R productOkOrNg(@Valid @RequestParam String productId,@RequestParam String aiImg,@RequestParam String isNg) throws InterruptedException {
		if(productId==null || isNg==null || aiImg==null){
			return R.fail("请传入产品信息");
		}
		ProductEntity productEntity = productService.getById(productId);
		if(productEntity==null){
			return R.fail("NG的产品不存在");
		}
		if(productEntity.getStatus()!=2 && (productEntity.getAiStatus()==0 || productEntity.getAiStatus()==1)){
			return R.fail("当前产品状态无法操作");
		}
		BladeUser user = AuthUtil.getUser();
		if("0".equals(isNg)){
			productEntity.setStatus(2);
			productEntity.setAiStatus(3);
			productService.updateById(productEntity);
		}else{
			productEntity.setAiStatus(1);
			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(aiImg);
			productReworkEntity.setProblemDesc("AI检测NG");
			productReworkEntity.setStatus(1);
			productReworkEntity.setCreatePersonName(user.getNickName());
			productReworkService.save(productReworkEntity);

		}
		ProductModelEntity productModel = productModelService.getById(productEntity.getProductModelId());
		if(productEntity!=null && productModel!=null && productModel.getIsPushTripartite()==1){
			if(productEntity.getAiStatus()==-1 || productEntity.getAiStatus()==2){
				productService.pushTripartite(productEntity.getQrCode(),aiImg,productModel,"OK");
			}
		}
		return R.success("操作成功");
	}

	/**
	 * 获取工序配置
	 */
	@GetMapping("/getProcessConfig")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取工序配置", notes = "传入productBatch")
	public R getProcessConfig(@Valid @RequestParam String processConfigId) throws InterruptedException {
		ProcessConfigEntity processConfigEntity = processConfigService.getById(processConfigId);
		if(processConfigEntity == null) {
			return R.fail("获取工序配置失败");
		}
		return R.data(processConfigEntity);
	}

	/**
	 * 获取工序统计
	 */
	@GetMapping("/productProcessReport")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取工序统计", notes = "传入productBatch")
	public R productProcessReport(@ApiIgnore @RequestParam Map<String, Object> productProcess) {
		BladeUser user = AuthUtil.getUser();
		if(user.getUserCategory()==2){
			productProcess.put("factoryId",user.getFactoryId());
		}
		List<ProductProcessExcel> list = productProcessService.exportProductProcess(productProcess);
		return R.data(list);
	}

	/**
	 * 获取产品及工序休息
	 */
	@GetMapping("/getProductProcess")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取产品及工序休息", notes = "传入productBatch")
	public R getProductProcess(@Valid @RequestParam String qrCode,@RequestParam String processId) throws InterruptedException {
		if(StringUtil.isBlank(qrCode)) {
			return R.fail("请传入产品信息");
		}
		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(",");
			ProcessEntity processEntity = processService.getById(processIds[0]);

			ProductProcessVO productProcessVO = BeanUtil.copy(processEntity, ProductProcessVO.class);
			productProcessVO.setProcessId(processEntity.getId());
			productProcessVO.setProcessName(processEntity.getName());
			productProcessVO.setProcessCode(processEntity.getCode());
			productProcessVO.setProcessType(processEntity.getType());
			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.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());
					details.add(productProcessItem);
				}
				productProcessVO.setDetails(details);
			}
			if(!processId.equals(productProcessVO.getProcessId().toString())){
				return R.fail("产品-"+qrCode+"当前工序为"+productProcessVO.getProcessName());
			}
			Map<String,Object> result = new HashMap<>();
			result.put("productModel",productModel);
			result.put("process",productProcessVO);
			return R.data(result);
		}else{
			if(productEntity.getStatus()==0){
				return R.fail("产品已作废");
			}
			if(productEntity.getStatus()==1){
				return R.fail("产品维修中");
			}
			if(productEntity.getStatus()==3){
				return R.fail("产品已入库");
			}
			//产品存在，查询工序数据
			long count = productProcessService.count(Wrappers.<ProductProcessEntity>lambdaQuery().eq(ProductProcessEntity::getProductId,productEntity.getId()));
			if(count==0){
				return R.fail("产品工序数据异常");
			}
			ProductProcessEntity processEntity = productProcessService.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 = ProductProcessWrapper.build().entityVO(processEntity);
			if(processEntity.getIsRetrospect()==1){
				List<ProductProcessItemEntity>details = productProcessItemService.list(Wrappers.<ProductProcessItemEntity>lambdaUpdate().eq(ProductProcessItemEntity::getProductProcessId,processEntity.getId()));
				productProcessVO.setDetails(details);
			}
			if(!processId.equals(productProcessVO.getProcessId().toString())){
				return R.fail("产品-"+qrCode+"无法追溯，当前可操作工序："+productProcessVO.getProcessCode()+productProcessVO.getProcessName());
			}
			Map<String,Object> result = new HashMap<>();
			result.put("product",productEntity);
			result.put("process",productProcessVO);
			return R.data(result);
		}
	}


	/**
	 * 工序提交
	 */
	@PostMapping("/processSubmit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "工序提交", notes = "传入productBatch")
	@ApiLog("工序提交")
	public R submit(@Valid @RequestBody ProductProcessSubmitVO productProcess) throws InterruptedException {
		// 获取可重入锁, 指定锁的名称
		RLock lock = redissonLock.getLock("lock:cameraUploadImg:"+productProcess.getQrCode());
		// 尝试获取锁
		// 参数1：获取锁的最大等待时间（期间会多次重试获取锁）
		// 参数2：锁自动释放时间
		// 参数3：时间单位
		boolean isGetLock = lock.tryLock(50, 60, TimeUnit.SECONDS);
		if (isGetLock) {
			try {
				return productProcessService.processSubmit(productProcess);
			} finally {
				lock.unlock();
			}
		}
		return R.success("操作失败");
	}
}
