package com.sw.mes.yb.turnstore.controller;

import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.core.dto.TurnstoreTrayDto;
import com.sw.mes.core.entity.TurnstoreTrayItem;
import com.sw.mes.core.enums.EnumValuesFactory;
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.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.turnstore.dto.TurnstoreTrayItemDto;
import com.sw.mes.yb.turnstore.entity.TurnstoreTray;
import com.sw.mes.yb.turnstore.service.TurnstoreTrayItemService;
import com.sw.mes.yb.turnstore.service.TurnstoreTrayService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/turnstoreTrayItem")
@Slf4j
@Api(description = "组拖明细接口")
public class TurnstoreTrayItemController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private TurnstoreTrayItemService turnstoreTrayItemService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private TurnstoreTrayService turnstoreTrayService;

    @ApiOperation(value = "分页查询组拖明细列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_trayId", value = "主表id", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_IN_sectionNo", value = "晶段编号", dataType = "array", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_trayNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_time", value = "组托时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_time", value = "组托时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<TurnstoreTrayItemDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<TurnstoreTrayItem> specification = DynamicSpecifications.bySearchFilter(request, TurnstoreTrayItem.class);
        Page<TurnstoreTrayItem> page = turnstoreTrayItemService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<TurnstoreTrayItemDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有组拖明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_EQ_trayId", value = "主表id", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listAll")
    public Result<List<TurnstoreTrayItemDto>> listAll(ServletRequest request) {
        Specification<TurnstoreTrayItem> specification = DynamicSpecifications.bySearchFilter(request, TurnstoreTrayItem.class);
        List<TurnstoreTrayItem> turnstoreTrayItems = turnstoreTrayItemService.findByExampleSort(specification, null);
        List<TurnstoreTrayItemDto> turnstoreTrayItemDtos = turnstoreTrayItems.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(turnstoreTrayItemDtos);
    }

    @ApiOperation(value = "组拖明细详细信息")
    @GetMapping("/{id}")
    public Result<TurnstoreTrayItemDto> get(@PathVariable @ApiParam(value = "组拖明细id") Integer id) {
        TurnstoreTrayItem turnstoreTrayItem = turnstoreTrayItemService.get(id);
        if (null == turnstoreTrayItem) {
            return ResultGenerator.fail("该组拖明细不存在");
        }
        return ResultGenerator.success(toEagerDto(turnstoreTrayItem));
    }

    @ApiOperation(value = "创建组拖明细")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "组拖明细对象") TurnstoreTrayItemDto turnstoreTrayItemDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        TurnstoreTrayItem turnstoreTrayItem = fromDto(turnstoreTrayItemDto);
        turnstoreTrayItemService.saveOrUpdate(turnstoreTrayItem);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建组拖明细列表")
    @PostMapping("/createList")
    public Result createList(@RequestBody @Valid @ApiParam(value = "组拖明细对象列表") List<TurnstoreTrayItemDto> turnstoreTrayItemDtos, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        for (TurnstoreTrayItemDto trayItemDto : turnstoreTrayItemDtos) {
            TurnstoreTrayItem turnstoreTrayItem = fromDto(trayItemDto);
            turnstoreTrayItemService.saveOrUpdate(turnstoreTrayItem);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新组拖明细")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "组拖明细") TurnstoreTrayItemDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        TurnstoreTrayItem entity = turnstoreTrayItemService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            TurnstoreTrayItem entityFromFto = fromDto(dto);
            BeanUtils.copyProperties(entityFromFto, entity, BeanUtil.getIgnoreProperties(entityFromFto, null, null));
            turnstoreTrayItemService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "导出Excel")
    @GetMapping("/exportExcel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_EQ_sectionNo", value = "晶段编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_trayNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_time", value = "组托时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_time", value = "组托时间", dataType = "string", paramType = "query"),
    })
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        turnstoreTrayItemService.exportExcel(request, resp);
    }


    @ApiOperation(value = "删除组拖明细")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (Integer id : ids) {
            TurnstoreTrayItem trayItem = turnstoreTrayItemService.get(id);
            if (null == trayItem) {
                return ResultGenerator.fail("原信息不存在");
            }
            if (9 != trayItem.getState()) {
                return ResultGenerator.fail("当前不处于待出库状态,不能进行删除,请刷新后再试");
            }
            //解锁组托状态
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(trayItem.getSectionNo());
            planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
            planProcessingOrderService.saveOrUpdate(planProcessingOrder);
            turnstoreTrayItemService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据拖号获取明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "trayNo", value = "拖号", dataType = "string", paramType = "query"),
    })
    @GetMapping("/getItemsByTrayNo")
    public Result getItemsByTrayNo(@RequestParam String trayNo, @RequestParam String hasGone, @RequestParam String ruleName) {
        if (StringUtils.isBlank(trayNo)) {
            return ResultGenerator.fail("托号不能为空");
        }
        if (StringUtils.isBlank(hasGone)) {
            return ResultGenerator.fail("去向不能为空");
        }
        //查询组托主表状态
        TurnstoreTray turnstoreTray = turnstoreTrayService.findByTrayNo(trayNo);
        if (null == turnstoreTray) {
            return ResultGenerator.fail("组托主表信息不存在");
        }
        if (null != turnstoreTray.getState() && (turnstoreTray.getState() != 4)) {
            return ResultGenerator.fail("该拖晶段不是取消状态,无法合托");
        }
        //判断是否可以进行合拖
        //去向
        if (!hasGone.equals(turnstoreTray.getHasGone())) {
            return ResultGenerator.fail("去向不一致,无法合托");
        }
        //规则判断
        if ("综计WMS".equals(turnstoreTray.getHasGone()) && !ruleName.equals(turnstoreTray.getRuleName())) {
            return ResultGenerator.fail("组托规则不一致,无法合托");
        }
        //查询目标列表进行返回
        List<TurnstoreTrayItem> itemsByTrayNo = turnstoreTrayItemService.getItemsByTrayNo(trayNo);

        return ResultGenerator.success(itemsByTrayNo);
    }

    public TurnstoreTrayItemDto toLazyDto(TurnstoreTrayItem entity) {
        //ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper.map(entity, TurnstoreTrayItemDto.class);
    }

    public TurnstoreTrayItemDto toEagerDto(TurnstoreTrayItem entity) {
        //ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper.map(entity, TurnstoreTrayItemDto.class);
    }

    public TurnstoreTrayItem fromDto(TurnstoreTrayItemDto dto) {
        //ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper.map(dto, TurnstoreTrayItem.class);
    }

    public TurnstoreTrayDto fromDto(TurnstoreTray dto) {
        //ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper.map(dto, TurnstoreTrayDto.class);
    }
}
