package com.sw.common.accessory.server.controller;
import com.sw.common.accessory.api.feignCilent.YbFeignClients;
import com.sw.common.accessory.server.dto.*;
import com.sw.common.accessory.server.entity.AccessoryProductionOrder;
import com.sw.common.accessory.server.service.AccessoryProductionOrderService;
import com.sw.common.accessory.server.service.AccessoryService;
import com.sw.common.accessory.utils.DateCountTools;
import com.sw.common.core.annotation.TokenNotValidation;
import com.sw.common.core.request.RequestPage;
import com.sw.common.core.response.ResponsePage;
import com.sw.common.core.response.Result;
import com.sw.common.core.response.ResultGenerator;
import com.sw.common.mybatisplus.entity.Page;
import com.sw.common.mybatisplus.utils.DynamicSpecifications;
import com.sw.common.mybatisplus.utils.PageUtil;
import com.sw.common.mybatisplus.utils.Specification;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lf
 * @description
 * @date 2024/3/9 19:59
 */
@RestController
@RequestMapping("/accessoryProductionOrder")
@Slf4j
@Api(tags = "石墨件排程工单关联对象")
public class AccessoryProductionOrderController {

    @Autowired
    private AccessoryProductionOrderService accessoryProductionOrderService;

    @Autowired
    private AccessoryService accessoryService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private DateCountTools dateCountTools;


    @ApiOperation(value = "分页查询石墨件排程工单关联对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<AccessoryProductionOrderDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<AccessoryProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, AccessoryProductionOrder.class);
        Page<AccessoryProductionOrder> page = accessoryProductionOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<AccessoryProductionOrderDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        List<AccessoryProductionOrderDto> collect = dtos.stream().filter(entity -> entity.isDel() == false).collect(Collectors.toList());
        ResponsePage<AccessoryProductionOrderDto> responsePage = new ResponsePage<>(collect, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取石墨件排程工单关联对象列表")
    @GetMapping("/listAll")
    public Result<List<AccessoryProductionOrderDto>> listAll(ServletRequest request) {
        Specification<AccessoryProductionOrder> specification = DynamicSpecifications.bySearchFilter(request, AccessoryProductionOrder.class);
        List<AccessoryProductionOrder> accessoryProductionOrders = accessoryProductionOrderService.findByExampleSort(specification, null);
        List<AccessoryProductionOrderDto> accessoryProductionOrderDtos = accessoryProductionOrders.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        List<AccessoryProductionOrderDto> collect = accessoryProductionOrderDtos.stream().filter(entity -> entity.isDel() == false).collect(Collectors.toList());
        return ResultGenerator.success(accessoryProductionOrderDtos);
    }

    @ApiOperation(value = "石墨件排程工单关联对象详细信息")
    @GetMapping("/{id}")
    public Result<AccessoryProductionOrderDto> get(@PathVariable @ApiParam(value = "石墨件排程工单关联对象id") Long id) {
        AccessoryProductionOrder accessoryProductionOrder = accessoryProductionOrderService.get(id);
        if (null == accessoryProductionOrder) {
            return ResultGenerator.fail("该石墨件排程工单关联对象不存在");
        }
        return ResultGenerator.success(toLazyDto(accessoryProductionOrder));
    }

    @ApiOperation(value = "通过id获取石墨件排程工单关联对象详细信息")
    @GetMapping("/findById")
    public Result<AccessoryProductionOrderDto> findById(@RequestParam @ApiParam(value = "石墨件排程工单关联对象id") Long id) {
        AccessoryProductionOrder accessoryProductionOrder = accessoryProductionOrderService.get(id);
        if (null == accessoryProductionOrder) {
            return ResultGenerator.fail("该石墨件排程工单关联对象不存在");
        }
        return ResultGenerator.success(toLazyDto(accessoryProductionOrder));
    }

    @ApiOperation(value = "通过料号和工单号和设备号获取石墨件排程工单关联对象详细信息")
    @GetMapping("/findMaterialCodeAndProductionNoAndDeviceCode")
    public Result<AccessoryProductionOrderDto> findMaterialCodeAndProductionNo(@RequestParam @ApiParam(value = "料号") String materialCode
            , @RequestParam @ApiParam(value = "工单号") String productionNo
            , @RequestParam @ApiParam(value = "设备号") String deviceCode) {
        AccessoryProductionOrder accessoryProductionOrder = accessoryProductionOrderService.findMaterialCodeAndProductionNo(materialCode, productionNo, deviceCode);
        if (null == accessoryProductionOrder) {
            return ResultGenerator.fail("该石墨件排程工单关联对象不存在");
        }
        return ResultGenerator.success(toLazyDto(accessoryProductionOrder));
    }

    @ApiOperation(value = "创建石墨件排程工单关联对象")
    @PostMapping("/create")
    @TokenNotValidation
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "创建石墨件排程工单关联对象dto") AccessoryProductionOrderDto dto) {
        return accessoryProductionOrderService.create(dto);
    }

    @ApiOperation(value = "修改石墨件排程工单关联对象")
    @PostMapping("/update")
    @TokenNotValidation
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "石墨件排程工单关联对象dto") AccessoryProductionOrderDto productionScheduleDto) {
        return accessoryProductionOrderService.update(productionScheduleDto);
    }


    @ApiOperation(value = "删除石墨件排程工单关联对象")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            accessoryProductionOrderService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "通过料号和工单开始时间和工单结束时间获取对应时间计算结果")
    @GetMapping("/findMaterialCodeAndStartTimeNoAndEndTime")
    public Result<ComputingTimeDto> findMaterialCodeAndStartTimeNoAndEndTime(@RequestParam @ApiParam(value = "料号") String materialCode
            , @RequestParam @ApiParam(value = "工单开始时间") Date startTime
            , @RequestParam @ApiParam(value = "工单结束时间") Date endTime) {
        ComputingTimeDto computingTimeDto = dateCountTools.computingTime(materialCode, startTime, endTime);
        if (null == computingTimeDto) {
            return ResultGenerator.fail("未获取到相关数据,请确认数据!");
        }
        return ResultGenerator.success(computingTimeDto);
    }

    @ApiOperation(value = "石墨件物料维度上报SAP接口(手动)")
    @PostMapping("/productionMaterialToSAP")
    public Result productionMaterialToSAP(@RequestBody @ApiParam(value = "工单对象") ProductionScheduleDto productionScheduleDto) {
        AccessoryProductionOrder orderNoId = accessoryProductionOrderService.findOrderNoId(productionScheduleDto.getId());
        if(ObjectUtils.isEmpty(orderNoId) || orderNoId.isMaterialDel()){
            return ResultGenerator.fail("石墨件成本中心消耗上报失败!");
        }
        return accessoryProductionOrderService.productionMaterialToSAPs(productionScheduleDto);
    }

    @ApiOperation(value = "石墨件物料维度上报SAP接口(自动)")
    @PostMapping("/automaticProductionMaterialToSAP")
//    @Scheduled(cron = "0 58 23 L * ?")
    public Result automaticProductionMaterialToSAP() {
        List<AccessoryProductionOrder> allMaterialOrderNo = accessoryProductionOrderService.findAllMaterialOrderNo();
        if(!CollectionUtils.isEmpty(allMaterialOrderNo)){
            allMaterialOrderNo.forEach(entity->{
                ProductionScheduleDto productionScheduleDto = new ProductionScheduleDto();
                productionScheduleDto.setId(entity.getOrderNoId());
                accessoryProductionOrderService.productionMaterialToSAPs(productionScheduleDto);
            });
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "石墨件工单维度上报SAP接口(手动)")
    @PostMapping("/productionOrderToSAP")
    public Result productionOrderToSAP(@RequestBody @ApiParam(value = "工单对象") ProductionScheduleDto productionScheduleDto) {
        AccessoryProductionOrder orderNoId = accessoryProductionOrderService.findOrderNoId(productionScheduleDto.getId());
        if(ObjectUtils.isEmpty(orderNoId) || orderNoId.isProductionDel()){
            return ResultGenerator.fail("石墨件工单工时上报失败!");
        }
        return accessoryProductionOrderService.productionOrderToSAPs(productionScheduleDto);
    }

    @ApiOperation(value = "石墨件工单维度上报SAP接口(自动)")
    @PostMapping("/automaticProductionOrderToSAP")
//    @Scheduled(cron = "0 58 23 L * ?")
    public Result automaticProductionOrderToSAP() {
        List<AccessoryProductionOrder> allProductionOrderNo = accessoryProductionOrderService.findAllProductionOrderNo();
        if(!CollectionUtils.isEmpty(allProductionOrderNo)){
            allProductionOrderNo.forEach(entity->{
                ProductionScheduleDto productionScheduleDto = new ProductionScheduleDto();
                productionScheduleDto.setId(entity.getOrderNoId());
                accessoryProductionOrderService.productionOrderToSAPs(productionScheduleDto);
            });
        }
        return ResultGenerator.success();
    }

    public AccessoryProductionOrder fromDto(AccessoryProductionOrderDto dto) {
        AccessoryProductionOrder accessoryProductionOrder = new AccessoryProductionOrder();
        BeanUtils.copyProperties(dto, accessoryProductionOrder);
        return accessoryProductionOrder;
    }

    public AccessoryProductionOrderDto toLazyDto(AccessoryProductionOrder entity) {
        AccessoryProductionOrderDto accessoryProductionOrderDto = new AccessoryProductionOrderDto();
        BeanUtils.copyProperties(entity, accessoryProductionOrderDto);
        return accessoryProductionOrderDto;
    }
}
