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

import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.store.WarehouseOutputBillBo;
import com.sw.mes.core.dto.store.WarehouseOutputBillDetailBo;
import com.sw.mes.core.enums.SeedStoreStatusEnum;
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.SeedGroupBracketDetailsDto;
import com.sw.mes.yb.seed.dto.SeedGroupBracketDto;
import com.sw.mes.yb.seed.entity.SeedData;
import com.sw.mes.yb.seed.entity.SeedGroupBracket;
import com.sw.mes.yb.seed.entity.SeedGroupBracketDetails;
import com.sw.mes.yb.seed.service.SeedGroupBracketDetailsService;
import com.sw.mes.yb.seed.service.SeedGroupBracketService;
import com.sw.mes.yb.seed.service.SeedService;
import com.sw.mes.yb.seed.utils.CodeSender;
import com.sw.mes.yb.seed.utils.SeedBatchNoGenerator;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/seed/bracket")
@Api(description = "籽晶组托主表接口")
@Transactional
public class SeedGroupBracketController {
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    private SeedGroupBracketService seedGroupBracketService;
    @Autowired
    private SeedGroupBracketDetailsService seedGroupBracketDetailsService;

    @ApiOperation(value = "分页查询籽晶组托列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<SeedGroupBracketDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<SeedGroupBracket> specification = DynamicSpecifications.bySearchFilter(request, SeedGroupBracket.class);
        Page<SeedGroupBracket> seedGroupBrackets = seedGroupBracketService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<SeedGroupBracketDto> dtos = seedGroupBrackets.getContent().stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, seedGroupBrackets.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @GetMapping("/listAll")
    @ApiOperation(value = "查询籽晶组托列表")
    public Result<List<SeedGroupBracketDto>> listAll(ServletRequest request) {
        Specification<SeedGroupBracket> specification = DynamicSpecifications.bySearchFilter(request, SeedGroupBracket.class);
        List<SeedGroupBracket> seedGroupBrackets = seedGroupBracketService.findByExampleSort(specification, null);
        List<SeedGroupBracketDto> dtos = seedGroupBrackets.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询籽晶组托详情")
    public Result<SeedGroupBracketDto> getById(@PathVariable @ApiParam(value = "id") Long id) {
        SeedGroupBracket seedGroupBracket = seedGroupBracketService.get(id);
        if (ObjectUtils.isEmpty(seedGroupBracket)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        List<SeedGroupBracketDetails> seedGroupBracketDetails = seedGroupBracketDetailsService.findParentId(id);
        List<SeedGroupBracketDetailsDto> seedGroupBracketDetailsDtos = new ArrayList<>();
        seedGroupBracketDetails.stream().forEach(entity -> {
            SeedGroupBracketDetailsDto seedGroupBracketDetailsDto = new SeedGroupBracketDetailsDto();
            BeanUtils.copyProperties(entity, seedGroupBracketDetailsDto);
            seedGroupBracketDetailsDto.setId(entity.getId());
            seedGroupBracketDetailsDtos.add(seedGroupBracketDetailsDto);
        });
        SeedGroupBracketDto seedGroupBracketDto = toEagerDto(seedGroupBracket);
        seedGroupBracketDto.setDetailsDtos(seedGroupBracketDetailsDtos);
        return ResultGenerator.success(seedGroupBracketDto);
    }

    @GetMapping("/findGroupBracketByCode")
    @ApiOperation(value = "通过托号查询籽晶组托详情")
    public Result<SeedGroupBracketDto> findGroupBracketByCode(@RequestParam @ApiParam(value = "id") String code) {
        SeedGroupBracketDto groupBrackeByCode = seedGroupBracketService.findGroupBracketByCode(code);
        return ResultGenerator.success(groupBrackeByCode);
    }

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

    @ApiOperation(value = "更新籽晶组托")
    @PostMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody @Valid @ApiParam(value = "SeedGroupBracketDto的对象") SeedGroupBracketDto seedGroupBracketDto) {
        return seedGroupBracketService.update(seedGroupBracketDto);
    }

    @ApiOperation(value = "更新籽晶组托")
    @PostMapping("/updateSeedGroupBracket")
    public Result updateSeedGroupBracket(@RequestBody @Valid @ApiParam(value = "SeedGroupBracketDto的对象") SeedGroupBracketDto seedGroupBracketDto) {
        SeedGroupBracket seedGroupBracket = new SeedGroupBracket();
        BeanUtils.copyProperties(seedGroupBracketDto, seedGroupBracket);
        seedGroupBracketService.saveOrUpdate(seedGroupBracket);
        seedGroupBracketDto.getDetailsDtos().forEach(seedGroupBracketDetailsDto ->{
            SeedGroupBracketDetails seedGroupBracketDetails = new SeedGroupBracketDetails();
            BeanUtils.copyProperties(seedGroupBracketDetailsDto,seedGroupBracketDetails);
            seedGroupBracketDetailsService.saveOrUpdate(seedGroupBracketDetails);
        });
        return ResultGenerator.success();
    }

    /**
     * 更新籽晶组托(接收线边仓)
     *
     * @param billCode
     * @param status
     * @return
     */
    @ApiOperation(value = "更新籽晶组托(接收线边仓)")
    @GetMapping("/bracketUpdate")
    public Result bracketUpdate(@RequestParam String billCode, @RequestParam String status) {
        SeedGroupBracket serviceBillCode = seedGroupBracketService.findBillCode(billCode);
        serviceBillCode.setStatus(status);
        seedGroupBracketService.saveOrUpdate(serviceBillCode);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "发起入库")
    @GetMapping("/initiate")
    public Result initiate(@RequestParam @ApiParam(value = "id") Long id) {
        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除籽晶组托")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            seedGroupBracketService.delete(id);
            List<SeedGroupBracketDetails> seedGroupBracketDetails = seedGroupBracketDetailsService.findParentId(id);
            if(!CollectionUtils.isEmpty(seedGroupBracketDetails)){
                seedGroupBracketDetails.stream().forEach(entity->{
                    seedGroupBracketDetailsService.delete(entity.getId());
                });
            }
        }
        return ResultGenerator.success();
    }


    public SeedGroupBracketDto toLazyDto(SeedGroupBracket entity) {
        SeedGroupBracketDto seedGroupBracketDto = new SeedGroupBracketDto();
        BeanUtils.copyProperties(entity, seedGroupBracketDto);
        return seedGroupBracketDto;
    }

    public SeedGroupBracketDto toEagerDto(SeedGroupBracket entity) {
        SeedGroupBracketDto seedGroupBracketDto = new SeedGroupBracketDto();
        BeanUtils.copyProperties(entity, seedGroupBracketDto);
        return seedGroupBracketDto;
    }

    public SeedGroupBracket fromDto(SeedGroupBracketDto dto) {
        SeedGroupBracket seedGroupBracket = new SeedGroupBracket();
        BeanUtils.copyProperties(dto, seedGroupBracket);
        return seedGroupBracket;
    }

}
