package org.jeecg.modules.workOrder.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.material.entity.BuMaterialInfo;
import org.jeecg.modules.material.entity.BuMaterialSheet;
import org.jeecg.modules.material.entity.BuMaterialStock;
import org.jeecg.modules.material.service.IBuMaterialInfoService;
import org.jeecg.modules.material.service.IBuMaterialSheetService;
import org.jeecg.modules.material.service.IBuMaterialStockService;
import org.jeecg.modules.workOrder.entity.AvailableMaterial;
import org.jeecg.modules.workOrder.entity.ReplacementRecords;
import org.jeecg.modules.workOrder.entity.WorkOrder;
import org.jeecg.modules.workOrder.service.IReplacementRecordsService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.workOrder.service.IWorkOrderService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 材料更换记录
 * @Author: jeecg-boot
 * @Date:   2025-02-20
 * @Version: V1.0
 */
@Api(tags="材料更换记录")
@RestController
@RequestMapping("/workOrder/replacementRecords")
@Slf4j
public class ReplacementRecordsController extends JeecgController<ReplacementRecords, IReplacementRecordsService> {
	@Autowired
	private IReplacementRecordsService replacementRecordsService;
	@Autowired
	private IBuMaterialStockService materialStockService;
	@Autowired
	private IBuMaterialInfoService materialInfoService;
	@Autowired
	private IBuMaterialSheetService materialSheetService;
	@Autowired
	private IWorkOrderService workOrderService;
	/**
	 * 分页列表查询
	 *
	 * @param replacementRecords
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "材料更换记录-分页列表查询")
	@ApiOperation(value="材料更换记录-分页列表查询", notes="材料更换记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ReplacementRecords>> queryPageList(ReplacementRecords replacementRecords,
														   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														   HttpServletRequest req) {
		List<WorkOrder> workOrders = workOrderService.list(new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getDeviceId,replacementRecords.getDeviceId()));
		Set<String> workOrderIds = workOrders.stream().map(WorkOrder::getId).collect(Collectors.toSet());

		QueryWrapper<ReplacementRecords> queryWrapper = QueryGenerator.initQueryWrapper(replacementRecords, req.getParameterMap());
		queryWrapper.in(!workOrderIds.isEmpty(),"work_order",workOrderIds);
		Page<ReplacementRecords> page = new Page<ReplacementRecords>(pageNo, pageSize);
		IPage<ReplacementRecords> pageList = replacementRecordsService.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			BuMaterialSheet materialSheet = materialSheetService.getById(item.getMaterialId());
			if(materialSheet!=null){
				BuMaterialInfo materialInfo = materialInfoService.getById(materialSheet.getMaterialId());
				item.setMaterialDescription(materialInfo.getName());
				item.setUnit(materialInfo.getUnit());
			}
		});
		return Result.OK(pageList);
	}
	@AutoLog(value = "根据工单查询可用材料")
	@ApiOperation(value="根据工单查询可用材料", notes="根据工单查询可用材料")
	//@RequiresPermissions("org.jeecg.modules:bu_replacement_records:add")
	@GetMapping(value = "/available/{id}")
	public Result<?> quaeryAvailableMaterials(@PathVariable("id")String id){
		List<AvailableMaterial> materials = replacementRecordsService.getAvailableMaterials(id);
		return Result.ok(materials);
	}
	/**
	 *   添加
	 *
	 * @param replacementRecords
	 * @return
	 */
	@AutoLog(value = "材料更换记录-添加")
	@ApiOperation(value="材料更换记录-添加", notes="材料更换记录-添加")
	//@RequiresPermissions("org.jeecg.modules:bu_replacement_records:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ReplacementRecords replacementRecords) {
		long count = replacementRecordsService.count(new QueryWrapper<ReplacementRecords>().eq("work_order", replacementRecords.getWorkOrder()));
		replacementRecords.setSeq((int)count+1);
		replacementRecordsService.save(replacementRecords);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param replacementRecords
	 * @return
	 */
	@AutoLog(value = "材料更换记录-编辑")
	@ApiOperation(value="材料更换记录-编辑", notes="材料更换记录-编辑")
	//@RequiresPermissions("org.jeecg.modules:bu_replacement_records:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ReplacementRecords replacementRecords) {
		replacementRecordsService.updateById(replacementRecords);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "材料更换记录-通过id删除")
	@ApiOperation(value="材料更换记录-通过id删除", notes="材料更换记录-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:bu_replacement_records:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		replacementRecordsService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "材料更换记录-批量删除")
	@ApiOperation(value="材料更换记录-批量删除", notes="材料更换记录-批量删除")
	//@RequiresPermissions("org.jeecg.modules:bu_replacement_records:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.replacementRecordsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "材料更换记录-通过id查询")
	@ApiOperation(value="材料更换记录-通过id查询", notes="材料更换记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ReplacementRecords> queryById(@RequestParam(name="id",required=true) String id) {
		ReplacementRecords replacementRecords = replacementRecordsService.getById(id);
		if(replacementRecords==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(replacementRecords);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param replacementRecords
	 */
	//@RequiresPermissions("org.jeecg.modules:bu_replacement_records:exportXls")
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, ReplacementRecords replacementRecords) {
		return super.exportXls(request, replacementRecords, ReplacementRecords.class, "材料更换记录");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	//@RequiresPermissions("bu_replacement_records:importExcel")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, ReplacementRecords.class);
	}

	@AutoLog(value = "材料更换记录-批量添加")
	@ApiOperation(value="材料更换记录-批量添加", notes="材料更换记录-批量添加")
	@PostMapping(value = "/addBatch")
	public Result<String> addBatch(@RequestBody List<ReplacementRecords> replacementRecordsList) {
		// 用于存储库存不足的物料信息
		List<String> insufficientMaterials = new ArrayList<>();
		// 用于存储需要更新的库存信息，避免重复查询
		List<BuMaterialSheet> replacements = new ArrayList<>();

		// 遍历每个更换记录，检查库存是否足够
		for (ReplacementRecords replacementRecords : replacementRecordsList) {
			BuMaterialSheet materialSheet = materialSheetService.getOne(new QueryWrapper<BuMaterialSheet>().eq("material_id", replacementRecords.getMaterialCode()));
			if (materialSheet == null || materialSheet.getQuantity() < replacementRecords.getQuantity()) {
				BuMaterialInfo buMaterialInfo = materialInfoService.getOne(new QueryWrapper<BuMaterialInfo>().eq("id", replacementRecords.getMaterialCode()));
				insufficientMaterials.add(buMaterialInfo.getName());
			}else {
				replacements.add(materialSheet);
			}
		}

		// 如果有库存不足的物料，返回错误信息
		if (!insufficientMaterials.isEmpty()) {
			return Result.error(String.join(", ", insufficientMaterials)+"  "+insufficientMaterials.size()+"种物料库存不足!" );
		}

		// 如果所有物料库存都足够，执行之前的校验和保存逻辑
		for (int i = 0; i < replacementRecordsList.size(); i++) {
			ReplacementRecords replacementRecords = replacementRecordsList.get(i);
			BuMaterialSheet materialSheet = replacements.get(i);
			if (materialSheet != null && materialSheet.getQuantity() >= replacementRecords.getQuantity()) {
				materialSheet.setQuantity(materialSheet.getQuantity() - replacementRecords.getQuantity());
				materialSheetService.updateById(materialSheet);

				// 存储
				// 查询该工单下是否有相同物料的更换记录，有就合并两个的数量
				QueryWrapper<ReplacementRecords> queryWrapper = new QueryWrapper<ReplacementRecords>();
				queryWrapper.eq("work_order", replacementRecords.getWorkOrder());
				queryWrapper.eq("material_code", replacementRecords.getMaterialCode());
				queryWrapper.orderByDesc("create_time").last("limit 1");
				ReplacementRecords oldReplacementRecords = replacementRecordsService.getOne(queryWrapper);
				if (oldReplacementRecords != null) {
					oldReplacementRecords.setQuantity(oldReplacementRecords.getQuantity() + replacementRecords.getQuantity());
					replacementRecordsService.updateById(oldReplacementRecords);
				} else {
					replacementRecordsService.save(replacementRecords);
				}
			}
		}
		replacements.clear();
		return Result.OK("物料申请成功！");
	}
}
