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.RawMaterialLevelImportDto;
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.RawMaterialLevel;
import com.sw.mes.yb.alloy.dto.RawMaterialLevelDto;
import com.sw.mes.yb.alloy.service.RawMaterialLevelService;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/rawMaterialLevel")
@Slf4j
@Api(description = "原料档位接口")
public class RawMaterialLevelController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private RawMaterialLevelService rawMaterialLevelService;

    @ApiOperation(value = "分页查询原料档位列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<RawMaterialLevelDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<RawMaterialLevel> specification = DynamicSpecifications.bySearchFilter(request, RawMaterialLevel.class);
        Page<RawMaterialLevel> page = rawMaterialLevelService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<RawMaterialLevelDto> 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<RawMaterialLevelDto>> listAll(ServletRequest request) {
        Specification<RawMaterialLevel> specification = DynamicSpecifications.bySearchFilter(request, RawMaterialLevel.class);
        List<RawMaterialLevel> rawMaterialLevels = rawMaterialLevelService.findByExampleSort(specification, null);
        List<RawMaterialLevelDto> rawMaterialLevelDtos = rawMaterialLevels.stream()
                .map(rawMaterialLevel -> toLazyDto(rawMaterialLevel))
                .collect(Collectors.toList());
        return ResultGenerator.success(rawMaterialLevelDtos);
    }

    @ApiOperation(value = "原料档位详细信息")
    @GetMapping("/{id}")
    public Result<RawMaterialLevelDto> get(@PathVariable @ApiParam(value = "原料档位id") Integer id) {
        RawMaterialLevel rawMaterialLevel = rawMaterialLevelService.get(id);
        if (null == rawMaterialLevel)
            return ResultGenerator.fail("该原料档位不存在");
        return ResultGenerator.success(toEagerDto(rawMaterialLevel));
    }

    @ApiOperation(value = "创建原料档位")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "原料档位对象") RawMaterialLevelDto rawMaterialLevelDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        RawMaterialLevel rawMaterialLevelDb = rawMaterialLevelService.findByMaterialCodeAndResistanceGear(rawMaterialLevelDto.getMaterialCode(), rawMaterialLevelDto.getResistanceGear());
        if (null != rawMaterialLevelDb) {
            return ResultGenerator.fail("该物料号和电阻档位已存在");
        }
        RawMaterialLevel rawMaterialLevel = fromDto(rawMaterialLevelDto);
        rawMaterialLevel.setCreateUser(BaseContextHandler.getUsername());
        rawMaterialLevel.setCreateDate(new Date());
        rawMaterialLevelService.saveOrUpdate(rawMaterialLevel);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新原料档位")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "原料档位") RawMaterialLevelDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        RawMaterialLevel entity = rawMaterialLevelService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        RawMaterialLevel rawMaterialLevelDb = rawMaterialLevelService.findByMaterialCodeAndResistanceGearAndIdNot(dto.getMaterialCode(), dto.getResistanceGear(), dto.getId());
        if (null != rawMaterialLevelDb) {
            return ResultGenerator.fail("该物料号和电阻档位已存在");
        }
        try {
            RawMaterialLevel entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entity.setUpdateUser(BaseContextHandler.getUsername());
            entity.setUpdateDate(new Date());
            rawMaterialLevelService.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) {
            rawMaterialLevelService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "原料信息导入")
    @PostMapping("/importRawMaterialLevel")
    public Result importRawMaterialLevel(MultipartFile file) {

        try {
            Object objList = EasyExcelUtils.readExcel(file, new RawMaterialLevelImportDto(), 1, 1);
            if (objList != null) {
                List<RawMaterialLevelImportDto> rawMaterialLevelDtoList = (List<RawMaterialLevelImportDto>) objList;
                rawMaterialLevelService.importRawMaterialLevel(rawMaterialLevelDtoList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("原料信息导入错误：", e);
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "原料信息导入模版下载")
    @PostMapping("/downloadTemplate")
    @TokenNotValidation
    public Result exportRawMaterialLevelTemplate(HttpServletResponse response) {
        String path = "template/原料信息导入模版.xlsx";
        ExcelUtil.download1(path, response);
        return ResultGenerator.success();
    }

    public RawMaterialLevelDto toLazyDto(RawMaterialLevel entity) {
        return modelMapper.map(entity, RawMaterialLevelDto.class);
    }

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

    public RawMaterialLevel fromDto(RawMaterialLevelDto dto) {
        return modelMapper.map(dto, RawMaterialLevel.class);
    }


}
