package com.sw.mes.fb.checkout.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.sw.mes.base.workinprocess.dto.PlanProcessingOrderWipStorageDto;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.context.BaseContextHandler;
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.ResultCode;
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.fb.checkout.dto.PickUpCheckDto;
import com.sw.mes.fb.checkout.entity.PickUpCheck;
import com.sw.mes.fb.checkout.service.PickUpCheckService;
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.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.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/pickUpCheck")
@Slf4j
@Api(description = "方棒抽检接口")
public class PickUpCheckController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private PickUpCheckService pickUpCheckService;

	@Autowired
    private WipStorageService wipStorageService;

	@Autowired
    private PlanProcessingOrderService planProcessingOrderService;

	@ApiOperation(value = "分页查询方棒抽检列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<PickUpCheckDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<PickUpCheck> specification = DynamicSpecifications.bySearchFilter(request, PickUpCheck.class);
    	Page<PickUpCheck> page = pickUpCheckService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<PickUpCheckDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有方棒抽检")
	@GetMapping("/listAll")
	public Result<List<PickUpCheckDto>> listAll(ServletRequest request) {
		Specification<PickUpCheck> specification = DynamicSpecifications.bySearchFilter(request, PickUpCheck.class);
		List<PickUpCheck> pickUpChecks = pickUpCheckService.findByExampleSort(specification, null);
		List<PickUpCheckDto> pickUpCheckDtos = pickUpChecks.stream()
					.map(pickUpCheck -> toLazyDto(pickUpCheck))
					.collect(Collectors.toList());
		return ResultGenerator.success(pickUpCheckDtos);
	}

	@ApiOperation(value = "方棒抽检详细信息")
	@GetMapping("/{id}")
	public Result<PickUpCheckDto> get(@PathVariable @ApiParam(value="方棒抽检id") Integer id) {
		PickUpCheck pickUpCheck = pickUpCheckService.get(id);
		if (null == pickUpCheck)
			return ResultGenerator.fail("该方棒抽检不存在");
		return ResultGenerator.success(toEagerDto(pickUpCheck));
	}

	@ApiOperation(value = "方棒抽检扫码")
    @GetMapping("/pickUpCheckScan")
    public Result pickUpCheckScan(@RequestParam String code){
        // 检验数据提交判断是否在方棒检验状态
//        PlanProcessingOrderWipStorageDto planProcessingOrderWipStorageDto = wipStorageService.selectWipStorage(code, EnumValuesFactory.WipStorageCode.方棒检验.getKey(), null);
        WipStorage wipStorage = wipStorageService.findByProcessingOrderCode(code, Arrays.asList(EnumValuesFactory.WipStorageStatus.待进站.getKey()
                                                                                                , EnumValuesFactory.WipStorageStatus.已进站.getKey()
                                                                                                , EnumValuesFactory.WipStorageStatus.已出站.getKey()));
        if (wipStorage == null) {
            return ResultGenerator.fail("晶段" + code + "不在加工站点中");
        }
        if (!EnumValuesFactory.WipStorageCode.方棒检验.getValue().equals(wipStorage.getProcessName())
                || (EnumValuesFactory.WipStorageCode.方棒检验.getValue().equals(wipStorage.getProcessName()) && wipStorage.getStatus() == EnumValuesFactory.WipStorageStatus.已出站.getKey()))
        {
            return ResultGenerator.fail("晶棒" + code + "不在方棒检验站点，当前站点为" + wipStorage.getProcessName() + EnumValuesFactory.WipStorageStatus.getText(wipStorage.getStatus()));
        }

        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(code);
        if (planProcessingOrder != null) {
            if (EnumValuesFactory.PlanProcessingOrderStatus.已作废.getKey() == planProcessingOrder.getStatus()){
                return ResultGenerator.fail("晶棒"+code+"已组托退料");
            }
            if (EnumValuesFactory.PlanProcessingOrderStatus.组托.getKey() == planProcessingOrder.getStatus()){
                return ResultGenerator.fail("晶棒"+code+"已组托");
            }
        }
        return ResultGenerator.success(code);
    }

	@ApiOperation(value = "创建方棒抽检")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "方棒抽检对象") PickUpCheckDto pickUpCheckDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
        Result result = pickUpCheckScan(pickUpCheckDto.getSectionNo());
		if (ResultCode.SUCCESS.getCode() != result.getCode()){
		    return result;
        }
        PickUpCheck pickUpCheck = fromDto(pickUpCheckDto);
		pickUpCheckService.createPickUpCheck(pickUpCheck);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新方棒抽检")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "方棒抽检") PickUpCheckDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            PickUpCheck entity = pickUpCheckService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            PickUpCheck entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			pickUpCheckService.updatePickUpCheck(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(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) {
				pickUpCheckService.delete(id);
		}
		return ResultGenerator.success();
	}

	public PickUpCheckDto toLazyDto(PickUpCheck entity) {
		return modelMapper.map(entity, PickUpCheckDto.class);
	}

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

	public PickUpCheck fromDto(PickUpCheckDto dto) {
		return modelMapper.map(dto, PickUpCheck.class);
	}


}
