package com.sw.mes.plan.controller;

import com.sw.mes.base.factory.init.entity.MachineCapacityInfo;
import com.sw.mes.base.factory.init.service.MachineCapacityKfinfoService;
import com.sw.mes.base.factory.product.entity.FbProductModel;
import com.sw.mes.base.factory.product.entity.ProductModel;
import com.sw.mes.base.factory.product.service.FbProductModelService;
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.TokenNotValidation;
import com.sw.mes.core.dto.erp.ErpOrderDto;
import com.sw.mes.core.dto.mes.pc.fb.FbProductionOrderDto;
import com.sw.mes.core.entity.SearchFilter;
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.*;
import com.sw.mes.plan.dto.FbProductionOrderImport;
import com.sw.mes.plan.dto.ProductionOrderCountDto;
import com.sw.mes.plan.dto.ProductionOrderDto;
import com.sw.mes.plan.entity.FbProductionOrder;
import com.sw.mes.plan.service.FbProductionOrderService;
import com.sw.mes.plan.service.FbProductionScheduleService;
import com.sw.mes.scheduled.DeviceInspectPlanTask;
import com.sw.mes.utils.ExcelUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
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.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


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

    @Autowired
    private FbProductionOrderService productionOrderService;

    @Autowired
    private FbProductModelService fbProductModelService;

    @Autowired
    private FbProductionScheduleService productionScheduleService;

    @Autowired
    private MachineCapacityKfinfoService machineCapacityKfinfoService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @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<FbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, FbProductionOrder.class);
        Page<FbProductionOrder> 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 = "导出方棒计划工单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_LIKE_aufnr", value = "订单编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_matnr", value = "产品料号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_gstrp", value = "计划(开始时间)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_gltrp", value = "计划(结束时间)", dataType = "string", paramType = "query"),
    })
    @GetMapping("/export")
    public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
        try {
            Specification<FbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, FbProductionOrder.class);
            List<FbProductionOrder> list = productionOrderService.findByExampleSort(specification, Sort.by(Sort.Direction.DESC,"id"));
            List<ProductionOrderDto> dtos = list.stream()
                    .map(entity -> toLazyDto(entity))
                    .collect(Collectors.toList());

            EasyExcelUtils.write(response, ProductionOrderDto.class, "导出方棒计划工单", "导出方棒计划工单", dtos);
        } catch (Exception e) {
            throw new RuntimeException("导出方棒计划工单失败，错误信息：" + e.getMessage());
        }
    }




    @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<FbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, FbProductionOrder.class,
                new SearchFilter("productionStatus", SearchFilter.Operator.EQ, true));
        Page<FbProductionOrder> 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 = "分页查询圆棒订单完成情况")
    @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<FbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, FbProductionOrder.class);
        Page<FbProductionOrder> 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(FbProductionOrder entity) {
        LinkedList<CompletionStatusDto> completionStatusDtos = new LinkedList<>();
        CompletionStatusDto completionStatusDto = new CompletionStatusDto();
        completionStatusDto.setName("在制品总数");
        completionStatusDto.setCount(BigDecimal.valueOf(0));
        completionStatusDtos.add(completionStatusDto);

        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<FbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, FbProductionOrder.class);
        List<FbProductionOrder> sapProductionOrders = productionOrderService.findByExampleSort(specification, null);
        List<ProductionOrderDto> productionOrderDtos = sapProductionOrders.stream()
                .map(sapProductionOrder -> toLazyDto(sapProductionOrder))
                .collect(Collectors.toList());
        return ResultGenerator.success(productionOrderDtos);
    }

    @ApiOperation(value = "通过订单编号获取方棒订单")
    @PostMapping("/findByAufnr")
    public Result<FbProductionOrderDto> findByAufnr(@RequestBody FbProductionOrderDto fbProductionOrderDto) {
        FbProductionOrder fbProductionOrder1 = productionOrderService.findByAufnr(fbProductionOrderDto.getAufnr());
        FbProductionOrderDto dto = null;
        if(null != fbProductionOrder1) {
            dto = modelMapper.map(fbProductionOrder1, FbProductionOrderDto.class);
        }
        return ResultGenerator.success(dto);
    }

    @ApiOperation(value = "工单详细信息")
    @GetMapping("/{id}")
    public Result<ProductionOrderDto> get(@PathVariable @ApiParam(value = "sapProductionOrderid") Long id) {
        FbProductionOrder 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) {
        FbProductionOrder 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());
        }
        FbProductionOrder productionOrder = productionOrderService.findByAufnr(productionOrderDto.getAufnr());
        if (productionOrder != null) return ResultGenerator.fail("订单编号已存在");
        FbProductModel fbproductModel = fbProductModelService.findByProductNo(productionOrderDto.getMatnr());
        if (fbproductModel == null) return ResultGenerator.fail("产品料号【" + productionOrderDto.getMatnr() + "】，不存在");

        FbProductionOrder sapProductionOrder = fromDto(productionOrderDto);
        sapProductionOrder.setFbProductModel(fbproductModel);
        if (StringUtils.isBlank(productionOrderDto.getStatus()))
            sapProductionOrder.setStatus("REL");
        if (productionOrderDto.getProductionStatus() == null)
            sapProductionOrder.setProductionStatus(false);
//        if (sapProductionOrder.getProductionStatus()){
//            //查询范围时间与料号 是否 存在冲突的订单
//            List<FbProductionOrder> listOrders = productionOrderService.findByProductCodeAndTime(sapProductionOrder.getMatnr(), sapProductionOrder.getGstrp(), sapProductionOrder.getGltrp());
//            if (listOrders.size() > 0){
//                return ResultGenerator.fail("存在料号"+sapProductionOrder.getMatnr()+"正在生产的订单，订单号为"+StringUtils.join(listOrders.stream().map(FbProductionOrder::getAufnr).collect(Collectors.toList())));
//            }
//        }
        productionOrderService.saveOrUpdate(sapProductionOrder);
        return ResultGenerator.success();
    }


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

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

            for (FbProductionOrderImport productionOrderImport : list) {
                FbProductionOrder productionOrder = productionOrderService.findByAufnr(productionOrderImport.getAufnr());
                if (productionOrder != null) {
                    return ResultGenerator.fail("订单编号已存在");
                }
                FbProductModel productModel = fbProductModelService.findByProductNo(productionOrderImport.getMatnr());
                if (productModel == null) {
                    return ResultGenerator.fail("产品料号【" + productionOrderImport.getMatnr() + "】，不存在");
                }
                FbProductionOrder sapProductionOrder = fromProductionOrderImport(productionOrderImport);
                DictionaryItem item = dictionaryItemService.findByThemeValueAndNameAndEnable("product_category", productionOrderImport.getProductType(), true);
                if (item == null){
                    return ResultGenerator.fail("产品类别"+productionOrderImport.getProductType()+"未在数据字典中配置，关键字[product_category]");
                }
                sapProductionOrder.setProductType(item.getValue());
                sapProductionOrder.setFbProductModel(productModel);
                sapProductionOrder.setStatus("REL");
                sapProductionOrder.setProductionStatus(productionOrderImport.getProductionStatus());
//                if (sapProductionOrder.getProductionStatus()){
//                    //查询范围时间与料号 是否 存在冲突的订单
//                    List<FbProductionOrder> listOrders = productionOrderService.findByProductCodeAndTime(sapProductionOrder.getMatnr(), sapProductionOrder.getGstrp(), sapProductionOrder.getGltrp());
//                    if (listOrders.size() > 0){
//                        return ResultGenerator.fail("存在料号"+sapProductionOrder.getMatnr()+"正在生产的订单，订单号为"+StringUtils.join(listOrders.stream().map(FbProductionOrder::getAufnr).collect(Collectors.toList())));
//                    }
//                }
                listOrder.add(sapProductionOrder);
            }
            productionOrderService.saveAll(listOrder);
        }

        return ResultGenerator.success();
    }

    private void checkRepeatOrder(List<FbProductionOrderImport> list) {
        Map<String, Integer> map = new HashMap<>();
        for (FbProductionOrderImport 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 FbProductionOrder fromProductionOrderImport(FbProductionOrderImport productionOrderImport) {
        return modelMapper.map(productionOrderImport, FbProductionOrder.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不能为空");
        FbProductionOrder entity = productionOrderService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            FbProductionOrder entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
//            if (entity.getProductionStatus()){
//                //查询范围时间与料号 是否 存在冲突的订单
//                List<FbProductionOrder> listOrders = productionOrderService.findByProductCodeAndTime(entity.getMatnr(), entity.getGstrp(), entity.getGltrp());
//                if (listOrders.size() > 0){
//                    return ResultGenerator.fail("存在料号"+entity.getMatnr()+"正在生产的订单，订单号为"+StringUtils.join(listOrders.stream().map(FbProductionOrder::getAufnr).collect(Collectors.toList())));
//                }
//            }
            productionOrderService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            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不符合规范");
        FbProductionOrder entity = productionOrderService.get(id);
        if (entity == null) return ResultGenerator.fail("订单信息不存在");
        if ("CLOSE".equals(entity.getStatus())) return ResultGenerator.fail("订单已是关闭状态不允许开启生产");
        try {
//            if (productionStatus){
//                //查询范围时间与料号 是否 存在冲突的订单
//                List<FbProductionOrder> listOrders = productionOrderService.findByProductCodeAndTime(entity.getMatnr(), entity.getGstrp(), entity.getGltrp());
//                if (listOrders.size() > 0){
//                    return ResultGenerator.fail("存在料号"+entity.getMatnr()+"正在生产的订单，订单号为"+StringUtils.join(listOrders.stream().map(FbProductionOrder::getAufnr).collect(Collectors.toList())));
//                }
//            }
            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);
    }


    @ApiOperation(value = "处理erp下发订单")
    @PostMapping("/handleErpOrder")
    public Result handleErpOrder(@RequestBody @Valid @ApiParam(value = "fbErpOrderDto")List<ErpOrderDto> fbErpOrderDto){
        Result result = productionOrderService.handleErpOrder(fbErpOrderDto);
        return result;
    }


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

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

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


    @Autowired
    public DeviceInspectPlanTask deviceInspectPlanTask;

    @GetMapping("/testTask")
    public void testTask(){
        deviceInspectPlanTask.scheduleDeviceInspectPlanTask();
    }

}
