package com.sw.mes.itemclean.clean.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.mes.core.dto.erp.ErpOrderDto;
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.itemclean.clean.domain.MaterialGroup;
import com.sw.mes.itemclean.clean.domain.MaterialPlanOrder;
import com.sw.mes.itemclean.clean.dto.MaterialGroupDto;
import com.sw.mes.itemclean.clean.dto.MaterialProductionOrderDto;
import com.sw.mes.itemclean.clean.service.MaterialPlanOrderService;
import io.swagger.annotations.*;
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.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Api(tags = "清洗计划工单")
@RequestMapping("/clean/MaterialPlanOrder")
@RestController
public class MaterialPlanOrderController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialPlanOrderService baseService;

    @ApiOperation(value = "获取列表")
    @RequestMapping(path = "/get/list", method = RequestMethod.GET)
    public Result getMaterialPlanOrderList() {
        return ResultGenerator.success(baseService.getList());
    }

    @ApiOperation(value = "获取", response = MaterialPlanOrder.class)
    @RequestMapping(path = "/get/{id}", method = RequestMethod.GET)
    public Result getMaterialPlanOrder(@PathVariable Integer id) {
        return ResultGenerator.success((baseService.getById(id)));
    }

    @ApiOperation(value = "新增", response = MaterialPlanOrder.class)
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public Result insertMaterialPlanOrder(@RequestBody MaterialPlanOrder materialPlanOrder) {
        baseService.insert(materialPlanOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除")
    @RequestMapping(path = "/delete/{id}", method = RequestMethod.POST)
    public Result deleteMaterialPlanOrder(@PathVariable Integer id) {
        baseService.delete(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "修改")
    @RequestMapping(path = "/activeUpdate", method = RequestMethod.POST)
    public Result activeUpdateMaterialPlanOrder(@RequestBody MaterialPlanOrder materialPlanOrder) {
        baseService.activeUpdate(materialPlanOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建清洗计划工单")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "清洗工单对象") MaterialProductionOrderDto productionOrderDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialPlanOrder productionOrder = baseService.findByAufnr(productionOrderDto.getAufnr());

        if (productionOrder != null) {
            return ResultGenerator.fail("订单编号已存在");
        }

        MaterialPlanOrder materialPlanOrder = fromDto(productionOrderDto);

        if (StringUtils.isBlank(productionOrderDto.getStatus()))
            materialPlanOrder.setStatus("REL");
        if (productionOrderDto.getProductionStatus() == null) {

            materialPlanOrder.setProductionStatus(false);

        }
        baseService.saveOrUpdate(materialPlanOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "关闭订单")
    @GetMapping("/closeOrder/{id}")
    public Result closeOrder(@PathVariable @ApiParam(value = "id") Long id) {
        MaterialPlanOrder materialPlanOrder = baseService.getById(id);
        if (null == materialPlanOrder) {
            return ResultGenerator.fail("该订单不存在");
        }
        materialPlanOrder.setStatus("CLOSE");
        materialPlanOrder.setCreateDate(new Date());
        materialPlanOrder.setProductionStatus(false);
        baseService.activeUpdate(materialPlanOrder);
        return ResultGenerator.success();
    }


    @ApiOperation(value = "更新工单信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "sapProductionOrder") MaterialProductionOrderDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        MaterialPlanOrder entity = baseService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            MaterialPlanOrder entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            baseService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "清洗计划工单分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<MaterialProductionOrderDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialPlanOrder> queryWrapper = DynmaicQueryWrapper.searchFilter(request, MaterialPlanOrder.class);
        Page<MaterialPlanOrder> listPage = baseService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialProductionOrderDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @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不符合规范!");
        }
        MaterialPlanOrder entity = baseService.getById(id);
        if (entity == null) {
            return ResultGenerator.fail("订单信息不存在");
        }
        if ("CLOSE".equals(entity.getStatus())) {
            return ResultGenerator.fail("订单已是关闭状态不允许开启生产");
        }

        entity.setProductionStatus(productionStatus);
        baseService.saveOrUpdate(entity);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "清洗计划工单导出")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, HttpServletResponse response) {
        //分页查询
        try {
            QueryWrapper<MaterialPlanOrder> queryWrapper = DynmaicQueryWrapper.searchFilter(request, MaterialPlanOrder.class);
            List<MaterialPlanOrder> list = baseService.list(queryWrapper);
            List<MaterialProductionOrderDto> dtos = list.stream()
                    .map(entity -> toLazyDto(entity))
                    .collect(Collectors.toList());

            EasyExcelUtils.write(response, MaterialProductionOrderDto.class, "导出原料清洗计划工单", "导出原料清洗计划工单", dtos);
        } catch (
                IOException e) {
            throw new RuntimeException("过站履历导出失败，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation(value = "处理erp洗料订单")
    @PostMapping("/handleErpOrder")
    public Result handleErpOrder(@RequestBody List<ErpOrderDto> xlErpOrderDto) {
        Result result;
        try {
            result = baseService.handleErpOrder(xlErpOrderDto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return result;
    }

    public MaterialPlanOrder fromDto(MaterialProductionOrderDto dto) {
        return modelMapper.map(dto, MaterialPlanOrder.class);
    }


    public MaterialProductionOrderDto toLazyDto(MaterialPlanOrder entity) {
        return modelMapper.map(entity, MaterialProductionOrderDto.class);
    }
}