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.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.seed.dto.SeedRequireTaskDto;
import com.sw.mes.yb.seed.entity.SeedRequireTask;
import com.sw.mes.yb.seed.service.SeedRequireTaskService;
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.CollectionUtils;
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.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 籽晶原料需求任务接口
 */

@RestController
@RequestMapping("/seed/requireTask")
@Api(description = "籽晶原料需求任务接口")
@Transactional
public class SeedRequireTaskController {

    @Autowired
    private SeedRequireTaskService requireTaskService;

    @Autowired
    ModelMapper modelMapper;

    @ApiOperation(value = "分页查询籽晶原料需求任务信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<SeedRequireTaskDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<SeedRequireTask> specification = DynamicSpecifications.bySearchFilter(request, SeedRequireTask.class);
        Page<SeedRequireTask> seedRequireTasks = requireTaskService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<SeedRequireTaskDto> dtos = seedRequireTasks.getContent().stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, seedRequireTasks.getTotalElements());
        return ResultGenerator.success(responsePage);
    }


    @GetMapping("/listAll")
    @ApiOperation(value = "查询籽晶原料需求任务信息列表")
    public Result<List<SeedRequireTaskDto>> listAll(ServletRequest request) {
        Specification<SeedRequireTask> specification = DynamicSpecifications.bySearchFilter(request, SeedRequireTask.class);
        List<SeedRequireTask> seedRequireTasks = requireTaskService.findByExampleSort(specification, null);
        List<SeedRequireTaskDto> dtos = seedRequireTasks.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/findOldSeedRequireTask")
    @ApiOperation(value = "查询未完成籽晶原料需求任务信息列表")
    public Result<List<SeedRequireTaskDto>> findOldSeedRequireTask() {
        List<SeedRequireTask> seedRequireTasks = requireTaskService.findOldSeedRequireTask();
        List<SeedRequireTaskDto> dtos = seedRequireTasks.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询籽晶原料需求任务")
    public Result<SeedRequireTaskDto> getById(@PathVariable @ApiParam(value = "id") Long id) {
        SeedRequireTask seedRequireTask = requireTaskService.get(id);
        if (ObjectUtils.isEmpty(seedRequireTask)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedRequireTask));
    }

    @ApiOperation(value = "创建籽晶原料需求任务")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "SeedDataDto的对象") SeedRequireTaskDto seedRequireTaskDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return requireTaskService.create(seedRequireTaskDto);
    }

    @ApiOperation(value = "更新籽晶原料需求任务")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "SeedDataDto的对象") SeedRequireTaskDto seedRequireTaskDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return requireTaskService.update(seedRequireTaskDto);
    }



    @GetMapping("/findByCode")
    @ApiOperation(value = "通过任务编码查询籽晶原料需求任务")
    public Result<SeedRequireTaskDto> getById(@RequestParam @ApiParam(value = "code") String code) {
        SeedRequireTask seedRequireTask = requireTaskService.findByCode(code);
        if (ObjectUtils.isEmpty(seedRequireTask)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedRequireTask));
    }

    @ApiOperation(value = "删除籽晶原料需求任务")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            SeedRequireTask seedRequireTask = requireTaskService.get(id);
            if (!ObjectUtils.isEmpty(seedRequireTask)) {
                seedRequireTask.setDel(true);
                requireTaskService.saveOrUpdate(seedRequireTask);
            }
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "定时更新籽晶原料需求任务状态")
    @PostMapping("/updateSeedRequireTaskJobHandler")
    public Result updateSeedRequireTaskJobHandler() {
        List<SeedRequireTask> seedRequireTasks = requireTaskService.findSeedRequireTask();
        if (!CollectionUtils.isEmpty(seedRequireTasks)) {
            seedRequireTasks.forEach(entity->{
                entity.setDel(true);
                requireTaskService.saveOrUpdate(entity);
            });
        }
        return ResultGenerator.success();
    }

    public SeedRequireTaskDto toLazyDto(SeedRequireTask entity) {
        SeedRequireTaskDto seedRequireTaskDto = new SeedRequireTaskDto();
        BeanUtils.copyProperties(entity, seedRequireTaskDto);
        if(null == seedRequireTaskDto.getAllotQuantity()){
            seedRequireTaskDto.setAllotQuantity(new BigDecimal(0));
        }
        return seedRequireTaskDto;
    }

    public SeedRequireTaskDto toEagerDto(SeedRequireTask entity) {
        SeedRequireTaskDto seedRequireTaskDto = new SeedRequireTaskDto();
        BeanUtils.copyProperties(entity, seedRequireTaskDto);
        return seedRequireTaskDto;
    }

    public SeedRequireTask fromDto(SeedRequireTaskDto dto) {
        SeedRequireTask seedRequireTask = new SeedRequireTask();
        BeanUtils.copyProperties(dto, seedRequireTask);
        return seedRequireTask;
    }
}
