package com.sw.mes.yb.plan.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.sw.mes.base.factory.init.dto.MachineCapacityInfoDataDto;
import com.sw.mes.base.factory.init.entity.MachineCapacityInfo;
import com.sw.mes.base.factory.init.service.MachineCapacityInfoService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.factory.product.entity.ProductModel;
import com.sw.mes.base.factory.product.service.ProductModelService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.dto.CompletionStatusDto;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.annotation.TokenNotValidation;
import com.sw.mes.core.entity.SearchFilter;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.EasyExcelUtils;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.sap.entity.LogSapMesInteractive;
import com.sw.mes.sap.service.LogSapMesInteractiveService;
import com.sw.mes.sap.service.SAPInputServiceService;
import com.sw.mes.utils.ExcelUtil;
import com.sw.mes.yb.plan.dto.ProductionOrderCountDto;
import com.sw.mes.yb.plan.dto.ProductionOrderDto;
import com.sw.mes.yb.plan.dto.ProductionOrderImport;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.entity.ProductionSchedule;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import com.sw.mes.yb.plan.service.ProductionScheduleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/productionOrder")
@Slf4j
@Api(description = "单晶订单接口")
public class ProductionOrderController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private ProductionOrderService productionOrderService;
    @Autowired
    private LogSapMesInteractiveService logSapMesInteractiveService;

    @Autowired
    private ProductModelService productModelService;

    @Autowired
    private ProductionScheduleService productionScheduleService;

    @Autowired
    private MachineCapacityInfoService machineCapacityInfoService;
    
    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private DictionaryItemService dictionaryItemService;
    @Autowired
    private SAPInputServiceService sapServiceService;

    @ApiOperation(value = "分页查询单晶订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ProductionOrderDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<ProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, ProductionOrder.class);

        Page<ProductionOrder> page = productionOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ProductionOrderDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }
    
    @ApiOperation(value = "同步订单bom信息 - 内部调用")
    @PostMapping("/synOrderBom")
    public Result synOrderBom() {
    	List<ProductionOrder> orderList = productionOrderService.findAll();
    	
    	for (ProductionOrder productionOrder : orderList) {
    		String aufnr = productionOrder.getAufnr();//订单编号
    		
    		LogSapMesInteractive logSapMesInteractive = logSapMesInteractiveService.getSapLog("晶科SAP生产工单下发",productionOrder.getAufnr());
    		if(logSapMesInteractive!=null) {
    			String context = logSapMesInteractive.getContext();
    			JSONObject data = JSON.parseObject(context);
    			sapServiceService.synProductonOrderBomData(productionOrder.getId(), data);
    		}
		}
    	
        return ResultGenerator.success();
    }
    

    @ApiOperation(value = "获取订单排程情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPageV2")
    public Result<ResponsePage<ProductionOrderDto>> listByPageV2(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<ProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, ProductionOrder.class,
                new SearchFilter("productionStatus", SearchFilter.Operator.EQ, true));
        Page<ProductionOrder> page = productionOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ProductionOrderDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        //排程情况
        Map<Long, ProductionOrderCountDto> productionOrderCountMap = productionScheduleService.getProductionScheduleData();
        for (ProductionOrderDto productionOrderDto : dtos) {

            //返回值中根据productType获得字典值，返回给前端
            //产品类别，去数据字典查
            List<DictionaryItem> productCategorys = dictionaryItemService.findByThemeNamAndItemValue("产品类别", productionOrderDto.getProductType(),true);
            if (productCategorys.size()>0){
                productionOrderDto.setProductTypeS(productCategorys.get(0).getName());
            }
            ProductionOrderCountDto productionOrderCountDto = productionOrderCountMap.get(productionOrderDto.getId());
            if (productionOrderCountDto != null) {
                productionOrderDto.setSumCount(productionOrderCountDto.getSumCount());
                productionOrderDto.setCounts(productionOrderCountDto.getCounts());
            } else {
                productionOrderDto.setSumCount(0L);
                productionOrderDto.setCounts(0L);
            }
        }
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }


    @ApiOperation(value = "分页查询单晶订单完成情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/completionStatus")
    public Result<ResponsePage<ProductionOrderDto>> completionStatus(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<ProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, ProductionOrder.class);
        Page<ProductionOrder> page = productionOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ProductionOrderDto> dtos = page.getContent().stream()
                .map(this::toLazyCompletionDto)
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    public ProductionOrderDto toLazyCompletionDto(ProductionOrder entity) {
        LinkedList<CompletionStatusDto> completionStatusDtos = new LinkedList<>();
        CompletionStatusDto completionStatusDto = new CompletionStatusDto();
        completionStatusDto.setName("长晶");
        completionStatusDto.setCount(BigDecimal.valueOf(0));
        completionStatusDtos.add(completionStatusDto);

        CompletionStatusDto completionStatusDto1 = new CompletionStatusDto();
        completionStatusDto1.setName("截断");
        completionStatusDto1.setCount(BigDecimal.valueOf(0));
        completionStatusDtos.add(completionStatusDto1);

        CompletionStatusDto completionStatusDto2 = new CompletionStatusDto();
        completionStatusDto2.setName("检验（圆）");
        completionStatusDto2.setCount(BigDecimal.valueOf(0));
        completionStatusDtos.add(completionStatusDto2);

        CompletionStatusDto completionStatusDto3 = new CompletionStatusDto();
        completionStatusDto3.setName("总数");
        completionStatusDto3.setCount(BigDecimal.valueOf(0));
        completionStatusDtos.add(completionStatusDto3);

        CompletionStatusDto completionStatusDto4 = new CompletionStatusDto();
        completionStatusDto4.setName("报工");
        completionStatusDto4.setCount(BigDecimal.valueOf(0));
        completionStatusDtos.add(completionStatusDto4);

        ProductionOrderDto productionOrderDto = modelMapper.map(entity, ProductionOrderDto.class);
        productionOrderDto.setCompletionStatusDtos(completionStatusDtos);
        return productionOrderDto;
    }

    @ApiOperation(value = "获取所有单晶订单")
    @GetMapping("/listAll")
    public Result<List<ProductionOrderDto>> listAll(ServletRequest request) {
        Specification<ProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, ProductionOrder.class);
        List<ProductionOrder> sapProductionOrders = productionOrderService.findByExampleSort(specification, null);
        List<ProductionOrderDto> productionOrderDtos = sapProductionOrders.stream()
                .map(sapProductionOrder -> toLazyDto(sapProductionOrder))
                .collect(Collectors.toList());
        return ResultGenerator.success(productionOrderDtos);
    }

    @ApiOperation(value = "工单详细信息")
    @GetMapping("/{id}")
    public Result<ProductionOrderDto> get(@PathVariable @ApiParam(value = "sapProductionOrderid") Long id) {
        ProductionOrder sapProductionOrder = productionOrderService.get(id);
        if (null == sapProductionOrder) {
            return ResultGenerator.fail("该sapProductionOrder不存在");
        }
        return ResultGenerator.success(toEagerDto(sapProductionOrder));
    }

    @ApiOperation(value = "工单详细信息")
    @GetMapping("/findProductionOrderById")
    public Result<ProductionOrderDto> findProductionOrderById(@RequestParam @ApiParam(value = "sapProductionOrderid") Long id) {
        ProductionOrder sapProductionOrder = productionOrderService.get(id);
        if (null == sapProductionOrder) {
            return ResultGenerator.fail("该sapProductionOrder不存在");
        }
        return ResultGenerator.success(toEagerDto(sapProductionOrder));
    }

    @ApiOperation(value = "关闭订单")
    @GetMapping("/closeOrder/{id}")
    public Result closeOrder(@PathVariable @ApiParam(value = "sapProductionOrderid") Long id) {
        ProductionOrder sapProductionOrder = productionOrderService.get(id);
        if (null == sapProductionOrder) {
            return ResultGenerator.fail("该订单不存在");
        }
        sapProductionOrder.setStatus("CLOSE");
        sapProductionOrder.setCreateDate(new Date());
        sapProductionOrder.setProductionStatus(false);
        productionOrderService.close(sapProductionOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建工单")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "sapProductionOrder对象") ProductionOrderDto productionOrderDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ProductionOrder productionOrder = productionOrderService.findByAufnr(productionOrderDto.getAufnr());
        if (productionOrder != null) {
            return ResultGenerator.fail("订单编号已存在");
        }
        ProductModel productModel = productModelService.findByCode(productionOrderDto.getMatnr());
        if (productModel == null) {
            return ResultGenerator.fail("产品料号【" + productionOrderDto.getMatnr() + "】，不存在");
        }
        
        
        productionOrderDto.setRdonlylogo(productionOrderDto.getRdNum());
        
        ProductionOrder sapProductionOrder = fromDto(productionOrderDto);
        sapProductionOrder.setProductModel(productModel);
        if (StringUtils.isBlank(productionOrderDto.getStatus())) {
            sapProductionOrder.setStatus("REL");
        }
        if (productionOrderDto.getProductionStatus() == null) {
            sapProductionOrder.setProductionStatus(false);
        }

        //BMK23061005D750-680
        String workShop = productionOrderDto.getWorkShop();
        String productType = productionOrderDto.getProductType();
        String baseMark = productionOrderDto.getBaseMark();
        String fromMark = productionOrderDto.getFromMark();
        
        MaterialModel materialModel = materialModelService.findByCode(sapProductionOrder.getMatnr());
        if(materialModel!=null) {
	        MachineCapacityInfoDataDto dataDto = materialModelService.getMachineCapacityInfoDataDto(materialModel.getId());
            if(dataDto.getConductionType()!=null && dataDto.getSpecification()!=null && dataDto.getDopant() !=null && dataDto.getSimpleName()!=null) {
    	        MachineCapacityInfo info = machineCapacityInfoService.getMachineCapacityInfoJk(dataDto.getConductionType(), dataDto.getSpecification(),dataDto.getDopant(),dataDto.getSimpleName());
    	        sapProductionOrder.setMachineCapacityId(info.getId());
	        }else {
	        	return ResultGenerator.fail("物料主数据缺少电性能,特性值,晶体尺寸规格,晶体类别,产品简称.请录入后再次添加");
	        }
        }
        
        if(materialModel!=null) {
        	sapProductionOrder.setWgbez(materialModel.getWgbez());
        	sapProductionOrder.setMtbez(materialModel.getName());
        	sapProductionOrder.setVtext(materialModel.getVtext());
        	sapProductionOrder.setMatkl(materialModel.getMatkl());
        	sapProductionOrder.setNtgew(materialModel.getNtgew());
        	sapProductionOrder.setLaeng(materialModel.getLaeng());
        	sapProductionOrder.setBreit(materialModel.getBreit());
        	sapProductionOrder.setHoehe(materialModel.getHoehe());
        	sapProductionOrder.setProductType(materialModel.getProductName());//产品类别 - 产品简称
        	sapProductionOrder.setResistanceType(materialModel.getType());//导电类型
        	sapProductionOrder.setField3(materialModel.getSpecification());//规格
        	sapProductionOrder.setField1(materialModel.getDopant());
        }
        
        sapProductionOrder.setMaterialModel(materialModel);
        sapProductionOrder.setField2(productType);
        sapProductionOrder.setWorkShop(workShop);
        sapProductionOrder.setBaseMark(baseMark);
        sapProductionOrder.setFromMark(fromMark);
        try {
        	productionOrderService.saveOrUpdate(sapProductionOrder);
        }catch (Exception e) {
			e.printStackTrace();
		}

        return ResultGenerator.success();
    }
    
    
    @PostMapping("/initOrderByMaterial")
    public Result initOrderByMaterial() {
    	List<ProductionOrder> orderList = productionOrderService.findAll();
    	for (ProductionOrder entity : orderList) {
    		MaterialModel materialModel = materialModelService.findByCode(entity.getMatnr());
			try {
				if (materialModel != null) {
					MachineCapacityInfoDataDto dataDto = materialModelService.getMachineCapacityInfoDataDto(materialModel.getId());
					if (entity.getMachineCapacityId() == null && dataDto.getConductionType() != null && dataDto.getSpecification() != null && dataDto.getDopant() != null && dataDto.getSimpleName() != null) {
						MachineCapacityInfo info = machineCapacityInfoService.getMachineCapacityInfoJk(dataDto.getConductionType(), dataDto.getSpecification(), dataDto.getDopant(),dataDto.getSimpleName());
						entity.setMachineCapacityId(info.getId());
					} else {}

					entity.setWgbez(materialModel.getWgbez());
					entity.setMtbez(materialModel.getName());
					entity.setVtext(materialModel.getVtext());
					entity.setMatkl(materialModel.getMatkl());
					entity.setNtgew(materialModel.getNtgew());
					entity.setLaeng(materialModel.getLaeng());
					entity.setBreit(materialModel.getBreit());
					entity.setHoehe(materialModel.getHoehe());
					entity.setProductType(materialModel.getProductName());// 产品类别 - 产品简称
					entity.setResistanceType(materialModel.getType());// 导电类型
					entity.setField3(materialModel.getSpecification());// 规格
					entity.setField1(materialModel.getDopant());
				}
			} catch (Exception e) {}
            
            productionOrderService.saveOrUpdate(entity);
		}
    	return ResultGenerator.success();
    }
    

    @ApiOperation(value = "单晶生产订单导入")
    @PostMapping("/import")
    public Result orderImport(MultipartFile file) {
        Object objList = EasyExcelUtils.readExcel(file, new ProductionOrderImport(), 1, 1);

        if (objList != null){
            List<ProductionOrder> listOrder = new ArrayList<>();
            List<ProductionOrderImport> list = (List<ProductionOrderImport>) objList;
            checkRepeatOrder(list);//检验导入订单号是否有重复

            for (ProductionOrderImport productionOrderImport : list) {
                ProductionOrder productionOrder = productionOrderService.findByAufnr(productionOrderImport.getAufnr());
                if (productionOrder != null) {
                    return ResultGenerator.fail("订单编号已存在");
                }
                ProductModel productModel = productModelService.findByCode(productionOrderImport.getMatnr());
                if (productModel == null) {
                    return ResultGenerator.fail("产品料号【" + productionOrderImport.getMatnr() + "】，不存在");
                }
                DictionaryItem item = dictionaryItemService.findByThemeValueAndNameAndEnable("product_category", productionOrderImport.getProductType(), true);
                if (item == null) {
                    return ResultGenerator.fail("产品类别" + productionOrderImport.getProductType() + "未在数据字典中配置，关键字[product_category]");
                }
                MachineCapacityInfo machineCapacityInfo = machineCapacityInfoService.getMachineCapacityInfo(productModel.getConductionType(), item.getValue(), productModel.getSpecs(), productModel.getDopant());
                ProductionOrder sapProductionOrder = fromProductionOrderImport(productionOrderImport);
                sapProductionOrder.setProductType(item.getValue());
                sapProductionOrder.setMachineCapacityId(machineCapacityInfo.getId());
                sapProductionOrder.setProductModel(productModel);
                sapProductionOrder.setStatus("REL");
                sapProductionOrder.setProductionStatus(productionOrderImport.getProductionStatus());
                String aufnr = sapProductionOrder.getAufnr();
                String workShop = sapProductionOrder.getWorkShop();
                String productType = sapProductionOrder.getProductType();
                String baseMark = sapProductionOrder.getBaseMark();
                String fromMark = sapProductionOrder.getFromMark();

                sapProductionOrder.setField1(workShop);
                sapProductionOrder.setField2(productType);

                //todo:追溯改造
                if (StringUtils.isEmpty(baseMark)) {
                    return ResultGenerator.fail("基地【" + baseMark + "】，不存在");
                }
                if (StringUtils.isEmpty(fromMark)) {
                    return ResultGenerator.fail("追溯标识【" + fromMark + "】，不存在");
                } else if (!fromMark.matches("[A-Z]+")) {
                    return ResultGenerator.fail("追溯标识【" + fromMark + "】，必须是字母");
                }
                if (StringUtils.isEmpty(productType)) {
                    return ResultGenerator.fail("产品类型【" + productType + "】，不存在");
                } else if (!productType.matches("[A-Z]+") && productType.length() == 2) {
                    return ResultGenerator.fail("产品类型【" + productType + "】，必须是字母");
                }
                if (StringUtils.isEmpty(workShop)) {
                    return ResultGenerator.fail("车间【" + workShop + "】，不存在");
                }

                listOrder.add(sapProductionOrder);
            }
            productionOrderService.saveAll(listOrder);
        }

        return ResultGenerator.success();
    }

    private void checkRepeatOrder(List<ProductionOrderImport> list) {
        Map<String, Integer> map = new HashMap<>();
        for (ProductionOrderImport productionOrderImport : list) {
            map.put(productionOrderImport.getAufnr(), map.getOrDefault(productionOrderImport.getAufnr(), 0) + 1);
        }
        List<String> collect = map.entrySet().stream().filter(item -> item.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());
        if (collect.size() > 0) {
            throw new RuntimeException("Excel中存在重复的订单"+collect);
        }
    }

    private ProductionOrder fromProductionOrderImport(ProductionOrderImport productionOrderImport) {
        return modelMapper.map(productionOrderImport, ProductionOrder.class);
    }

    @ApiOperation(value = "更新工单信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "sapProductionOrder") ProductionOrderDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        ProductionOrder entity = productionOrderService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        //已在排程中的订单不允许修改
        List<ProductionSchedule> byOderId = productionScheduleService.findByOderId(dto.getId());
        if(null != byOderId && byOderId.size() > 0){
            return ResultGenerator.fail("订单已排程不允许修改");
        }
        try {
        	
            ProductionOrder entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, "productModel,materialModel", null));
            
            MaterialModel materialModel = materialModelService.findByCode(entity.getMatnr());
			try {
				if (materialModel != null) {
					MachineCapacityInfoDataDto dataDto = materialModelService.getMachineCapacityInfoDataDto(materialModel.getId());
					if (dataDto.getConductionType() != null && dataDto.getSpecification() != null && dataDto.getDopant() != null && dataDto.getSimpleName() != null) {
						MachineCapacityInfo info = machineCapacityInfoService.getMachineCapacityInfoJk(dataDto.getConductionType(), dataDto.getSpecification(), dataDto.getDopant(),dataDto.getSimpleName());
						entity.setMachineCapacityId(info.getId());
					} else {
						return ResultGenerator.fail("非计划生产物料号,请重新选择");
					}

					entity.setWgbez(materialModel.getWgbez());
					entity.setMtbez(materialModel.getName());
					entity.setVtext(materialModel.getVtext());
					entity.setMatkl(materialModel.getMatkl());
					entity.setNtgew(materialModel.getNtgew());
					entity.setLaeng(materialModel.getLaeng());
					entity.setBreit(materialModel.getBreit());
					entity.setHoehe(materialModel.getHoehe());
					entity.setProductType(materialModel.getProductName());// 产品类别 - 产品简称
					entity.setResistanceType(materialModel.getType());// 导电类型
					entity.setField3(materialModel.getSpecification());// 规格
					entity.setField1(materialModel.getDopant());
				}
			} catch (Exception e) {}
            
            productionOrderService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
        	e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除sapProductionOrder")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (Integer id : ids) {
            productionOrderService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "调整生产状态")
    @PostMapping("/updateProductionStatus")
    public Result updateProductionStatus(@ApiParam(value = "id", type = "query") @RequestParam long id,
                                         @ApiParam(value = "productionStatus", type = "query") @RequestParam boolean productionStatus) {
        if (id <= 0) {
            return ResultGenerator.fail("id不符合规范");
        }
        ProductionOrder entity = productionOrderService.get(id);
        if (entity == null) {
            return ResultGenerator.fail("订单信息不存在");
        }
        if ("CLOSE".equals(entity.getStatus())) {
            return ResultGenerator.fail("订单已是关闭状态不允许开启生产");
        }
        try {
            entity.setProductionStatus(productionStatus);
            productionOrderService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("单晶订单状态修改", e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "模板文件下载")
    @PostMapping("/download")
    @TokenNotValidation
    public void download(HttpServletResponse response) {
        String path = "template/单晶订单导入模版.xlsx";
        ExcelUtil.download1(path, response);
    }

    @Jinko(author = "yyl", value = "根据成本中心或计划工单获取计划订单详情")
    @ApiOperation(value = "根据成本中心或计划工单获取计划订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_EQ_workType", value = "成本中心类别", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_aufnr", value = "计划工单", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_productModel.code", value = "产品模型_物料编码", dataType = "string", paramType = "query"),
    })
    @GetMapping("/getListByWorkType")
    public Result<List<ProductionOrderDto>> getListByWorkType(ServletRequest request) {
        Specification<ProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, ProductionOrder.class);
        List<ProductionOrder> sapProductionOrders = productionOrderService.findByExampleSort(specification,  Sort.by(Sort.Direction.DESC, "id"));
        List<ProductionOrderDto> productionOrderDtos = sapProductionOrders.stream()
                .map(sapProductionOrder -> toLazyDto(sapProductionOrder))
                .collect(Collectors.toList());
        return ResultGenerator.success(productionOrderDtos);
    }

    @Jinko(author = "yyl", value = "根据计划工单获取计划订单详情")
    @ApiOperation(value = "根据计划工单获取计划订单详情")
    @GetMapping("/getListByAufnr")
    public Result<ProductionOrderDto> getListByWorkType(@RequestParam String aufnr) {
        ProductionOrder productionOrder = productionOrderService.findByAufnr(aufnr);
        ProductionOrderDto productionOrderDto = toLazyDto(productionOrder);
        return ResultGenerator.success(productionOrderDto);
    }

    @Jinko(author = "yyl", value = "根据计划工单集合获取计划订单详情")
    @ApiOperation(value = "根据计划工单集合获取计划订单详情")
    @GetMapping("/getListByAufnrs")
    public Result<List<ProductionOrderDto>> getListByAufnrs(@RequestParam List<String> aufnrs) {
        List<ProductionOrder> sapProductionOrders = productionOrderService.findByAufnrs(aufnrs);
        sapProductionOrders.forEach(entity->{
           if(StringUtils.isBlank(entity.getZorientationind())){
               entity.setZorientationind("非定向");
           }
        });
        List<ProductionOrderDto> productionOrderDtos = sapProductionOrders.stream()
                .map(sapProductionOrder -> toLazyDto(sapProductionOrder))
                .collect(Collectors.toList());
        return ResultGenerator.success(productionOrderDtos);
    }

    @Jinko(author = "yyl", value = "根据计划工单获取车间value和定向标识")
    @ApiOperation(value = "根据计划工单获取车间value和定向标识")
    @GetMapping("/getWorkShopValueAndDirectionalSign")
    public Result<Map<String, String>> getWorkShopValueAndDirectionalSign(@RequestParam String aufnr) {
        Map<String, String> workShopValue = productionOrderService.getWorkShopValue(aufnr);
        return ResultGenerator.success(workShopValue);
    }

    @Jinko(author = "yyl", value = "根据副产品订单号获取主产品订单详情")
    @ApiOperation(value = "根据副产品订单号获取主产品订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workType", value = "成本中心类别", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "aufnr", value = "副产品计划工单", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "副产品计划工单是否开启状态", dataType = "string", paramType = "query"),
    })
    @GetMapping("/getListByWorkTypeAndAufnr")
    public Result<List<ProductionOrderDto>> getListByWorkTypeAndAufnr(@RequestParam("workType") String workType,
                                                                      @RequestParam("aufnr") String aufnr,
                                                                      @RequestParam("status") String status
    ) {
        List<ProductionOrder> sapProductionOrders = productionOrderService.getListByWorkTypeAndAufnr(workType, status, aufnr);
        List<ProductionOrderDto> productionOrderDtos = sapProductionOrders.stream()
                .map(sapProductionOrder -> toLazyDto(sapProductionOrder))
                .collect(Collectors.toList());
        return ResultGenerator.success(productionOrderDtos);
    }

    @Jinko(author = "yyl", value = "通过主产品查询不同类型工单列表")
    @ApiOperation(value = "通过主产品查询不同类型工单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_EQ_workType", value = "成本中心类别", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_aufnr", value = "计划工单", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_matnr", value = "产品料号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_gstrp", value = "开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_gltrp", value = "结束时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listBySearchConditions")
    public Result<List<ProductionOrderDto>> listBySearchConditions(ServletRequest request) {
        Specification<ProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, ProductionOrder.class);
        List<ProductionOrder> sapProductionOrders = productionOrderService.findByExampleSort(specification, null);
        if (CollectionUtils.isEmpty(sapProductionOrders)) {
            throw new BusinessException("没有查询到对应计划工单!");
        }
        List<ProductionOrderDto> productionOrderDtos = sapProductionOrders.stream()
                .map(sapProductionOrder -> toLazyDto(sapProductionOrder))
                .collect(Collectors.toList());
        return ResultGenerator.success(productionOrderDtos);
    }


    public ProductionOrderDto toLazyDto(ProductionOrder entity) {
        return modelMapper.map(entity, ProductionOrderDto.class);
    }

    public ProductionOrderDto toEagerDto(ProductionOrder entity) {
        ProductionOrderDto dto = modelMapper.map(entity, ProductionOrderDto.class);
        return dto;
    }

    public ProductionOrder fromDto(ProductionOrderDto dto) {
        return modelMapper.map(dto, ProductionOrder.class);
    }


}
