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.*;
import com.sw.mes.itemclean.clean.domain.MaterialApplyOrder;
import com.sw.mes.itemclean.clean.domain.MaterialApplyOrderRelation;
import com.sw.mes.itemclean.clean.dto.*;
import com.sw.mes.itemclean.clean.domain.MaterialGroupDetail;
import com.sw.mes.itemclean.clean.mapper.MaterialGroupDetailMapper;
import com.sw.mes.itemclean.clean.service.MaterialGroupDetailService;
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.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/clean/materialGroupDetail")
@Slf4j
@Api(tags = "组托/破碎下料小箱明细")
public class MaterialGroupDetailController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialGroupDetailService materialGroupDetailService;

    @Autowired
    private MaterialGroupDetailMapper materialGroupDetailMapper;

    @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<MaterialGroupDetailDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialGroupDetail> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialGroupDetail.class);
        Page<MaterialGroupDetail> listPage = materialGroupDetailService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialGroupDetailDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有列表")
    @GetMapping("/listAll")
    public Result<List<MaterialGroupDetailDto>> listAll(ServletRequest request) {
        QueryWrapper<MaterialGroupDetail> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialGroupDetail.class);
        List<MaterialGroupDetail> materialGroupDetails = materialGroupDetailService.list(queryWrapper);
        List<MaterialGroupDetailDto> materialGroupDetailDtos = materialGroupDetails.stream()
                .map(materialGroupDetail -> toLazyDto(materialGroupDetail))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialGroupDetailDtos);
    }

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

    @ApiOperation(value = "创建")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialGroupDetailDto materialGroupDetailDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialGroupDetail materialGroupDetail = fromDto(materialGroupDetailDto);
        materialGroupDetailService.saveOrUpdate(materialGroupDetail);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "循环料上报ERP")
    @PostMapping("/reportedErp")
    public Result reportedErp(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialGroupDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }

        return materialGroupDetailService.reportedErp(dto);
    }

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


    @Jinko(author = "yyl", value = "硅料组托入库-成品组托记录分页查询列表")
    @ApiOperation(value = "硅料组托入库-成品组托记录分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_materialName", value = "物料名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialCode", value = "物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_groupNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_productBatchNo", value = "生产批次", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "组托开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "组托结束时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listPageByQuery")
    public Result<ResponsePage<MaterialGroupToDetailDto>> listPageByQuery(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        ResponsePage<MaterialGroupToDetailDto> responsePage = new ResponsePage<>();
        GroupDetailParamQuery groupDetailParamQuery = new GroupDetailParamQuery();
        groupDetailParamQuery.setMaterialName(request.getParameter("search_LIKE_materialName"))
                .setMaterialCode(request.getParameter("search_EQ_materialCode"))
                .setGroupNo(request.getParameter("search_EQ_groupNo"))
                .setProductBatchNo(request.getParameter("search_EQ_productBatchNo"))
                .setCreateStartTime(request.getParameter("search_GTE_createTime"))
                .setCreateEndTime(request.getParameter("search_LTE_createTime"));
        IPage<MaterialGroupToDetailDto> iPage = new Page<>(requestPage.getPage(), requestPage.getRows());
        IPage<MaterialGroupToDetailDto> materialGroupDetailDtoIPage = materialGroupDetailService.queryList(iPage, groupDetailParamQuery);
        responsePage.setRows(materialGroupDetailDtoIPage.getRecords());
        responsePage.setTotal(materialGroupDetailDtoIPage.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"),
            @ApiImplicitParam(name = "search_LIKE_materialName", value = "物料名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialCode", value = "物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_groupNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_productBatchNo", value = "生产批次", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_aufnr", value = "工单号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_materialBoxNo", value = "成箱号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "成箱开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "成箱结束时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/queryBoxList")
    public Result<ResponsePage<MaterialGroupToBoxDetailDto>> queryBoxList(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        ResponsePage<MaterialGroupToBoxDetailDto> responsePage = new ResponsePage<>();
        GroupDetailParamQuery groupDetailParamQuery = new GroupDetailParamQuery();
        groupDetailParamQuery.setMaterialName(request.getParameter("search_LIKE_materialName"))
                .setMaterialCode(request.getParameter("search_EQ_materialCode"))
                .setGroupNo(request.getParameter("search_EQ_groupNo"))
                .setAufnr(request.getParameter("search_EQ_aufnr"))
                .setProductBatchNo(request.getParameter("search_EQ_productBatchNo"))
                .setMaterialBoxNo(request.getParameter("search_LIKE_materialBoxNo"))
                .setCreateStartTime(request.getParameter("search_GTE_createTime"))
                .setCreateEndTime(request.getParameter("search_LTE_createTime"));
        IPage<MaterialGroupToBoxDetailDto> iPage = new Page<>(requestPage.getPage(), requestPage.getRows());
        IPage<MaterialGroupToBoxDetailDto> materialGroupDetailDtoIPage = materialGroupDetailService.queryBoxPage(iPage, groupDetailParamQuery);
        responsePage.setRows(materialGroupDetailDtoIPage.getRecords());
        responsePage.setTotal(materialGroupDetailDtoIPage.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"),
            @ApiImplicitParam(name = "search_LIKE_materialName", value = "物料名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialCode", value = "物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_groupNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_productBatchNo", value = "生产批次", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_aufnr", value = "工单号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "成箱开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "成箱结束时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/exportBoxList")
    public void exportBoxList(ServletRequest request, HttpServletResponse response) {
        try {
            ResponsePage<MaterialGroupToBoxDetailDto> responsePage = new ResponsePage<>();
            GroupDetailParamQuery groupDetailParamQuery = new GroupDetailParamQuery();
            groupDetailParamQuery.setMaterialName(request.getParameter("search_LIKE_materialName"))
                    .setMaterialCode(request.getParameter("search_EQ_materialCode"))
                    .setGroupNo(request.getParameter("search_EQ_groupNo"))
                    .setAufnr(request.getParameter("search_EQ_aufnr"))
                    .setProductBatchNo(request.getParameter("search_EQ_productBatchNo"))
                    .setCreateStartTime(request.getParameter("search_GTE_createTime"))
                    .setCreateEndTime(request.getParameter("search_LTE_createTime"));
            List<MaterialGroupToBoxDetailDto> list = materialGroupDetailService.queryBoxList(groupDetailParamQuery);

            EasyExcelUtils.write(response, MaterialGroupToBoxDetailDto.class, "导出小箱记录", "导出小箱记录", list);
        } catch (Exception e) {
            throw new RuntimeException("导出成品组托记录失败，错误信息：" + e.getMessage());
        }
    }
    /**
     * 导出成品组托记录
     *
     * @param request
     * @param response
     */
    @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 = "生产批次", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_groupNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "组托开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "组托结束时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/export")
    @TokenNotValidation
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
            GroupDetailParamQuery groupDetailParamQuery = new GroupDetailParamQuery();
            groupDetailParamQuery.setMaterialName(request.getParameter("search_LIKE_materialName"))
                    .setMaterialCode(request.getParameter("search_EQ_materialCode"))
                    .setGroupNo(request.getParameter("search_EQ_groupNo"))
                    .setProductBatchNo(request.getParameter("search_EQ_productBatchNo"))
                    .setCreateStartTime(request.getParameter("search_GTE_createTime"))
                    .setCreateEndTime(request.getParameter("search_LTE_createTime"));
            List<MaterialGroupToDetailDto> list = materialGroupDetailService.queryListByParam(groupDetailParamQuery);

            EasyExcelUtils.write(response, MaterialGroupToDetailDto.class, "导出成品组托记录", "导出成品组托记录", list);
        } catch (Exception e) {
            throw new RuntimeException("导出成品组托记录失败，错误信息：" + e.getMessage());
        }
    }

    @Jinko(author = "yyl", value = "破碎下料和组托入库-通过料盒号校验组托明细中是否存在未组托数据")
    @ApiOperation(value = "破碎下料和组托入库-通过箱号/通过料盒号校验组托明细中是否存在未组托数据")
    @GetMapping("/getGroupDetailInfoByMaterialBoxNo")
    public Result<MaterialGroupDetail> getGroupDetailInfoByMaterialBoxNo(String materialBoxNo) {
        MaterialGroupDetail detail = materialGroupDetailService.getGroupDetailInfoByMaterialBoxNo(materialBoxNo);
        return ResultGenerator.success(detail);
    }

    public MaterialGroupDetailDto toLazyDto(MaterialGroupDetail entity) {
        return modelMapper.map(entity, MaterialGroupDetailDto.class);
    }

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

    public MaterialGroupDetail fromDto(MaterialGroupDetailDto dto) {
        return modelMapper.map(dto, MaterialGroupDetail.class);
    }
}
