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.*;
import com.sw.mes.yb.seed.dto.SeedBatchesDataDto;
import com.sw.mes.yb.seed.dto.SeedBatchesDto;
import com.sw.mes.yb.seed.dto.SeedDataDto;
import com.sw.mes.yb.seed.entity.SeedData;
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.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 籽晶页面接口
 *
 * @Author：wanjia
 * @Date：2024/1/9 16:57
 */
@RestController
@RequestMapping("/seed")
@Api(description = "籽晶对象接口")
@Transactional
public class SeedDataController {

    @Autowired
    private SeedService seedService;
    @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<SeedDataDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<SeedData> specification = DynamicSpecifications.bySearchFilter(request, SeedData.class);
        Page<SeedData> seedData = seedService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<SeedDataDto> dtos = seedData.getContent().stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, seedData.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

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

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询籽晶详情")
    public Result<SeedDataDto> getById(@PathVariable @ApiParam(value = "id") Long id) {
        SeedData seedData = seedService.get(id);
        if (ObjectUtils.isEmpty(seedData)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedData));
    }

    @PostMapping("/seedCode")
    @ApiOperation(value = "通过籽晶编码查询籽晶详情")
    public Result<SeedDataDto> getSeedCode(@PathVariable @ApiParam(value = "seedCode") String seedCode) {
        SeedData seedData = seedService.findByCode(seedCode);
        if (ObjectUtils.isEmpty(seedData)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedData));
    }

    @PostMapping("/batchNo")
    @ApiOperation(value = "通过籽晶序列号查询籽晶详情-弃用")
    public Result<SeedDataDto> getBatchNo(@PathVariable @ApiParam(value = "batchNo") String batchNo) {
//        SeedData seedData = seedService.findByBatchNo(batchNo);
//        if(ObjectUtils.isEmpty(seedData)){
//            return ResultGenerator.fail("未查到相关数据!");
//        }
//        return ResultGenerator.success(toEagerDto(seedData));
        return ResultGenerator.success();
    }

    @GetMapping("/motherBatchNo")
    @ApiOperation(value = "通过母晶批次查询籽晶数据")
    public Result<List<SeedDataDto>> getMotherBatchNo(@RequestParam @ApiParam(value = "motherBatchNo") String motherBatchNo) {
        List<SeedData> seedDatas = seedService.findByBatchs(motherBatchNo);
        if (ObjectUtils.isEmpty(seedDatas)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        List<SeedDataDto> seedDataDtoList = new ArrayList<>();
        seedDatas.stream().forEach(seedData -> {
            SeedDataDto seedDataDto = new SeedDataDto();
            BeanUtils.copyProperties(seedData, seedDataDto);
            seedDataDtoList.add(seedDataDto);
        });
        return ResultGenerator.success(seedDataDtoList);
    }

    @ApiOperation(value = "创建籽晶对象")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "SeedDataDto的对象") SeedDataDto seedDataDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return seedService.create(seedDataDto);
    }

    @ApiOperation(value = "籽晶分批接口")
    @PostMapping("/batches")
    public Result batches(@RequestBody @Valid @ApiParam(value = "SeedBatchesDto的对象") SeedBatchesDto seedBatchesDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return seedService.batches(seedBatchesDto);
    }

    @ApiOperation(value = "籽晶对象分批提交接口")
    @PostMapping("/submit")
    public Result submit(@RequestBody @Valid @ApiParam(value = "SeedBatchesDataDto") SeedBatchesDataDto seedBatchesDataDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if(null == seedBatchesDataDto.getSeedBatchesDto().getWeight()){
            return ResultGenerator.fail("消耗重量不能为空!");
        }
        return seedService.submit(seedBatchesDataDto);
    }

    @ApiOperation(value = "更新籽晶对象信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "SeedDataDto的对象") SeedDataDto seedDataDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SeedData seedDataCode = seedService.findByCode(seedDataDto.getSeedCode());
        if (ObjectUtils.isEmpty(seedDataCode)) {
            return ResultGenerator.fail("该籽晶对象不存在!");
        }
        SeedData seedData = fromDto(seedDataDto);
        if (!ObjectUtils.isEmpty(seedDataCode)) {
            seedData.setId(seedDataCode.getId());
        }
        seedData.setUpdateBy(BaseContextHandler.getUsername());
        seedData.setUpdateDate(new Date());
        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) {
            seedService.delete(id);
        }
        return ResultGenerator.success();
    }

    public SeedDataDto toLazyDto(SeedData entity) {
        SeedDataDto seedDataDto = new SeedDataDto();
        BeanUtils.copyProperties(entity, seedDataDto);
        return seedDataDto;
    }

    public SeedDataDto toEagerDto(SeedData entity) {
        SeedDataDto seedDataDto = new SeedDataDto();
        BeanUtils.copyProperties(entity,seedDataDto);
        return seedDataDto;
    }

    public SeedData fromDto(SeedDataDto dto) {
        SeedData seedData = new SeedData();
        BeanUtils.copyProperties(dto,seedData);
        return seedData;
    }


}
