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

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.*;
import com.sw.mes.fb.checkout.dto.FbJoinDto;
import com.sw.mes.fb.checkout.entity.FbJoin;
import com.sw.mes.fb.checkout.service.FbJoinService;
import com.sw.mes.fb.turnstore.entity.RawMaterialReceivingDetail;
import com.sw.mes.fb.turnstore.service.RawMaterialReceivingDetailService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
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.domain.Sort;
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.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


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

	@Autowired
	private FbJoinService fbJoinService;

	@Autowired
	private WipStorageService wipStorageService;

	@Autowired
	private RawMaterialReceivingDetailService receivingDetailService;

	@ApiOperation(value = "分页查询拼方棒列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_EQ_state", value = "状态(1：绑定，0：未绑定)", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_sectionNoFb", value = "方棒编号", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_GTE_bindTime", value = "绑定时间(开始时间)", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LT_bindTime", value = "绑定时间(结束时间)", dataType = "string", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<FbJoinDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<FbJoin> specification = DynamicSpecifications.bySearchFilter(request, FbJoin.class);
    	Page<FbJoin> page = fbJoinService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<FbJoinDto> obj = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(obj, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有拼方棒")
	@GetMapping("/listAll")
	public Result<List<FbJoinDto>> listAll(ServletRequest request) {
		Specification<FbJoin> specification = DynamicSpecifications.bySearchFilter(request, FbJoin.class);
		List<FbJoin> fbJoins = fbJoinService.findByExampleSort(specification, null);
		List<FbJoinDto> fbJoinList = fbJoins.stream()
					.map(fbJoin -> toLazyDto(fbJoin))
					.collect(Collectors.toList());
		return ResultGenerator.success(fbJoinList);
	}

	@ApiOperation(value = "拼方棒详细信息")
	@GetMapping("/{id}")
	public Result<FbJoinDto> get(@PathVariable @ApiParam(value="id") Integer id) {
		FbJoin fbJoin = fbJoinService.get(id);
		if (null == fbJoin)
			return ResultGenerator.fail("该FbJoin不存在");
		return ResultGenerator.success(toEagerDto(fbJoin));
	}

	@ApiOperation(value = "创建拼方棒")
	@PostMapping("/pasteStick")
	public Result create(@RequestBody @Valid @ApiParam(value = "fbjoin对象")List<String> sectionNoFbList) {
		if (sectionNoFbList.size() < 2) {
			return ResultGenerator.fail("拼棒的方棒数量应该大于2");
		}
		return fbJoinService.pasteStick(sectionNoFbList);
	}

    @ApiOperation(value = "更新拼方棒")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "FbJoin") FbJoinDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            FbJoin entity = fbJoinService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            FbJoin obj = fromDto(dto);
			BeanUtils.copyProperties(obj, entity, BeanUtil.getIgnoreProperties(obj, null, null));
			fbJoinService.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) {
				fbJoinService.deleteById(id);
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "方棒解除绑定")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "id", dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "relieveReason", value = "解绑原因", dataType = "string", paramType = "query"),
	})
	@PostMapping("/fbRelieve")
	public Result ybJoinUnbind(Long id,String relieveReason) {
		fbJoinService.fbRelieve(id,relieveReason);
		return ResultGenerator.success();
	}

	@PostMapping("/unPasteStick")
	public Result ybJoinUnbind(@RequestBody List<String> sectionNoFbList) {
//		fbJoinService.unPasteStick(sectionNoFbList);
		return ResultGenerator.success();
	}


	@ApiOperation(value = "pda根据晶段编号id解除绑定")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionNo", value = "方棒晶段编号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "relieveReason", value = "解绑原因", dataType = "string", paramType = "query"),
	})
	@PostMapping("/pdaRelieveBySectionNo")
	public Result pdaRelieveBySectionNo(String sectionNo,String relieveReason) {

		if (StringUtils.isBlank(sectionNo)){
			ResultGenerator.fail("晶段编码为空！");
		}
		try {
			fbJoinService.pdaRelieveBySectionNo(sectionNo,relieveReason);
			return ResultGenerator.success();
		}catch (Exception e){
			return ResultGenerator.fail(e.getMessage());
		}
	}

	@ApiOperation(value = "根据晶段编号查询方棒信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionNoFb", value = "方棒晶段编号", dataType = "string", paramType = "query"),
	})
	@GetMapping("/getFbJoinBySectionNoFb")
	public Result getFbJoinBySectionNo(String sectionNoFb) {

		if (StringUtils.isBlank(sectionNoFb)){
			ResultGenerator.fail("晶段编码为空！");
		}
		try {
			FbJoin fbJoin = fbJoinService.getFbJoinBySectionNo(sectionNoFb);
			if (fbJoin != null){
				wipStorageService.selectWipStorage(fbJoin.getSectionNoFb(), EnumValuesFactory.WipStorageCode.粘方棒.getKey(), true);
				return ResultGenerator.success(fbJoin);
			}else {
				return ResultGenerator.fail("该晶段在检验节点");
			}
		}catch (Exception e){
			return ResultGenerator.fail(e.getMessage());
		}
	}

	@ApiOperation(value = "导出方棒记录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "search_EQ_state", value = "状态(1：绑定，0：未绑定)", dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_sectionNoFb", value = "方棒编号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_GTE_bindTime", value = "绑定时间(开始时间)", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LT_bindTime", value = "绑定时间(结束时间)", dataType = "string", paramType = "query"),
	})
	@GetMapping("/export")
	public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
		try {
			Specification<FbJoin> specification = DynamicSpecifications.bySearchFilter(request, FbJoin.class);
			List<FbJoin> list = fbJoinService.findByExampleSort(specification, Sort.by(Sort.Direction.DESC,"id"));
			List<FbJoinDto> obj = list.stream()
					.map(entity -> toLazyDto(entity))
					.collect(Collectors.toList());
			for	(FbJoinDto fbJoinDto : obj){
				List<RawMaterialReceivingDetail> list1 = receivingDetailService.findBySectionNoAndState(fbJoinDto.getSectionNoFb(), 1);
				if (list1 != null && list1.size() > 0) {
					fbJoinDto.setSpecs(list1.get(0).getSpecification());
				}
			}
			EasyExcelUtils.write(response, FbJoinDto.class, "导出方棒记录", "导出方棒记录", obj);
		} catch (Exception e) {
			throw new RuntimeException("方棒拼棒记录导出失败，错误信息：" + e.getMessage());
		}
	}

	public FbJoinDto toLazyDto(FbJoin entity) {
		return modelMapper.map(entity, FbJoinDto.class);
	}

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

	public FbJoin fromDto(FbJoinDto dto) {
		return modelMapper.map(dto, FbJoin.class);
	}


}
