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


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.DynmaicQueryWrapper;
import com.sw.mes.core.utils.EasyExcelUtils;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.itemclean.clean.domain.MaterialCleaning;
import com.sw.mes.itemclean.clean.domain.MaterialStoreSignBox;
import com.sw.mes.itemclean.clean.domain.MaterialUnpacking;
import com.sw.mes.itemclean.clean.dto.*;
import com.sw.mes.itemclean.clean.domain.MaterialBroken;
import com.sw.mes.itemclean.clean.mapper.MaterialBrokenMapper;
import com.sw.mes.itemclean.clean.service.MaterialBrokenService;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/clean/materialBroken")
@Slf4j
@Api(tags = "破碎")
public class MaterialBrokenController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialBrokenService materialBrokenService;

    @Autowired
    private MaterialBrokenMapper materialBrokenMapper;

    @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<MaterialBrokenDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialBroken> queryWrapper = DynmaicQueryWrapper.searchFilter(request, MaterialBroken.class);
        Page<MaterialBroken> listPage = materialBrokenService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialBrokenDto> 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 = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/upAndDownListByPage")
    public Result<ResponsePage<MaterialBrokenUpAndDownDto>> upAndDownListByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        ResponsePage<MaterialBrokenUpAndDownDto> responsePage = new ResponsePage<>();
        BrokeUpAndDownParamQuery brokeUpAndDownParamQuery = new BrokeUpAndDownParamQuery();
        brokeUpAndDownParamQuery.setMaterialName(request.getParameter("search_LIKE_materialName"))
                .setMaterialCode(request.getParameter("search_EQ_materialCode"))
                .setProductBatchNo(request.getParameter("search_EQ_productBatchNo"))
                .setCreateStartTime(request.getParameter("search_GTE_upCreateTime"))
                .setCreateEndTime(request.getParameter("search_LT_upCreateTime"))
                .setDownCreateStartTime(request.getParameter("search_GTE_downCreateTime"))
                .setDownCreateEndTime(request.getParameter("search_LT_downCreateTime"));
        IPage<MaterialBrokenUpAndDownDto> iPage = new Page<>(requestPage.getPage(), requestPage.getRows());
        IPage<MaterialBrokenUpAndDownDto> brokenUpAndDownDtoIPage = materialBrokenService.queryList(iPage, brokeUpAndDownParamQuery);
        responsePage.setRows(brokenUpAndDownDtoIPage.getRecords());
        responsePage.setTotal(brokenUpAndDownDtoIPage.getTotal());
//        brokenUpAndDownDtoIPage.getRecords().forEach(entity->{
//            BigDecimal subtract = entity.getUpWeight().subtract(entity.getDownWeight());
//            entity.setDiffWeight(subtract);
//        });
        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_upCreateTime", value = "破碎上料开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_upCreateTime", value = "破碎上料结束时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_downCreateTime", value = "破碎下料开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_downCreateTime", value = "破碎下料结束时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/export")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
            BrokeUpAndDownParamQuery brokeUpAndDownParamQuery = new BrokeUpAndDownParamQuery();
            brokeUpAndDownParamQuery.setMaterialName(request.getParameter("search_LIKE_materialName"))
                    .setMaterialCode(request.getParameter("search_EQ_materialCode"))
                    .setProductBatchNo(request.getParameter("search_EQ_productBatchNo"))
                    .setCreateStartTime(request.getParameter("search_GTE_upCreateTime"))
                    .setCreateEndTime(request.getParameter("search_LT_upCreateTime"))
                    .setDownCreateStartTime(request.getParameter("search_GTE_downCreateTime"))
                    .setDownCreateEndTime(request.getParameter("search_LT_downCreateTime"));
            List<MaterialBrokenUpAndDownDto> list = materialBrokenService.queryListByParam(brokeUpAndDownParamQuery);
//            list.forEach(entity->{
//                BigDecimal subtract = entity.getUpWeight().subtract(entity.getDownWeight());
//                entity.setDiffWeight(subtract);
//            });
            EasyExcelUtils.write(response, MaterialBrokenUpAndDownDto.class, "破碎记录", "破碎记录", list);
        } catch (Exception e) {
            throw new RuntimeException("导出破碎记录失败，错误信息：" + e.getMessage());
        }
    }


    @ApiOperation(value = "获取所有列表")
    @GetMapping("/listAll")
    public Result<List<MaterialBrokenDto>> listAll(ServletRequest request) {
        QueryWrapper<MaterialBroken> queryWrapper = DynmaicQueryWrapper.searchFilter(request, MaterialBroken.class);
        List<MaterialBroken> materialBrokens = materialBrokenService.list(queryWrapper);
        List<MaterialBrokenDto> materialBrokenDtos = materialBrokens.stream()
                .map(materialBroken -> toLazyDto(materialBroken))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialBrokenDtos);
    }

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

    @ApiOperation(value = "创建")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialBrokenDto materialBrokenDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialBroken materialBroken = fromDto(materialBrokenDto);
        materialBrokenService.saveOrUpdate(materialBroken);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialBrokenDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        MaterialBroken entity = materialBrokenService.getById(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            MaterialBroken entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            materialBrokenService.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) {
            materialBrokenMapper.deleteById(id);
        }
        return ResultGenerator.success();
    }

    /**
     * 获取当前设备正在破碎任务信息
     *
     * @param deviceNo
     * @return
     */
    @ApiOperation(value = "新版获取当前设备正在破碎任务信息")
    @GetMapping("/getCurrentBrokenUpInfo")
    public Result<MaterialBrokenCurrentInfoDto> getCurrentBrokenUpInfo(String deviceNo) {
        MaterialBroken materialBroken = materialBrokenService.getCurrentBrokenUpInfo(deviceNo);
        if (materialBroken == null) {
            return ResultGenerator.success();
        }
        MaterialBrokenDto materialBrokenDto = toEagerDto(materialBroken);
//        List<MaterialBroken> list = materialBrokenService.getByDevice(deviceNo);
//        if (list.size() > 1) {
//            materialBrokenDto.setIsNewBatch(1);
//        }else {
//            materialBrokenDto.setIsNewBatch(0);
//        }
        //计算该机台的改生产批次在破碎机台上的余量
        BigDecimal subBrokenWeight = materialBrokenService.getSumWeightByBatchNo(materialBroken.getProductBatchNo(), deviceNo);
        materialBrokenDto.setSubWeight(subBrokenWeight);
        MaterialBrokenCurrentInfoDto dto = new MaterialBrokenCurrentInfoDto(materialBrokenDto);
        return ResultGenerator.success(dto);
    }

    /**
     * 新版破碎上料
     * materialCleaningPackaging
     *
     * @param dto
     * @param bindingResult
     * @return
     */
    @Jinko(author = "yyl", value = "新版原料破碎上料")
    @ApiOperation(value = "新版原料破碎上料")
    @PostMapping("/materialBrokenUp")
    public Result materialBrokenUp(@RequestBody @Valid MaterialBrokenUpDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialBrokenService.materialBrokenUp(dto);
        return ResultGenerator.success();
    }

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

    //todo:暂时不使用此接口,使用临时方案的接口
    @ApiOperation(value = "原料清洗下料，打签成箱")
    @PostMapping("/materialBrokenPackaging")
    public Result materialBrokenPackaging(@RequestBody @Valid BrokenDownDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialBrokenService.materialBrokenPackaging(dto);
        //TODO 打箱后返回什么？
        return ResultGenerator.success();
    }

    @Jinko(author = "yyl", value = "新版接口-破碎打签成箱")
    @ApiOperation(value = "新版接口-破碎打签成箱")
    @PostMapping("/materialBrokenToPackaging")
    public Result materialBrokenToPackaging(@RequestBody @Valid BrokenToPackDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ArrayList<Object> list = new ArrayList<>();
        //满足多个箱标打印要求
        for (int i = 0; i < dto.getBoxNum(); i++) {
            list.add(materialBrokenService.materialBrokenToPackaging(dto));
        }
        return ResultGenerator.success(list);
    }

    @Jinko(author = "yyl", value = "破碎上料-通过箱号/花篮号获取箱内物料信息")
    @ApiOperation(value = "破碎上料-通过箱号/花篮号获取箱内物料信息")
    @GetMapping("/getInfoByBoxNo")
    public Result<BoxInfoDto> getInfoByBoxNo(String boxNo) {
        BoxInfoDto boxInfoDto = materialBrokenService.getInfoByBoxNo(boxNo);
        if (boxInfoDto == null) {
            return ResultGenerator.fail("该箱号不存在可使用的物料");
        } else {
            return ResultGenerator.success(boxInfoDto);
        }
    }

    @Jinko(author = "yyl", value = "破碎下料-通过箱号/花篮号获取破碎上料内物料信息")
    @ApiOperation(value = "破碎下料-通过箱号/花篮号获取破碎上料内物料信息")
    @GetMapping("/getBrokenInfoByBoxNo")
    public Result<MaterialBroken> getBrokenInfoByBoxNo(String boxNo) {
        MaterialBroken broken = materialBrokenService.getBrokenInfoByBoxNo(boxNo);
        if (broken == null) {
            return ResultGenerator.fail("该箱号不存在可使用的破碎物料");
        } else {
            return ResultGenerator.success(broken);
        }
    }


    public MaterialBrokenDto toLazyDto(MaterialBroken entity) {
        return modelMapper.map(entity, MaterialBrokenDto.class);
    }

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

    public MaterialBroken fromDto(MaterialBrokenDto dto) {
        return modelMapper.map(dto, MaterialBroken.class);
    }
}
