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

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.DynamicSpecifications;
import com.sw.mes.core.utils.ExcelUtil;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.seed.dto.SeedSelfInspectionDto;
import com.sw.mes.yb.seed.entity.SeedData;
import com.sw.mes.yb.seed.entity.SeedSelfInspection;
import com.sw.mes.yb.seed.service.SeedSelfInspectionService;
import com.sw.mes.yb.seed.service.SeedService;
import io.swagger.annotations.*;
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.transaction.annotation.Transactional;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/seed/self")
@Api(description = "籽晶自检接口")
@Transactional
public class SeedSelfInspectionController {
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    private SeedSelfInspectionService seedSelfInspectionService;
    @Autowired
    private SeedService seedService;
    @ApiOperation(value = "分页查询籽晶自检信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<SeedSelfInspectionDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<SeedSelfInspection> specification = DynamicSpecifications.bySearchFilter(request, SeedSelfInspection.class);
        Page<SeedSelfInspection> selfInspections = seedSelfInspectionService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<SeedSelfInspectionDto> dtos = selfInspections.getContent().stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, selfInspections.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @GetMapping("/qualified/listAll")
    @ApiOperation(value = "查询籽晶自检合格/不合格的数据")
    public Result<List<SeedSelfInspectionDto>> qualified(@RequestParam Boolean isQualified) {
        List<SeedSelfInspection> selfInspections = seedSelfInspectionService.getQualified(isQualified);
        List<SeedSelfInspectionDto> dtos = selfInspections.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/listAll")
    @ApiOperation(value = "查询籽晶自检信息列表")
    public Result<List<SeedSelfInspectionDto>> listAll(ServletRequest request) {
        Specification<SeedSelfInspection> specification = DynamicSpecifications.bySearchFilter(request, SeedSelfInspection.class);
        List<SeedSelfInspection> selfInspections = seedSelfInspectionService.findByExampleSort(specification, null);
        List<SeedSelfInspectionDto> dtos = selfInspections.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询籽晶自检信息")
    public Result<SeedSelfInspectionDto> getById(@PathVariable @ApiParam(value = "id") Long id) {
        SeedSelfInspection seedSelfInspection = seedSelfInspectionService.get(id);
        if (ObjectUtils.isEmpty(seedSelfInspection)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedSelfInspection));
    }

    @ApiOperation(value = "创建籽晶自检信息")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "SeedSelfInspectionDto的对象") SeedSelfInspectionDto seedSelfInspectionDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return seedSelfInspectionService.create(seedSelfInspectionDto);
    }

    @ApiOperation(value = "自动化创建籽晶自检信息")
    @PostMapping("/automationCreate")
    public Result automationCreate(@RequestBody @Valid @ApiParam(value = "SeedSelfInspectionDto的对象") SeedSelfInspectionDto seedSelfInspectionDto) {
        return seedSelfInspectionService.create(seedSelfInspectionDto);
    }

    @ApiOperation(value = "修改籽晶自检信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "SeedSelfInspectionDto的对象") SeedSelfInspectionDto seedSelfInspectionDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SeedSelfInspection seedCode = seedSelfInspectionService.getBySeedCode(seedSelfInspectionDto.getSeedCode());
        if (ObjectUtils.isEmpty(seedCode)) {
            return ResultGenerator.fail("该数据不存在!");
        }
        SeedSelfInspection seedSelfInspection = fromDto(seedSelfInspectionDto);
        seedSelfInspection.setId(seedCode.getId());
        seedSelfInspection.setUpdateBy(BaseContextHandler.getUsername());
        seedSelfInspection.setUpdateDate(new Date());
        seedSelfInspectionService.saveOrUpdate(seedSelfInspection);
        SeedData seedData = seedService.findByCode(seedCode.getSeedCode());
        if(!ObjectUtils.isEmpty(seedData)){
            if(seedSelfInspection.getIsQualified() == true){
                seedData.setSelfQualified(true);
                seedData.setDetectionTime(seedSelfInspection.getUpdateDate());
                seedService.saveOrUpdate(seedData);
            }else {
                seedData.setSelfQualified(false);
                seedData.setDetectionTime(seedSelfInspection.getUpdateDate());
                seedService.saveOrUpdate(seedData);
            }
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除籽晶自检信息")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            seedSelfInspectionService.delete(id);
        }
        return ResultGenerator.success();
    }

    @GetMapping("/seedCode")
    @ApiOperation(value = "通过籽晶编码查询籽晶自检信息")
    public Result<SeedSelfInspectionDto> getSeedCode(@RequestParam @ApiParam(value = "seedCode") String seedCode) {
        SeedSelfInspection seedData = seedSelfInspectionService.getBySeedCode(seedCode);
        return ResultGenerator.success(toEagerDto(seedData));
    }

    @GetMapping("/seedBatchNo")
    @ApiOperation(value = "通过籽晶序列号查询籽晶自检信息")
    public Result<SeedSelfInspectionDto> getSeedBatchNo(@RequestParam @ApiParam(value = "seedBatchNo") String seedBatchNo) {
        SeedSelfInspection seedData = seedSelfInspectionService.getBySeedBatchNo(seedBatchNo);
        return ResultGenerator.success(toEagerDto(seedData));
    }

    @GetMapping("/planCode")
    @ApiOperation(value = "通过籽晶计划单号查询籽晶自检信息")
    public Result<List<SeedSelfInspection>> getByPlanCode(@RequestParam @ApiParam(value = "planCode") String planCode) {
        List<SeedSelfInspection> selfInspections = seedSelfInspectionService.getByPlanCode(planCode);
        return ResultGenerator.success(selfInspections);
    }

    @GetMapping("/batchNo")
    @ApiOperation(value = "通过序列号查询自检信息")
    public Result<List<SeedSelfInspection>> getBatchNo(@RequestParam @ApiParam(value = "batchNo") String batchNo) {
        List<SeedSelfInspection> inspections = seedSelfInspectionService.getByBatchNo(batchNo);
        return ResultGenerator.success(inspections);
    }
    @ApiOperation(value = "导出籽晶自检信息接口")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, HttpServletResponse response) {
        Specification<SeedSelfInspection> specification = DynamicSpecifications.bySearchFilter(request, SeedSelfInspection.class);
        List<SeedSelfInspection> byExampleSort = seedSelfInspectionService.findByExampleSort(specification, null);
        List<SeedSelfInspectionDto> dtos = byExampleSort.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        ExcelUtil.exportExcel(dtos, "导出籽晶质检信息接口", SeedSelfInspectionDto.class, response);
    }
    public SeedSelfInspectionDto toLazyDto(SeedSelfInspection entity) {
        if (ObjectUtils.isEmpty(entity)) {
            return null;
        }
        return modelMapper.map(entity, SeedSelfInspectionDto.class);
    }

    public SeedSelfInspectionDto toEagerDto(SeedSelfInspection entity) {
        if (ObjectUtils.isEmpty(entity)) {
            return null;
        }
        SeedSelfInspectionDto dto = modelMapper.map(entity, SeedSelfInspectionDto.class);
        return dto;
    }

    public SeedSelfInspection fromDto(SeedSelfInspectionDto dto) {
        SeedSelfInspection seedSelfInspection = new SeedSelfInspection();
        BeanUtils.copyProperties(dto, seedSelfInspection);
        return seedSelfInspection;
    }
}
