package com.sw.common.accessory.server.controller;

import com.sw.common.accessory.server.dto.PartDto;
import com.sw.common.accessory.server.entity.Part;
import com.sw.common.accessory.server.service.PartService;
import com.sw.common.core.context.BaseContextHandler;
import com.sw.common.core.request.RequestPage;
import com.sw.common.core.response.ResponsePage;
import com.sw.common.core.response.Result;
import com.sw.common.core.response.ResultGenerator;
import com.sw.common.mybatisplus.entity.Page;
import com.sw.common.mybatisplus.utils.DynamicSpecifications;
import com.sw.common.mybatisplus.utils.PageUtil;
import com.sw.common.mybatisplus.utils.Specification;
import io.reactivex.rxjava3.internal.util.BackpressureHelper;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/part")
@Slf4j
@Api(tags = "热场部位维护接口")
public class PartController {
    @Autowired
    private PartService partService;
    @ApiOperation(value = "分页查热场部位维护列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<PartDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<Part> specification = DynamicSpecifications.bySearchFilter(request, Part.class);
        Page<Part> page = partService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<PartDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage<PartDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有部位维护记录")
    @GetMapping("/listAll")
    public Result<List<PartDto>> listAll(ServletRequest request) {
        Specification<Part> specification = DynamicSpecifications.bySearchFilter(request, Part.class);
        List<Part> parts = partService.findByExampleSort(specification, null);
        List<PartDto> partDtos = parts.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(partDtos);
    }


    @ApiOperation(value = "通过id获取部位维护信息")
    @GetMapping("/{id}")
    public Result<PartDto> get(@PathVariable @ApiParam(value = "所有部位维护id") Long id) {
        Part part = partService.get(id);
        if (null == part) {
            return ResultGenerator.fail("该辅料申请记录不存在");
        }
        return ResultGenerator.success(toEagerDto(part));
    }
    @ApiOperation(value = "通过编码获取部位维护信息")
    @GetMapping("/partCode")
    public Result<PartDto> getPartCode(@RequestParam @ApiParam(value = "部位编码") String partCode) {
        Part part = partService.getByPartCode(partCode);
        if (null == part) {
            return ResultGenerator.fail("该辅料申请记录不存在");
        }
        return ResultGenerator.success(toEagerDto(part));
    }
    @ApiOperation(value = "创建部位")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "所有部位维护对象") PartDto partDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        Part partCode = partService.getByPartCode(partDto.getPartCode());
        if(!ObjectUtils.isEmpty(partCode)){
            return ResultGenerator.fail("该数据已存在!");
        }
        Part part = fromDto(partDto);
        part.setCreateBy(BaseContextHandler.getUsername());
        part.setCreateTime(new Date());
        partService.saveOrUpdate(part);
        return ResultGenerator.success();
    }


    @ApiOperation(value = "更新部位记录")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "所有部位维护记录") PartDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            Part partCode = partService.getByPartCode(dto.getPartCode());
            if(ObjectUtils.isEmpty(partCode)){
                return ResultGenerator.fail("该数据不存在!");
            }
            Part part = fromDto(dto);
            part.setId(dto.getId());
            part.setUpdateBy(BaseContextHandler.getUsername());
            part.setUpdateTime(new Date());
            partService.saveOrUpdate(part);
        }catch (Exception ex){
            return ResultGenerator.fail(ex.getMessage());
        }
        return ResultGenerator.success();
    }


    public PartDto toLazyDto(Part entity) {
        PartDto partDto = new PartDto();
        BeanUtils.copyProperties(entity,partDto);
        return partDto;
    }

    public PartDto toEagerDto(Part entity) {
        PartDto partDto = new PartDto();
        BeanUtils.copyProperties(entity, partDto);
        return partDto;
    }

    public Part fromDto(PartDto dto) {
        Part part = new Part();
        BeanUtils.copyProperties(dto, part);
        return part;
    }
}
