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

import com.sw.common.accessory.api.feignCilent.YbFeignClients;
import com.sw.common.accessory.server.dto.*;
import com.sw.common.accessory.server.entity.AccessoryPart;
import com.sw.common.accessory.server.entity.AccessoryPartDetails;
import com.sw.common.accessory.server.service.AccessoryPartDetailsService;
import com.sw.common.accessory.server.service.AccessoryPartService;
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.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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/accessoryPart")
@Slf4j
@Api(tags = "热场物料部位维护接口")
public class AccessoryPartController {
    @Autowired
    private AccessoryPartService accessoryPartService;
    @Autowired
    private AccessoryPartDetailsService accessoryPartDetailsService;
    @Autowired
    private YbFeignClients ybFeignClients;

    @GetMapping("/listByPage")
    @ApiOperation(value = "分页查询热场物料部位列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    public Result<ResponsePage<AccessoryPartDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<AccessoryPart> specification = DynamicSpecifications.bySearchFilter(request, AccessoryPart.class);
        Page<AccessoryPart> page = accessoryPartService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<AccessoryPartDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage<AccessoryPartDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有热场物料部位")
    @GetMapping("/listAll")
    public Result<List<AccessoryPartDto>> listAll(ServletRequest request) {
        Specification<AccessoryPart> specification = DynamicSpecifications.bySearchFilter(request, AccessoryPart.class);
        List<AccessoryPart> accessoryParts = accessoryPartService.findByExampleSort(specification, null);
        List<AccessoryPartDto> accessoryPartDtos = accessoryParts.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(accessoryPartDtos);
    }

    @ApiOperation(value = "热场物料部位详细信息")
    @GetMapping("/{id}")
    public Result<AccessoryPartDto> get(@PathVariable @ApiParam(value = "热场物料部位id") Long id) {
        AccessoryPart accessoryPart = accessoryPartService.get(id);
        if (null == accessoryPart) {
            return ResultGenerator.fail("该物料部位详细记录不存在");
        }
        return ResultGenerator.success(toEagerDto(accessoryPart));
    }

    @ApiOperation(value = "删除热场物料部位")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            AccessoryPart accessoryPart = accessoryPartService.get(id);
            accessoryPartService.delete(id);
            accessoryPartDetailsService.deleteByCode(accessoryPart.getDeviceTypeCode(),accessoryPart.getMaterialCode(),accessoryPart.getPartCode());
        }
        return ResultGenerator.success();
    }
    @ApiOperation(value = "创建热场物料部位")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "热场物料部位记录对象") AccessoryPartBo bo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        StringBuilder errors = new StringBuilder();
        List<PartDto> partDtos = new ArrayList<>();
        if(bo.getPartDtos() != null){
            bo.getPartDtos().stream().forEach(entity->{
                AccessoryPart byCode = accessoryPartService.getByTypeCode(bo.getDeviceTypeCode(),entity.getMaterialCode(), entity.getPartCode());
                if(ObjectUtils.isEmpty(byCode)){
                    partDtos.add(entity);
                }else {
                    errors.append(entity.getMaterialName()+"--"+entity.getPartName()+"数据已存在\r") ;
                }
            });
        }
        if(ObjectUtils.isEmpty(partDtos)){
            return ResultGenerator.success(errors.toString(),null);
        }
        bo.setPartDtos(partDtos);
        Boolean aBoolean = accessoryPartService.create(bo);
        if(aBoolean==false){
            return ResultGenerator.fail("新增失败",null);
        }
        return ResultGenerator.success(errors.toString(),null);
    }

    @ApiOperation(value = "更新热场物料部位记录")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "热场物料部位记录") AccessoryPartDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        AccessoryPart accessoryPart = accessoryPartService.get(dto.getId());
        if(ObjectUtils.isEmpty(accessoryPart)){
            return ResultGenerator.fail("该数据不存在!");
        }
        Boolean update = accessoryPartService.update(dto);
        List<AccessoryPartDetails> deviceCode = accessoryPartDetailsService.getByNotDeviceCode(dto.getDeviceTypeCode(),dto.getMaterialCode(),dto.getPartCode());
        deviceCode.stream().forEach(entity->{
            AccessoryPartDetails accessoryPartDtails = new AccessoryPartDetails();
            accessoryPartDtails.setId(entity.getId());
            accessoryPartDtails.setPartCode(entity.getPartCode());
            accessoryPartDtails.setPartName(entity.getPartName());
            accessoryPartDtails.setMaterialCode(entity.getMaterialCode());
            accessoryPartDtails.setMaterialId(entity.getMaterialId());
            accessoryPartDtails.setMaterialName(entity.getMaterialName());
            accessoryPartDtails.setDeviceModelId(Integer.valueOf(String.valueOf(dto.getId())));
            accessoryPartDtails.setDeviceModelCode(dto.getDeviceModelCode());
            accessoryPartDtails.setDeviceModelName(dto.getDeviceModelName());
            accessoryPartDtails.setDeviceTypeId(entity.getDeviceTypeId());
            accessoryPartDtails.setDeviceTypeCode(entity.getDeviceTypeCode());
            accessoryPartDtails.setDeviceTypeName(entity.getDeviceTypeName());
            accessoryPartDtails.setCreateBy(BaseContextHandler.getUsername());
            accessoryPartDtails.setCreateTime(new Date());
            accessoryPartDtails.setTotalNumber(dto.getTotalNumber());
            accessoryPartDtails.setUsableNumber(dto.getTotalNumber() - entity.getUsedNumber());
            accessoryPartDtails.setIsUse(dto.getTotalNumber() - entity.getUsedNumber() >0?true:false);
            accessoryPartDtails.setUpdateBy(BaseContextHandler.getUsername());
            accessoryPartDtails.setUpdateTime(new Date());
            accessoryPartDetailsService.saveOrUpdate(accessoryPartDtails);
        });
        if(update == false){
            return ResultGenerator.fail("更新失败",null);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "通过部位编码获取热场物料部位详细信息")
    @GetMapping("/getPartCode")
    public Result<List<AccessoryPartDto>> getPartCode(@RequestParam @ApiParam(value = "热场物料部位编码") String partCode) {
        List<AccessoryPart> byPartCode = accessoryPartService.getByPartCode(partCode);
        if (null == byPartCode) {
            return ResultGenerator.fail("该热场物料部位记录不存在");
        }
        List<AccessoryPartDto> accessoryPartDtos = new ArrayList<>();
        byPartCode.stream().forEach(entity->{
            accessoryPartDtos.add(toEagerDto(entity));
        });
        return ResultGenerator.success(accessoryPartDtos);
    }

    @ApiOperation(value = "通过部位编码获取热场物料部位详细信息")
    @GetMapping("/getMaterialCode")
    public Result<List<AccessoryPartDto>> getMaterialCode(@RequestParam @ApiParam(value = "热场物料物料编码") String materialCode) {
        List<AccessoryPart> byPartCode = accessoryPartService.getByMaterialCode(materialCode);
        if (null == byPartCode) {
            return ResultGenerator.fail("该热场物料部位记录不存在");
        }
        List<AccessoryPartDto> accessoryPartDtos = new ArrayList<>();
        byPartCode.stream().forEach(entity->{
            accessoryPartDtos.add(toEagerDto(entity));
        });
        return ResultGenerator.success(accessoryPartDtos);
    }

    @ApiOperation(value = "通过部位编码获取热场物料部位详细信息")
    @GetMapping("/getCode")
    public Result<AccessoryPartDto> getCode(@RequestParam String deviceTypeCode,@RequestParam String deviceCode,@RequestParam String partCode,@RequestParam String materialCode) {
        AccessoryPart byCode = accessoryPartService.getByCode(deviceTypeCode,deviceCode,materialCode, partCode);
        if (null == byCode) {
            return ResultGenerator.fail("该热场物料部位记录不存在");
        }
        return ResultGenerator.success(toEagerDto(byCode));
    }
    @ApiOperation(value = "通过设备编码获取热场物料部位信息")
    @GetMapping("/getDeviceCode")
    public Result<List<AccessoryPartDetailsDto>> getDeviceCode(@RequestParam(value = "deviceCode") String deviceCode,
                                                        @RequestParam(value = "materialCode",required = false) String materialCode) {
        List<AccessoryPartDetails> byDeviceCode = accessoryPartDetailsService.getByDeviceCode(deviceCode);
        if(!ObjectUtils.isEmpty(materialCode)){
            byDeviceCode = byDeviceCode.stream().filter(entity -> entity.getMaterialCode().equals(materialCode)).collect(Collectors.toList());
        }
        if (null == byDeviceCode) {
            return ResultGenerator.fail("该热场物料部位记录不存在");
        }
        List<AccessoryPartDetailsDto> accessoryPartDtos = new ArrayList<>();
        byDeviceCode.stream().forEach(entity->{
            accessoryPartDtos.add(toEagerDetailsDto(entity));
        });
        return ResultGenerator.success(accessoryPartDtos);
    }
    public AccessoryPartDto toLazyDto(AccessoryPart entity) {
        AccessoryPartDto accessoryPartDto = new AccessoryPartDto();
        BeanUtils.copyProperties(entity,accessoryPartDto);
        return accessoryPartDto;
    }

    public AccessoryPartDto toEagerDto(AccessoryPart entity) {
        AccessoryPartDto accessoryPartDto = new AccessoryPartDto();
        BeanUtils.copyProperties(entity, accessoryPartDto);
        return accessoryPartDto;
    }

    public AccessoryPartDetailsDto toEagerDetailsDto(AccessoryPartDetails entity) {
        AccessoryPartDetailsDto accessoryPartDto = new AccessoryPartDetailsDto();
        BeanUtils.copyProperties(entity, accessoryPartDto);
        return accessoryPartDto;
    }
    public AccessoryPart fromDto(AccessoryPartDto dto) {
        AccessoryPart accessoryPart = new AccessoryPart();
        BeanUtils.copyProperties(dto, accessoryPart);
        return accessoryPart;
    }
}
