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

import com.sw.mes.base.factory.utils.excel.ExcelUtil;
import com.sw.mes.core.annotation.TokenNotValidation;
import com.sw.mes.core.context.BaseContextHandler;
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.yb.alloy.dto.ResistanceOfThisRodImportDto;
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 org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.sw.mes.yb.alloy.entity.ResistanceOfThisRod;
import com.sw.mes.yb.alloy.dto.ResistanceOfThisRodDto;
import com.sw.mes.yb.alloy.service.ResistanceOfThisRodService;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/resistanceOfThisRod")
@Slf4j
@Api(description = "本棒电阻接口")
public class ResistanceOfThisRodController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private ResistanceOfThisRodService resistanceOfThisRodService;

    @ApiOperation(value = "分页查询本棒电阻列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ResistanceOfThisRodDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<ResistanceOfThisRod> specification = DynamicSpecifications.bySearchFilter(request, ResistanceOfThisRod.class);
        Page<ResistanceOfThisRod> page = resistanceOfThisRodService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ResistanceOfThisRodDto> 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<ResistanceOfThisRodDto>> listAll(ServletRequest request) {
        Specification<ResistanceOfThisRod> specification = DynamicSpecifications.bySearchFilter(request, ResistanceOfThisRod.class);
        List<ResistanceOfThisRod> resistanceOfThisRods = resistanceOfThisRodService.findByExampleSort(specification, null);
        List<ResistanceOfThisRodDto> resistanceOfThisRodDtos = resistanceOfThisRods.stream()
                .map(resistanceOfThisRod -> toLazyDto(resistanceOfThisRod))
                .collect(Collectors.toList());
        return ResultGenerator.success(resistanceOfThisRodDtos);
    }

    @ApiOperation(value = "本棒电阻详细信息")
    @GetMapping("/{id}")
    public Result<ResistanceOfThisRodDto> get(@PathVariable @ApiParam(value = "本棒电阻id") Integer id) {
        ResistanceOfThisRod resistanceOfThisRod = resistanceOfThisRodService.get(id);
        if (null == resistanceOfThisRod)
            return ResultGenerator.fail("该本棒电阻不存在");
        return ResultGenerator.success(toEagerDto(resistanceOfThisRod));
    }

    @ApiOperation(value = "创建本棒电阻")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "本棒电阻对象") ResistanceOfThisRodDto resistanceOfThisRodDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ResistanceOfThisRod resistanceOfThisRod = fromDto(resistanceOfThisRodDto);
        resistanceOfThisRod.setCreateUser(BaseContextHandler.getUsername());
        resistanceOfThisRod.setCreateDate(new Date());
        List<ResistanceOfThisRod> resistanceOfThisRodList = resistanceOfThisRodService.findAllByResistanceOfThisRod(resistanceOfThisRod);
        if (null != resistanceOfThisRodList && resistanceOfThisRodList.size() != 0) {
            return ResultGenerator.fail("本棒电阻信息已存在!!!");
        }
        resistanceOfThisRodService.saveOrUpdate(resistanceOfThisRod);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新本棒电阻")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "本棒电阻") ResistanceOfThisRodDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        ResistanceOfThisRod entity = resistanceOfThisRodService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            ResistanceOfThisRod entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            List<ResistanceOfThisRod> resistanceOfThisRodList = resistanceOfThisRodService.findAllByResistanceOfThisRod(entity);
            if (null != resistanceOfThisRodList && resistanceOfThisRodList.size() != 0) {
                for (ResistanceOfThisRod resistanceOfThisRod : resistanceOfThisRodList) {
                    if (!resistanceOfThisRod.getId().equals(entity.getId())) {
                        return ResultGenerator.fail("本棒电阻已存在!!!");
                    }
                }
            }
            entity.setUpdateUser(BaseContextHandler.getUsername());
            entity.setUpdateDate(new Date());
            resistanceOfThisRodService.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) {
            resistanceOfThisRodService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "本棒电阻信息导入")
    @PostMapping("/importResistanceOfThisRod")
    public Result importResistanceOfThisRod(MultipartFile file) {

        try {
            Object objList = EasyExcelUtils.readExcel(file, new ResistanceOfThisRodImportDto(), 1, 1);
            if (objList != null) {
                List<ResistanceOfThisRodImportDto> resistanceOfThisRodImportDtoList = (List<ResistanceOfThisRodImportDto>) objList;
                resistanceOfThisRodService.importResistanceOfThisRod(resistanceOfThisRodImportDtoList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("本棒电阻信息导入错误：", e);
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "本棒电阻导入模版下载")
    @PostMapping("/downloadTemplate")
    @TokenNotValidation
    public Result exportResistanceOfThisRodTemplate(HttpServletResponse response) {
        String path = "template/本棒电阻导入模版.xlsx";
        ExcelUtil.download1(path, response);
        return ResultGenerator.success();
    }
    public ResistanceOfThisRodDto toLazyDto(ResistanceOfThisRod entity) {
        return modelMapper.map(entity, ResistanceOfThisRodDto.class);
    }

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

    public ResistanceOfThisRod fromDto(ResistanceOfThisRodDto dto) {
        return modelMapper.map(dto, ResistanceOfThisRod.class);
    }


}
