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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

import cc.cczn.matrix.commons.extra.jpa.BaseExtraEntity;
import com.sw.mes.base.factory.product.dto.NewProductModelDetailDtos;
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.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.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.NewProductModelDetail;
import com.sw.mes.base.factory.product.entity.ProductModel;
import com.sw.mes.base.factory.product.service.NewProductModelDetailService;
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.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.utils.ExcelUtil;
import com.sw.mes.yb.plan.dto.YbProductionOrderDto;
import com.sw.mes.yb.plan.dto.YbProductionOrderImport;
import com.sw.mes.yb.plan.entity.YbProductionOrder;
import com.sw.mes.yb.plan.service.YbProductionOrderService;

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("/ybProductionOrder")
@Slf4j
@Api(description = "圆棒生产订单接口")
public class YbProductionOrderController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private YbProductionOrderService ybProductionOrderService;

    @Autowired
    private ProductModelService productModelService;

    @Autowired
    private MachineCapacityInfoService machineCapacityInfoService;

    @Autowired
    private DictionaryItemService dictionaryItemService;
    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private NewProductModelDetailService newProductModelDetailService;

    @ApiOperation(value = "分页查询圆棒订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<YbProductionOrderDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<YbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, YbProductionOrder.class);
        Page<YbProductionOrder> page = ybProductionOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<YbProductionOrderDto> 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<YbProductionOrderDto>> completionStatus(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<YbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, YbProductionOrder.class);
        Page<YbProductionOrder> page = ybProductionOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<YbProductionOrderDto> dtos = page.getContent().stream()
                .map(this::toLazyCompletionDto)
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    public YbProductionOrderDto toLazyCompletionDto(YbProductionOrder 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);

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

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

    @ApiOperation(value = "工单详细信息")
    @GetMapping("/{id}")
    public Result<YbProductionOrderDto> get(@PathVariable @ApiParam(value = "sapProductionOrderid") Long id) {
        YbProductionOrder sapProductionOrder = ybProductionOrderService.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) {
        YbProductionOrder sapProductionOrder = ybProductionOrderService.get(id);
        if (null == sapProductionOrder) {
            return ResultGenerator.fail("该订单不存在");
        }
        sapProductionOrder.setStatus("CLOSE");
        sapProductionOrder.setCreateDate(new Date());
        sapProductionOrder.setProductionStatus(false);
        ybProductionOrderService.close(sapProductionOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建工单")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "sapProductionOrder对象") YbProductionOrderDto productionOrderDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        YbProductionOrder productionOrder = ybProductionOrderService.findByAufnr(productionOrderDto.getAufnr());
        if (productionOrder != null) {
            return ResultGenerator.fail("订单编号已存在");
        }
        ProductModel productModel = productModelService.findByCode(productionOrderDto.getMatnr());
        if (productModel == null) {
            return ResultGenerator.fail("产品料号【" + productionOrderDto.getMatnr() + "】，不存在");
        }
        
        
        

        MaterialModel materialModel = materialModelService.findByCode(productionOrderDto.getMatnr());
        
        MachineCapacityInfoDataDto dataDto = materialModelService.getMachineCapacityInfoDataDto(materialModel.getId());
        MachineCapacityInfo info = machineCapacityInfoService.getMachineCapacityInfoJk(dataDto.getConductionType(), dataDto.getSpecification(),dataDto.getDopant(),dataDto.getSimpleName());
        productionOrderDto.setMachineCapacityId(info.getId());
        YbProductionOrder sapProductionOrder = fromDto(productionOrderDto);
        sapProductionOrder.setProductModel(productModel);


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

        return ResultGenerator.success();
    }

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

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

            for (YbProductionOrderImport productionOrderImport : list) {
                YbProductionOrder productionOrder = ybProductionOrderService.findByAufnr(productionOrderImport.getAufnr());
                if (productionOrder != null) {
                    return ResultGenerator.fail("订单编号已存在");
                }
                ProductModel productModel = productModelService.findByCode(productionOrderImport.getMatnr());
                if (productModel == null) {
                    return ResultGenerator.fail("产品料号【" + productionOrderImport.getMatnr() + "】，不存在");
                }

                MaterialModel materialModel = materialModelService.findByCode(productionOrderImport.getMatnr());
                
                MachineCapacityInfoDataDto dataDto = materialModelService.getMachineCapacityInfoDataDto(materialModel.getId());
        	    MachineCapacityInfo info = machineCapacityInfoService.getMachineCapacityInfoJk(dataDto.getConductionType(), dataDto.getSpecification(),dataDto.getDopant(),dataDto.getSimpleName());
                

                YbProductionOrder 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.setMachineCapacityId(info.getId());
                sapProductionOrder.setProductModel(productModel);
                sapProductionOrder.setStatus("REL");
                sapProductionOrder.setProductionStatus(productionOrderImport.getProductionStatus());
//                if (sapProductionOrder.getProductionStatus()){
//                    //查询范围时间与料号 是否 存在冲突的订单
//                    List<YbProductionOrder> listOrders = ybProductionOrderService.findByProductCodeAndTime(sapProductionOrder.getMatnr(), sapProductionOrder.getGstrp(), sapProductionOrder.getGltrp());
//                    if (listOrders.size() > 0){
//                        return ResultGenerator.fail("存在料号"+sapProductionOrder.getMatnr()+"正在生产的订单，订单号为"+StringUtils.join(listOrders.stream().map(YbProductionOrder::getAufnr).collect(Collectors.toList())));
//                    }
//                }
                listOrder.add(sapProductionOrder);
            }
            ybProductionOrderService.saveAll(listOrder);
        }

        return ResultGenerator.success();
    }

    private void checkRepeatOrder(List<YbProductionOrderImport> list) {
        Map<String, Integer> map = new HashMap<>();
        for (YbProductionOrderImport 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 YbProductionOrder fromProductionOrderImport(YbProductionOrderImport productionOrderImport) {
        return modelMapper.map(productionOrderImport, YbProductionOrder.class);
    }

    @ApiOperation(value = "更新工单信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "sapProductionOrder") YbProductionOrderDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        YbProductionOrder entity = ybProductionOrderService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            YbProductionOrder entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
//            if (entity.getProductionStatus()){
//                //查询范围时间与料号 是否 存在冲突的订单
//                List<YbProductionOrder> listOrders = ybProductionOrderService.findByProductCodeAndTime(entity.getMatnr(), entity.getGstrp(), entity.getGltrp());
//                if (listOrders.size() > 0){
//                    return ResultGenerator.fail("存在料号"+entity.getMatnr()+"正在生产的订单，订单号为"+StringUtils.join(listOrders.stream().map(YbProductionOrder::getAufnr).collect(Collectors.toList())));
//                }
//            }
            ybProductionOrderService.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) {
            ybProductionOrderService.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不符合规范");
        }
        YbProductionOrder entity = ybProductionOrderService.get(id);
        if (entity == null) {
            return ResultGenerator.fail("订单信息不存在");
        }
        if ("CLOSE".equals(entity.getStatus())) {
            return ResultGenerator.fail("订单已是关闭状态不允许开启生产");
        }
        try {
//            if (productionStatus){
//                //查询范围时间与料号 是否 存在冲突的订单
//                List<YbProductionOrder> listOrders = ybProductionOrderService.findByProductCodeAndTime(entity.getMatnr(), entity.getGstrp(), entity.getGltrp());
//                if (listOrders.size() > 0){
//                    return ResultGenerator.fail("存在料号"+entity.getMatnr()+"正在生产的订单，订单号为"+StringUtils.join(listOrders.stream().map(YbProductionOrder::getAufnr).collect(Collectors.toList())));
//                }
//            }
            entity.setProductionStatus(productionStatus);
            ybProductionOrderService.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_zarbplLb", value = "成本中心", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_aufnr", value = "计划工单", dataType = "string", paramType = "query"),
    })
    @GetMapping("/getListByZarbplLb")
    public Result<List<YbProductionOrderDto>> getListByZarbplLb(ServletRequest request) {
        Specification<YbProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, YbProductionOrder.class);
        List<YbProductionOrder> sapProductionOrders = ybProductionOrderService.findByExampleSort(specification, null);
        List<YbProductionOrderDto> 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_categories", value = "产品详情模型主副产品类别", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_productModel.code", value = "产品模型_物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "conductionType", value = "产品模型_导电型号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "dopant", value = "产品模型_掺杂剂", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "directionalSign", value = "产品模型_定向标识", dataType = "string", paramType = "query"),
    })
    @GetMapping("/productModelDetailCodeList")
    public Result<NewProductModelDetailDtos> productModelDetailCodeList(ServletRequest request) {
        Specification<NewProductModelDetail> specification = DynamicSpecifications.bySearchFilter(request, NewProductModelDetail.class);
        String conductionType = request.getParameter("conductionType");
        String dopant = request.getParameter("dopant");
        String directionalSign = request.getParameter("directionalSign");
        List<NewProductModelDetail> list = newProductModelDetailService.findByExampleSort(specification, null);
        NewProductModelDetailDtos newProductModelDetailDtos = new NewProductModelDetailDtos();
        newProductModelDetailDtos.setNewProductModelDetails(list);
        newProductModelDetailDtos.setDopant(dopant);
        newProductModelDetailDtos.setConductionType(conductionType);
        newProductModelDetailDtos.setDirectionalSign(directionalSign);
        return ResultGenerator.success(newProductModelDetailDtos);
    }

    public YbProductionOrderDto toLazyDto(YbProductionOrder entity) {
        return modelMapper.map(entity, YbProductionOrderDto.class);
    }

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

    public YbProductionOrder fromDto(YbProductionOrderDto dto) {
        return modelMapper.map(dto, YbProductionOrder.class);
    }


}
