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.annotation.Jinko;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.enums.ItemCleanEnums;
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.ExcelUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.itemclean.clean.domain.MaterialGroupDetail;
import com.sw.mes.itemclean.clean.dto.*;
import com.sw.mes.itemclean.clean.domain.MaterialGroup;
import com.sw.mes.itemclean.clean.mapper.MaterialGroupMapper;
import com.sw.mes.itemclean.clean.service.MaterialGroupDetailService;
import com.sw.mes.itemclean.clean.service.MaterialGroupService;
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.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/clean/materialGroup")
@Slf4j
@Api(tags = "组托入库")
public class MaterialGroupController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialGroupService materialGroupService;

    @Autowired
    private MaterialGroupMapper materialGroupMapper;


    @Autowired
    private MaterialGroupDetailService materialGroupDetailService;


    @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_LIKE_groupNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_dateProduceBatchNo", value = "日批次号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialCode", 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"),
            @ApiImplicitParam(name = "search_EQ_status", value = "状态:0 未入库,1 已入库,2 调拨成功", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<MaterialGroupDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialGroup> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialGroup.class);
        queryWrapper.orderByDesc("create_time");
        Page<MaterialGroup> listPage = materialGroupService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialGroupDto> 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<MaterialGroupDto>> listAll(ServletRequest request) {
        QueryWrapper<MaterialGroup> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialGroup.class);
        List<MaterialGroup> materialGroups = materialGroupService.list(queryWrapper);
        List<MaterialGroupDto> materialGroupDtos = materialGroups.stream()
                .map(materialGroup -> toLazyDto(materialGroup))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialGroupDtos);
    }

    @ApiOperation(value = "导出硅料组托入库接口")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, HttpServletResponse response) {
        QueryWrapper<MaterialGroup> queryWrapper =  DynmaicQueryWrapper.searchFilter(request, MaterialGroup.class);
        List<MaterialGroup> materialGroups = materialGroupService.list(queryWrapper);
        List<MaterialGroupVo> materialGroupVos = new ArrayList<>();
        List<MaterialGroupDto> materialGroupDtos = materialGroups.stream()
                .map(materialGroup -> toEagerDto(materialGroup))
                .collect(Collectors.toList());
        materialGroupDtos.forEach(entity->{
            MaterialGroupVo materialGroupVo = new MaterialGroupVo();
            BeanUtils.copyProperties(entity,materialGroupVo);
            if(null != entity.getWarehousingTime()){
                java.util.Date date = Date.from(entity.getWarehousingTime().atZone(ZoneId.systemDefault()).toInstant());
                materialGroupVo.setWarehousingTime(date);
            }
            materialGroupVos.add(materialGroupVo);
        });

        ExcelUtil.exportExcel(materialGroupVos, "硅料组托入库记录", MaterialGroupVo.class, response);
    }

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

    @ApiOperation(value = "创建")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialGroupDto materialGroupDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialGroup materialGroup = fromDto(materialGroupDto);
        materialGroupService.saveOrUpdate(materialGroup);
        return ResultGenerator.success();
    }

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

    @Jinko(author = "yyl", value = "硅料组托入库-确定组托")
    @ApiOperation(value = "硅料组托入库-确定组托")
    @PostMapping("/confirmGroup")
    public Result confirmGroup(@RequestBody @Valid GroupStoreDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialGroup materialGroup = materialGroupService.confirmGroup(dto);
        return ResultGenerator.success(materialGroup);
    }

    @Jinko(author = "yyl", value = "硅料组托入库-新版破碎下料-组托入库")
    @ApiOperation(value = "硅料组托入库-新版破碎下料-组托入库(暂时不用)")
    @PostMapping("/groupStore")
    public Result groupStore(@RequestBody @Valid GroupStoreDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        MaterialGroup materialGroup = materialGroupService.groupStore(dto);
        return ResultGenerator.success(materialGroup);
    }

    @Jinko(author = "yyl", value = "硅料组托入库-编辑")
    @ApiOperation(value = "硅料组托入库-编辑")
    @PostMapping("/editGroup")
    public Result editGroup(@RequestBody @Valid MaterialGroupEditDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return materialGroupService.editGroup(dto);
    }

    @Jinko(author = "yyl", value = "硅料组托入库-新版破碎下料-通过id,组托入库")
    @ApiOperation(value = "硅料组托入库-新版破碎下料-通过id,组托入库")
    @GetMapping("/groupStoreById/{id}")
    public Result groupStoreById(@PathVariable @ApiParam(value="组托id") Integer id) {
        MaterialGroup materialGroup = materialGroupService.groupStoreById(id);
        return ResultGenerator.success(materialGroup);
    }

    @Jinko(author = "yyl", value = "硅料组托入库-通过id,手动补偿入库工时")
    @ApiOperation(value = "硅料组托入库-通过id,手动补偿入库工时")
    @GetMapping("/groupStoreWorkHourById/{id}")
    public Result groupStoreWorkHourById(@PathVariable @ApiParam(value = "组托id") Integer id) {
        MaterialGroup materialGroup = materialGroupService.groupStoreWorkHourById(id);
        return ResultGenerator.success(materialGroup);
    }

    @ApiOperation(value = "入库WMS")
    @PostMapping("/groupStorePc")
    public Result groupStorePc(@RequestBody @Valid MaterialGroupDto materialGroupDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        MaterialGroup materialGroup = fromDto(materialGroupDto);
        //组托到wms
        materialGroupService.groupStorePc(materialGroup);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "手动触发清洗成品组托到wms")
    @PostMapping("/fbGroupToWms")
    public Result groupStore(String groupNo) {
        return ResultGenerator.success(materialGroupService.fbGroupToWms(groupNo));
    }

    @ApiOperation(value = "清洗成品解托")
    @PostMapping("/openGroupToWms")
    public Result openGroupToWms(String groupNo) {
        return ResultGenerator.success(materialGroupService.openGroupToWms(groupNo));
    }


    @Jinko(author = "yyl", value = "通过托号获取信息")
    @ApiOperation(value = "通过托号获取信息")
    @GetMapping("/findDataByCleanGroupNo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupNo", value = "托号", dataType = "String", paramType = "query")
    })
    public Result get(String groupNo) {
        MaterialGroup materialGroup = materialGroupService.getByGroupNo(groupNo);
        if (null == materialGroup)
            return ResultGenerator.fail("该对象不存在");
        return ResultGenerator.success(materialGroup);
    }

    @Jinko(author = "yyl", value = "硅料成品调拨回调接口")
    @ApiOperation(value = "硅料成品调拨回调接口")
    @GetMapping("/updateStates")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupNo", value = "托号", dataType = "String", paramType = "query")
    })
    public Result updateStates(String groupNo) {
        MaterialGroup materialGroup = materialGroupService.getByGroupNo(groupNo);
        if (null == materialGroup){
            return ResultGenerator.fail("该对象不存在");
        }else {
            materialGroup.setStatus(ItemCleanEnums.MaterialGroupStatus.调拨成功.getKey());
            materialGroup.setUpdateTime(LocalDateTime.now());
            materialGroupService.updateById(materialGroup);
        }
        return ResultGenerator.success(materialGroup);
    }


    public MaterialGroupDto toLazyDto(MaterialGroup entity) {
        return modelMapper.map(entity, MaterialGroupDto.class);
    }

    public MaterialGroupVo toLazyVo(MaterialGroup entity) {
        return modelMapper.map(entity, MaterialGroupVo.class);
    }

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

    public MaterialGroup fromDto(MaterialGroupDto dto) {
        return modelMapper.map(dto, MaterialGroup.class);
    }
}
