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


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.mes.core.annotation.Jinko;
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.DynmaicQueryWrapper;
import com.sw.mes.core.utils.EasyExcelUtils;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.itemclean.clean.domain.MaterialCleaningBasket;
import com.sw.mes.itemclean.clean.dto.*;
import com.sw.mes.itemclean.clean.domain.MaterialCleaning;
import com.sw.mes.itemclean.clean.mapper.MaterialCleaningMapper;
import com.sw.mes.itemclean.clean.service.MaterialCleaningService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/clean/materialCleaning")
@Slf4j
@Api(tags = "清洗")
public class MaterialCleaningController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialCleaningService materialCleaningService;

    @Autowired
    private MaterialCleaningMapper materialCleaningMapper;


    @Jinko(author = "yyl", value = "硅料加工记录-清洗上下料分页查询列表")
    @ApiOperation(value = "硅料加工记录-清洗上下料分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<MaterialCleaningDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialCleaning> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialCleaning.class);
        queryWrapper.orderByDesc("create_time");
        Page<MaterialCleaning> listPage = materialCleaningService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialCleaningDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }


    @Jinko(author = "yyl", value = "硅料加工记录-清洗记录-导出")
    @ApiOperation(value = "硅料加工记录-清洗记录-导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_LIKE_materialName", value = "物料名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialCode", value = "物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_productBatchNo", value = "PP号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "清洗上料开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_createTime", value = "清洗上料结束时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_downTime", value = "清洗下料开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_downTime", value = "清洗下料结束时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/export")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
            QueryWrapper<MaterialCleaning> queryWrapper = DynmaicQueryWrapper.searchFilter(request, MaterialCleaning.class);
            queryWrapper.orderByDesc("create_time");
            List<MaterialCleaning> List = materialCleaningService.list(queryWrapper);
            List<MaterialCleaningDto> dtos = List.stream()
                    .map(entity -> toLazyDto(entity))
                    .collect(Collectors.toList());
            EasyExcelUtils.write(response, MaterialCleaningDto.class, "清洗记录", "清洗记录", dtos);
        } catch (Exception e) {
            throw new RuntimeException("导出清洗记录失败，错误信息：" + e.getMessage());
        }
    }


    @ApiOperation(value = "获取所有列表")
    @GetMapping("/listAll")
    public Result<List<MaterialCleaningDto>> listAll(ServletRequest request) {
        QueryWrapper<MaterialCleaning> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialCleaning.class);
        List<MaterialCleaning> materialCleanings = materialCleaningService.list(queryWrapper);
        List<MaterialCleaningDto> materialCleaningDtos = materialCleanings.stream()
                .map(materialCleaning -> toLazyDto(materialCleaning))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialCleaningDtos);
    }

    @ApiOperation(value = "详细信息")
    @GetMapping("/{id}")
    public Result<MaterialCleaningDto> get(@PathVariable @ApiParam(value="设备类型id") Integer id) {
        MaterialCleaning materialCleaning = materialCleaningService.getById(id);
        if (null == materialCleaning)
            return ResultGenerator.fail("该对象不存在");
        return ResultGenerator.success(toEagerDto(materialCleaning));
    }

    @ApiOperation(value = "创建")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialCleaningDto materialCleaningDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialCleaning materialCleaning = fromDto(materialCleaningDto);
        materialCleaningService.saveOrUpdate(materialCleaning);
        return ResultGenerator.success();
    }

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

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

    @ApiOperation(value = "获取当前设备正在清洗任务信息")
    @GetMapping("/getCurrentCleanUpInfo")
    public Result<MaterialCleaningCurrentInfoDto> getCurrentCleanUpInfo(String deviceNo){
        MaterialCleaning materialCleaning = materialCleaningService.getCurrentCleanUpInfo(deviceNo);
        if (materialCleaning == null){
            return ResultGenerator.success();
        }
        MaterialCleaningDto materialCleaningDto = toEagerDto(materialCleaning);
        List<MaterialCleaning> list = materialCleaningService.getByDevice(deviceNo);
        if (list.size() > 1) {
            materialCleaningDto.setIsNewBatch(1);
        }else {
            materialCleaningDto.setIsNewBatch(0);
        }

        List<MaterialCleaningBasketDto> basketDtos = new ArrayList<>();
        List<MaterialCleaningBasket> baskets = materialCleaningService.getBasketInfoByCleanId(materialCleaning.getId());
        for (MaterialCleaningBasket basket : baskets) {
            MaterialCleaningBasketDto basketDto = toBasketDto(basket);
            basketDtos.add(basketDto);
        }
        MaterialCleaningCurrentInfoDto dto = new MaterialCleaningCurrentInfoDto(materialCleaningDto, basketDtos);
        return ResultGenerator.success(dto);
    }

    @ApiModelProperty(value = "原料清洗标记花篮")
    @PostMapping("/markBasket")
    public Result markBasket(@RequestBody @Valid IdDto idDto, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialCleaningService.markBasket(idDto.getId());
        return ResultGenerator.success();
    }

    @Jinko(author = "yyl", value = "新版原料清洗上料")
    @ApiOperation(value = "新版原料清洗上料")
    @PostMapping("/materialCleaningUp")
    public Result materialCleaningUp(@RequestBody @Valid MaterialCleaningUpDto dto, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialCleaningService.materialCleaningUp(dto);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "原料清洗花篮选择")
    @PostMapping("/materialCleaningBasketChoose") //(作废)
    public Result materialCleaningBasketChoose(@RequestBody @Valid MaterialCleaningBasketChooseDto dto, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialCleaningService.materialCleaningBasketChoose(dto);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "原料清洗批次完结")
    @PostMapping("/materialCleaningEnd")
    public Result materialCleaningEnd(@RequestBody @Valid IdDto id, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialCleaningService.materialCleaningEnd(id.getId());
        return ResultGenerator.success();
    }

    @ApiOperation(value = "新版原料清洗下料")
    @PostMapping("/materialCleaningPackaging")
    public Result materialCleaningPackaging(@RequestBody @Valid IdDto id, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialCleaningService.materialCleaningPackaging(id.getId());
        return ResultGenerator.success();
    }

    @ApiOperation(value = "新版原料清洗下料成箱打签")
    @PostMapping("/materialCleaningPackagingBox")
    public Result<PackingBoxInfoPrintDto> materialCleaningPackagingBox(@RequestBody MaterialCleaningToBoxDto dto, BindingResult bindingResult) {

        return ResultGenerator.success(materialCleaningService.materialCleaningPackagingBox(dto));
    }

    @Jinko(author = "yyl", value = "清洗上料-校验花篮号是否被清洗工序占用")
    @ApiOperation(value = "清洗上料-校验花篮号是否被清洗工序占用")
    @GetMapping("/getNotCleanByBoxNo")
    public Result getNotCleanByBoxNo(String boxNo) {
        MaterialCleaning cleaning = materialCleaningService.getNotCleanByBoxNo(boxNo);
        if (cleaning != null) {
            return ResultGenerator.fail("该花篮被清洗上下料工序占用");
        } else {
            return ResultGenerator.success();
        }
    }

    public MaterialCleaningDto toLazyDto(MaterialCleaning entity) {
        return modelMapper.map(entity, MaterialCleaningDto.class);
    }

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

    private MaterialCleaningBasketDto toBasketDto(MaterialCleaningBasket basket) {
        MaterialCleaningBasketDto dto = new MaterialCleaningBasketDto();
        dto.setId(basket.getId());
        dto.setBasketNo(basket.getBasketNo());
        dto.setStatus(basket.getStatus());
        dto.setCleanId(basket.getCleanId());
        dto.setCreateUser(basket.getCreateUser());
        dto.setCreateTime(basket.getCreateTime());
        dto.setUpdateUser(basket.getUpdateUser());
        dto.setUpdateTime(basket.getUpdateTime());
        dto.setDelFlag(basket.getDelFlag());
        return dto;
    }

    public MaterialCleaning fromDto(MaterialCleaningDto dto) {
        return modelMapper.map(dto, MaterialCleaning.class);
    }
}
