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

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.enums.EnumValues;
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.utils.StringUtils;
import com.sw.mes.yb.pc.dto.FbjoinDto;
import com.sw.mes.yb.pc.dto.StickTogetherParam;
import com.sw.mes.yb.pc.dto.TrayBindingRecordDto;
import com.sw.mes.yb.pc.entity.Fbjoin;
import com.sw.mes.yb.pc.entity.TrayBindingRecord;
import com.sw.mes.yb.pc.service.FbjoinService;
import com.sw.mes.yb.pc.service.SectionService;
import com.sw.mes.yb.pc.service.TrayBindingRecordService;
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.List;
import java.util.stream.Collectors;


/**
 * 废除此接口移到方棒程序中去
 *
 * @Author 李儒
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/join")
@Slf4j
@Api(description = "粘圆棒、方棒接口")
@Deprecated
public class FbjoinController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FbjoinService fbjoinService;

    @Autowired
    private SectionService sectionService;

    @Autowired
    private TrayBindingRecordService trayBindingRecordService;

    @ApiOperation(value = "分页查询fbjoin列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/fbJoin/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> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有fbjoin")
    @GetMapping("/fbJoin/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> fbjoinDtos = fbjoins.stream()
                .map(fbjoin -> toLazyDto(fbjoin))
                .collect(Collectors.toList());
        return ResultGenerator.success(fbjoinDtos);
    }

    @ApiOperation(value = "fbjoin详细信息")
    @GetMapping("/fbJoin/{id}")
    public Result<FbjoinDto> get(@PathVariable @ApiParam(value = "fbjoinid") Integer id) {
        Fbjoin fbjoin = fbjoinService.get(id);
        if (null == fbjoin) {
            return ResultGenerator.fail("该fbjoin不存在");
        }
        return ResultGenerator.success(toEagerDto(fbjoin));
    }

    @ApiOperation(value = "创建fbjoin")
    @PostMapping("/fbJoin/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "fbjoin对象") List<String> sectionNoFbList) {
        fbjoinService.createBySectionNoFbList(sectionNoFbList);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "fbjoin解除绑定")
    @GetMapping("/fbJoin/unbind/{id}")
    public Result unbind(@PathVariable @ApiParam(value = "fbjoinid") Integer id) {
        fbjoinService.unbind(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新fbjoin")
    @PostMapping("/fbJoin/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 entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            fbjoinService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除fbjoin")
    @PostMapping("/fbJoin/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (Integer id : ids) {
            fbjoinService.deleteByMainId(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation("拼接圆棒")
    @PostMapping("/ybJoin/create")
    public Result stickTogether(@RequestBody StickTogetherParam stickTogetherParam) {
        try {
            return sectionService.stickTogetherBySectionNos(stickTogetherParam.getSectionNos(), stickTogetherParam.getCreateUser());
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    //region 废弃代码
//    @ApiOperation(value = "拼圆棒解除绑定")
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "id", value = "id", dataType = "integer", paramType = "query"),
//			@ApiImplicitParam(name = "userName", value = "解绑人", dataType = "string", paramType = "query"),
//	})
//	@GetMapping("/ybJoin/unbind")
//	public Result ybJoinUnbind(Integer id, String userName) {
//		sectionService.ybJoinUnbind(id,userName);
//		return ResultGenerator.success();
//	}
//
//	@ApiOperation(value = "拼圆棒Pda根据托盘解除绑定")
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "code", value = "托盘编号", dataType = "string", paramType = "query"),
//			@ApiImplicitParam(name = "userName", value = "解绑人", dataType = "string", paramType = "query"),
//			@ApiImplicitParam(name = "relieveReason", value = "解绑原因", dataType = "string", paramType = "query"),
//	})
//	@PostMapping("/ybJoinPda/unbind")
//	public Result ybJoinPdaUnbind(@RequestBody JSONObject params) {
//		if (null == params){
//			return ResultGenerator.fail("传入参数为空！");
//		}
//		String code = params.getString("code");
//		String userName = params.getString("userName");
//		String relieveReason = params.getString("relieveReason");
//		if (StringUtils.isBlank(code)){
//			ResultGenerator.fail("托盘编号为空！");
//		}
//		try {
//			sectionService.ybJoinPdaUnbind(code,userName,relieveReason);
//			return ResultGenerator.success();
//		}catch (Exception e){
//			return ResultGenerator.fail(e.getMessage());
//		}
//	}
    //endregion

    @ApiOperation(value = "分页查询托盘绑定操作记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/ybJoin/listByPage")
    public Result<ResponsePage<TrayBindingRecordDto>> yblistByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<TrayBindingRecord> specification = DynamicSpecifications.bySearchFilter(request, TrayBindingRecord.class);
        Page<TrayBindingRecord> page = trayBindingRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<TrayBindingRecordDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto1(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    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);
    }

    public TrayBindingRecordDto toLazyDto1(TrayBindingRecord entity) {
        TrayBindingRecordDto dto = modelMapper.map(entity, TrayBindingRecordDto.class);
        if (dto.getStatus() != null) {
            dto.setStatusName(EnumValues.trayBindingRecordStatus.getText(dto.getStatus()));
        }
        return dto;
    }


}
