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 lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.DateUtil;
import org.springblade.core.tool.utils.Func;
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.productProcess.entity.ProductProcessEntity;
import org.springblade.modules.pl.productProcess.service.IProductProcessService;
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.springblade.modules.pl.productRework.wrapper.ProductReworkWrapper;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("wx/productRework/api")
@Api(value = "产品", tags = "产品相关外放接口")
@Slf4j
public class ProductReworkApiController {

	private final IProductService productService;

	private final IProductReworkService productReworkService;

	private final IProductProcessService productProcessService;



	/**
	 * 产品返修表 自定义分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入productRework")
	public R<IPage<ProductReworkEntity>> page(ProductReworkVO productRework, Query query) {
		query.setDescs("create_time");
		BladeUser user = AuthUtil.getUser();
		productRework.setFactoryId(user.getFactoryId());
		QueryWrapper<ProductReworkEntity> queryWrapper = Condition.getQueryWrapper(productRework);
		if("1".equals(productRework.getType())){
			queryWrapper.in("status", Func.toLongList("0,1"));
		}else {
			queryWrapper.in("status", productRework.getType());
		}
		IPage<ProductReworkEntity> pages = productReworkService.page(Condition.getPage(query),queryWrapper);
		return R.data(pages);
	}


	/**
	 * 产品返修表 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入productRework")
	public R<IPage<ProductReworkEntity>> page(@ApiIgnore @RequestParam Map<String, Object> productRework, Query query) {
		query.setDescs("create_time");
		BladeUser user = AuthUtil.getUser();
		productRework.put("factoryId",user.getFactoryId());
		QueryWrapper<ProductReworkEntity> wrapper = Condition.getQueryWrapper(productRework,ProductReworkEntity.class);
		IPage<ProductReworkEntity> pages = productReworkService.page(Condition.getPage(query),wrapper);
		return R.data(pages);
	}

	/**
	 * 产品维修表 统计
	 */
	@GetMapping("/countProductRework")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入product")
	public R<Object> countProduct(@ApiIgnore @RequestParam Map<String, Object> productRework, Query query) {
		Map<String,Object> result = new HashMap<>();
		if(productRework.get("status")!=null && "-1".equals(productRework.get("status"))){
			BladeUser user = AuthUtil.getUser();
			productRework.put("factoryId_equal",user.getFactoryId());
			if(productRework.get("auditDate")==null){
				productRework.put("auditDate", DateUtil.formatDate(new Date()));
			}
			QueryWrapper<ProductReworkEntity> wrapper = Condition.getQueryWrapper(productRework,ProductReworkEntity.class);
			long countNow = productReworkService.count(wrapper);
			productRework.remove("auditDate");
			wrapper = Condition.getQueryWrapper(productRework,ProductReworkEntity.class);
			long countAll = productReworkService.count(wrapper);
			result.put("countAll",countAll);
			result.put("countNow",countNow);

		}else{
			BladeUser user = AuthUtil.getUser();
			productRework.put("factoryId_equal",user.getFactoryId());
			QueryWrapper<ProductReworkEntity> wrapper = Condition.getQueryWrapper(productRework,ProductReworkEntity.class);
			long countAll = productReworkService.count(wrapper);
			productRework.put("status_equal","2");
			wrapper = Condition.getQueryWrapper(productRework,ProductReworkEntity.class);
			long countSucceed = productReworkService.count(wrapper);
			productRework.put("status_equal","3");
			wrapper = Condition.getQueryWrapper(productRework,ProductReworkEntity.class);
			long countCheck = productReworkService.count(wrapper);
			productRework.put("status_equal","-1");
			wrapper = Condition.getQueryWrapper(productRework,ProductReworkEntity.class);
			long countInvalid = productReworkService.count(wrapper);
			result.put("countAll",countAll);
			result.put("countSucceed",countSucceed);
			result.put("countCheck",countCheck);
			result.put("countInvalid",countInvalid);
		}
		return R.data(result);
	}


	/**
	 * 新增维修
	 */
	@PostMapping("/add")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增维修", notes = "传入productBatch")
	public R submit(@Valid @RequestBody ProductReworkVO productRework) throws InterruptedException {
		return productReworkService.add(productRework);
	}


	/**
	 * 产品返修表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入productRework")
	public R<ProductReworkVO> detail(ProductReworkEntity productRework) {
		BladeUser user = AuthUtil.getUser();
		productRework.setFactoryId(user.getFactoryId());
		ProductReworkEntity detail = productReworkService.getOne(Condition.getQueryWrapper(productRework));
		return R.data(ProductReworkWrapper.build().entityVO(detail));
	}


	/**
	 * 维修
	 */
	@PostMapping("/rework")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "维修", notes = "传入productBatch")
	public R rework(@Valid @RequestBody ProductReworkEntity productRework) {
		BladeUser user = AuthUtil.getUser();
		ProductReworkEntity detail = productReworkService.getById(productRework.getId());
		if(detail.getStatus()>1){
			return R.fail("当前状态无法维修");
		}
		if(StringUtil.isNotBlank(productRework.getQrCode())){
			if(!productRework.getQrCode().equals(detail.getQrCode())){
				long count = productService.count(Wrappers.<ProductEntity>lambdaQuery().eq(ProductEntity::getFactoryId,detail.getFactoryId()).eq(ProductEntity::getQrCode,productRework.getQrCode()));
				if(count>0){
					return R.fail("产品二维码已存在");
				}
				ProductEntity product = new ProductEntity();
				product.setId(detail.getProductId());
				product.setQrCode(productRework.getQrCode());
				product.setOldQrCode(detail.getQrCode());
				productService.updateById(product);
			}
		}
		productRework.setStatus(2);
		productRework.setReworkDate(new Date());
		productRework.setReworkPersonName(user.getNickName());
		productRework.setAuditFailCause("");
		productReworkService.updateById(productRework);
		return R.success("操作成功");
	}

	/**
	 * 审核
	 */
	@PostMapping("/check")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "审核", notes = "传入productBatch")
	public R check(@Valid @RequestBody ProductReworkEntity productRework) {
		BladeUser user = AuthUtil.getUser();
		ProductReworkEntity detail = productReworkService.getById(productRework.getId());
		if(detail.getStatus()>2){
			return R.fail("当前状态无法审核");
		}
		productRework.setAuditDate(new Date());
		productRework.setAuditPersonName(user.getNickName());
		productReworkService.updateById(productRework);
		if(productRework.getStatus() ==3 ){
			ProductEntity product = productService.getById(detail.getProductId());
			ProductEntity productEntity = new ProductEntity();
			productEntity.setId(product.getId());
			long count = productProcessService.count(Wrappers.<ProductProcessEntity>lambdaQuery().eq(ProductProcessEntity::getProductId,productEntity.getId()));
			if(count==0){
				//无工序数据
				productEntity.setStatus(2);
			}else{
				count = productProcessService.count(Wrappers.<ProductProcessEntity>lambdaQuery()
					.eq(ProductProcessEntity::getProductId,productEntity.getId())
					.eq(ProductProcessEntity::getIsDownline,1)
					.eq(ProductProcessEntity::getStatus,1));
				if(count>1){
					//已执行下线工序状态改为已下线
					productEntity.setStatus(2);
				}else{
					//未执行下线工序状态改为生产中
					productEntity.setStatus(-1);
				}
			}
			if(product.getAiStatus()==1){
				productEntity.setAiStatus(3);
			}
			productService.updateById(productEntity);
		}else if(productRework.getStatus() ==-1 ){
			ProductEntity productEntity = new ProductEntity();
			productEntity.setId(detail.getProductId());
			productEntity.setStatus(0);
			productService.updateById(productEntity);
		}
		return R.success("操作成功");
	}
}
