package org.springblade.modules.material.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.exception.ServiceException;
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.annotation.PreAuth;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.fitting.constant.FittingConstant;
import org.springblade.modules.flowable.processForm.utils.GuardUtils;
import org.springblade.modules.material.excel.MaterialImporter;
import org.springblade.modules.material.pojo.entity.MaterialEntity;
import org.springblade.modules.material.pojo.entity.MaterialOutboundEntity;
import org.springblade.modules.material.pojo.vo.EmpGetFittingOutVo;
import org.springblade.modules.material.pojo.vo.MaterialOutboundVO;
import org.springblade.modules.material.pojo.vo.MaterialVO;
import org.springblade.modules.material.service.IMaterialOutboundService;
import org.springblade.modules.material.service.IMaterialService;
import org.springblade.modules.material.wrapper.MaterialWrapper;
import org.springblade.modules.nh.excel.InefficientSettingExcel;
import org.springblade.modules.nh.excel.InefficientSettingImporter;
import org.springblade.modules.nh.excel.MaterialExcel;
import org.springblade.modules.order.pojo.vo.SelectVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 物料库存 控制器
 *
 * @author cswang
 * @since 2024-08-25
 */
@RestController
@AllArgsConstructor
@RequestMapping("wl/material")
@Tag(name = "物料库存", description = "物料库存接口")
public class MaterialController extends BladeController {

	private final IMaterialService materialService;

	private final IMaterialOutboundService outboundService;
	/**
	 * 物料库存 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description  = "传入material")
	public R<MaterialVO> detail(MaterialEntity material) {
		MaterialEntity detail = materialService.getOne(Condition.getQueryWrapper(material));
		return R.data(MaterialWrapper.build().entityVO(detail));
	}
	/**
	 * 物料库存 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description  = "传入material")
	public R<IPage<MaterialVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> material, Query query) {
		query.setDescs("status");

		IPage<MaterialEntity> pages = materialService.page(Condition.getPage(query), Condition.getQueryWrapper(material, MaterialEntity.class));
		return R.data(MaterialWrapper.build().pageVO(pages));
	}

	/**
	 * 物料库存 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description  = "传入material")
	public R<IPage<MaterialVO>> page(MaterialVO material, Query query) {
		IPage<MaterialVO> pages = materialService.selectMaterialPage(Condition.getPage(query), material);
		return R.data(pages);
	}

	/**
	 * 物料库存 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description  = "传入material")
	public R save(@Valid @RequestBody MaterialEntity material) {
		GuardUtils.notBlank(material.getCode(), "物料编码不能为空");
		GuardUtils.notBlank(material.getName(), "物料名称不能为空");
		GuardUtils.notBlank(material.getType(), "物料类型不能为空");
		GuardUtils.notBlank(material.getModel(), "物料型号不能为空");
		GuardUtils.notBlank(material.getPower(), "物料规格不能为空");
		GuardUtils.notBlank(material.getBrand(), "物料品牌不能为空");
		GuardUtils.notNull(material.getStock(),"库存不能为空");
		MaterialEntity entity = materialService.getByMaterialCode(material.getCode());
		if(entity!= null){
			throw new ServiceException("物料编码已存在");
		}
		material.setCompanyId(-1L);
		if(material.getRetailPrice()== null){
			material.setRetailPrice(0.0);
		}
		BladeUser user = AuthUtil.getUser();
		boolean check =materialService.save(material);
		if(material.getStock()>0){
			//添加入库明细
			outboundService.saveMateInkeep(material,"1",user, FittingConstant.KEEP_FORM_IN);

		}
		return R.status(check);
	}

	/**
	 * 物料库存 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description  = "传入material")
	public R update(@Valid @RequestBody MaterialEntity material) {

		GuardUtils.notBlank(material.getName(), "物料名称不能为空");
		GuardUtils.notBlank(material.getType(), "物料类型不能为空");
		GuardUtils.notBlank(material.getModel(), "物料型号不能为空");
		GuardUtils.notBlank(material.getPower(), "物料规格不能为空");
		GuardUtils.notBlank(material.getBrand(), "物料品牌不能为空");
		return R.status(materialService.updateById(material));
	}

	/**
	 * 物料库存 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description  = "传入material")
	public R submit(@Valid @RequestBody MaterialEntity material) {
		if(material.getId()!=null){
			material.setStock(null);
		}else{
			GuardUtils.notBlank(material.getCode(), "物料编码不能为空");
			GuardUtils.notNull(material.getStock(),"库存不能为空");
			MaterialEntity entity = materialService.getByMaterialCode(material.getCode());
			if(entity!= null){
				throw new ServiceException("物料编码已存在");
			}

			if(material.getRetailPrice()== null){
				material.setRetailPrice(0.0);
			}
		}
		GuardUtils.notBlank(material.getName(), "物料名称不能为空");
		GuardUtils.notBlank(material.getType(), "物料类型不能为空");
		GuardUtils.notBlank(material.getModel(), "物料型号不能为空");
		GuardUtils.notBlank(material.getPower(), "物料规格不能为空");
		GuardUtils.notBlank(material.getBrand(), "物料品牌不能为空");
		material.setCompanyId(-1L);

		BladeUser user = AuthUtil.getUser();
		boolean check =materialService.saveOrUpdate(material);

		if(material.getStock() != null&& material.getStock()>0){
			//添加入库明细
			outboundService.saveMateInkeep(material,"1",user, FittingConstant.KEEP_FORM_IN);
		}

		return R.status(check);
		//return R.status(materialService.saveOrUpdate(material));
	}

	/**
	 * 物料库存 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "删除", description  = "传入ids")
	public R remove(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		LambdaUpdateWrapper<MaterialEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(MaterialEntity::getId,Func.toLongList(ids))
			.eq(MaterialEntity::getStatus,"0")
			.set(MaterialEntity::getIsDeleted,1);
		return R.status(materialService.update(updateWrapper));
	}

	/**
	 * 设置物料状态
	 */
	@PostMapping("/setStatus")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "删除", description  = "传入ids")
	public R setStatus(@Parameter(name = "主键集合", required = true) @RequestParam String ids,
					   @Parameter(required = true) @RequestParam String status) {
		List<Long> idList = Func.toLongList(ids);
		if("0".equals(status)){
			for(Long id:idList){
				MaterialEntity entity =materialService.getById(id);
				if(entity.getStock()>0){
					return R.fail("该物料存在库存，不可禁用");
				}
			}
		}
		LambdaUpdateWrapper<MaterialEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(MaterialEntity::getId,idList)
			.set(MaterialEntity::getStatus,status);
		return R.status(materialService.update(updateWrapper));
	}

	@PostMapping("/setStock")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "调整库存", description  = "")
	public R setStock(@Parameter(name = "主键集合", required = true) @RequestParam Long id,
					   @Parameter(required = true) @RequestParam Integer newStock,
					   @Parameter(required = true) @RequestParam String reason) {
		MaterialEntity entity = materialService.getById(id);

		LambdaUpdateWrapper<MaterialEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(MaterialEntity::getId,id)
			.set(MaterialEntity::getStock,newStock);
		materialService.update(updateWrapper);

		MaterialOutboundEntity outbound = new MaterialOutboundEntity();
		BeanUtil.copyProperties(entity,outbound);
		outbound.setMaterialId(id);
		outbound.setId(null);
		outbound.setOutType("3");
		outbound.setKeepType("3");
		outbound.setCompanyId("-1");
		if(newStock > entity.getStock()){
			outbound.setOutDirect("1");
			outbound.setKeepFrom("1");
		}else{
			outbound.setOutDirect("2");
			outbound.setKeepFrom("2");
		}
		int count = Math.abs(newStock-entity.getStock());
		outbound.setOutCount(count);
		outbound.setOutAmount(count*entity.getRetailPrice());
		outbound.setRemarks(reason);
		outboundService.save(outbound);

		return R.success("设置成功");
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/export-material")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出数据", description  = "传入material")
	public void exportMaterial(@Parameter(hidden = true) @RequestParam Map<String, Object> material, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<MaterialEntity> queryWrapper = Condition.getQueryWrapper(material, MaterialEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(Material::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(MaterialEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<MaterialExcel> list = materialService.exportMaterial(queryWrapper);
		ExcelUtil.export(response, "物料库存数据" + DateUtil.time(), "物料库存数据表", list, MaterialExcel.class);
	}


	/**
	 * 导入
	 */
	@PostMapping("import-material")
	@ApiOperationSupport(order = 12)
	@Operation(summary = "导入用户", description = "传入excel")
	public R importUser(MultipartFile file) {
		MaterialImporter importer = new MaterialImporter(materialService,false);
		ExcelUtil.save(file, importer, MaterialExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiOperationSupport(order = 14)
	@Operation(summary = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<MaterialExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "物料数据模板", "物料数据表", list, MaterialExcel.class);
	}

	//工程师领取出库
	@PostMapping(value = "empGetFittingOut")
	@ApiOperationSupport(order = 15)
	@Operation(summary = "工程师领取出库")
    public R empGetFittingOut(@Valid @RequestBody EmpGetFittingOutVo empGetFittingOutVo){
		return R.status(materialService.empGetFittingOut(empGetFittingOutVo));
	}

	//根据工单编码模糊查询出工单
	@GetMapping(value = "getOrderListByNumber")
	@ApiOperationSupport(order = 16)
	@Operation(summary = "根据工单编码模糊查询出工单")
	public R<List<SelectVo>> getOrderListByNumber(String number){
		List<SelectVo> list=materialService.getOrderListByNumber(number);
		return R.data(list);
	}
}
