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

import com.sw.mes.base.factory.product.entity.ProductModel;
import com.sw.mes.base.factory.product.service.ProductModelService;
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.SeedPlanOrderDto;
import com.sw.mes.yb.seed.entity.SeedPlanOrder;
import com.sw.mes.yb.seed.enums.SeedPlanStatusEnum;
import com.sw.mes.yb.seed.service.SeedPlanOrderService;
import com.sw.mes.yb.seed.utils.CodeSender;
import io.swagger.annotations.*;
import org.modelmapper.ModelMapper;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/seed/plan")
@Api(description = "籽晶计划单接口")
@Transactional
public class SeedPlanOrderController {
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    private SeedPlanOrderService seedPlanOrderService;
    @Autowired
    private ProductModelService productModelService;

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

    @GetMapping("/listAll")
    @ApiOperation(value = "查询籽晶计划列表")
    public Result<List<SeedPlanOrderDto>> listAll(ServletRequest request) {
        Specification<SeedPlanOrder> specification = DynamicSpecifications.bySearchFilter(request, SeedPlanOrder.class);
        List<SeedPlanOrder> seedPlanOrders = seedPlanOrderService.findByExampleSort(specification, null);
        List<SeedPlanOrderDto> dtos = seedPlanOrders.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/normal/listAll")
    @ApiOperation(value = "查询籽晶正常状态的计划列表")
    public Result<List<SeedPlanOrderDto>> normalListAll() {
        List<SeedPlanOrder> seedPlanOrders = seedPlanOrderService.findNormalOrder();
        List<SeedPlanOrderDto> dtos = seedPlanOrders.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询计划单详情")
    public Result<SeedPlanOrderDto> getById(@PathVariable @ApiParam(value = "id") Long id) {
        SeedPlanOrder seedPlanOrders = seedPlanOrderService.get(id);
        if (ObjectUtils.isEmpty(seedPlanOrders)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedPlanOrders));
    }

    @PostMapping("/planCode")
    @ApiOperation(value = "通过计划单编码查询计划单详情")
    public Result<SeedPlanOrderDto> planCode(@RequestParam @ApiParam(value = "planCode") String planCode) {
        SeedPlanOrder seedPlanOrders = seedPlanOrderService.findByCode(planCode);
        if (ObjectUtils.isEmpty(seedPlanOrders)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedPlanOrders));
    }

    @ApiOperation(value = "创建籽晶计划单")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "SeedPlanOrder的对象") SeedPlanOrderDto seedPlanOrderDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SeedPlanOrder serviceByCode = seedPlanOrderService.findByCode(seedPlanOrderDto.getPlanCode());
        if (!ObjectUtils.isEmpty(serviceByCode)) {
            return ResultGenerator.fail("该计划单号已存在!");
        }
        ProductModel productModel = productModelService.findByCode(seedPlanOrderDto.getMaterialCode());
        if (ObjectUtils.isEmpty(productModel)) {
            return ResultGenerator.fail("物料编码【" + seedPlanOrderDto.getMaterialCode() + "】,不存在");
        }
        SeedPlanOrder seedPlanOrder = fromDto(seedPlanOrderDto);
        seedPlanOrder.setMaterialId(productModel.getId());
        seedPlanOrder.setMaterialName(productModel.getName());
        seedPlanOrder.setMaterialType(productModel.getType());
        seedPlanOrder.setDirectionalSign(productModel.getDirectionalSign());
        seedPlanOrder.setSpec(productModel.getSpecs());
        seedPlanOrder.setCreateBy(BaseContextHandler.getUsername());
        seedPlanOrder.setCreateDate(new Date());
        seedPlanOrder.setMaterialModel(productModel.getModelNumber());
        if (ObjectUtils.isEmpty(seedPlanOrderDto.getStatus())) {
            seedPlanOrder.setStatus(SeedPlanStatusEnum.正常.getStatus());
        }
        if (ObjectUtils.isEmpty(seedPlanOrderDto.getProductionStatus())) {
            seedPlanOrder.setProductionStatus(false);
        }
        seedPlanOrderService.saveOrUpdate(seedPlanOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "关闭籽晶计划单")
    @GetMapping("/closeOrder/{id}")
    public Result closeOrder(@PathVariable @ApiParam(value = "SeedPlanOrder的id") Long id) {
        SeedPlanOrder seedPlanOrder = seedPlanOrderService.get(id);
        if (ObjectUtils.isEmpty(seedPlanOrder)) {
            return ResultGenerator.fail("该计划单不存在!");
        }
        seedPlanOrder.setStatus(SeedPlanStatusEnum.已关闭.getStatus());
        seedPlanOrder.setOperationBy(BaseContextHandler.getUsername());
        seedPlanOrder.setOperationDate(new Date());
        seedPlanOrder.setUpdateBy(BaseContextHandler.getUsername());
        seedPlanOrder.setUpdateDate(new Date());
        seedPlanOrderService.saveOrUpdate(seedPlanOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "调整计划单生产状态")
    @PostMapping("/updateProductionStatus/{id}/{productionStatus}")
    public Result updateProductionStatus(@PathVariable @ApiParam(value = "SeedPlanOrder的id") Long id,
                                         @PathVariable @ApiParam("是否生产状态") Boolean productionStatus) {
        SeedPlanOrder seedPlanOrder = seedPlanOrderService.get(id);
        if (ObjectUtils.isEmpty(seedPlanOrder)) {
            return ResultGenerator.fail("该计划单不存在!");
        }
        seedPlanOrder.setProductionStatus(productionStatus);
        seedPlanOrder.setUpdateBy(BaseContextHandler.getUsername());
        seedPlanOrder.setUpdateDate(new Date());
        seedPlanOrder.setOperationBy(BaseContextHandler.getUsername());
        seedPlanOrder.setOperationDate(new Date());
        seedPlanOrderService.saveOrUpdate(seedPlanOrder);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新计划单信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "SeedPlanOrder的对象") SeedPlanOrderDto seedPlanOrderDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SeedPlanOrder serviceByCode = seedPlanOrderService.findByCode(seedPlanOrderDto.getPlanCode());
        if (ObjectUtils.isEmpty(serviceByCode)) {
            return ResultGenerator.fail("原计划单不存在!");
        }
        ProductModel productModel = productModelService.findByCode(seedPlanOrderDto.getMaterialCode());
        if (ObjectUtils.isEmpty(productModel)) {
            return ResultGenerator.fail("物料编码【" + seedPlanOrderDto.getMaterialCode() + "】,不存在");
        }
        SeedPlanOrder seedPlanOrder = fromDto(seedPlanOrderDto);
        seedPlanOrder.setId(serviceByCode.getId());
        seedPlanOrder.setMaterialId(productModel.getId());
        seedPlanOrder.setMaterialName(productModel.getName());
        seedPlanOrder.setMaterialType(productModel.getType());
        seedPlanOrder.setSpec(productModel.getSpecs());
        seedPlanOrder.setUpdateBy(BaseContextHandler.getUsername());
        seedPlanOrder.setUpdateDate(new Date());
        seedPlanOrder.setMaterialModel(productModel.getModelNumber());
        seedPlanOrder.setCreateBy(serviceByCode.getCreateBy());
        seedPlanOrder.setCreateDate(serviceByCode.getCreateDate());
        if (ObjectUtils.isEmpty(seedPlanOrderDto.getStatus())) {
            seedPlanOrder.setStatus(SeedPlanStatusEnum.正常.getStatus());
        }
        if (ObjectUtils.isEmpty(seedPlanOrderDto.getProductionStatus())) {
            seedPlanOrder.setProductionStatus(false);
        }
        seedPlanOrderService.saveOrUpdate(seedPlanOrder);
        return ResultGenerator.success();
    }

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

    public SeedPlanOrderDto toLazyDto(SeedPlanOrder entity) {
        return modelMapper.map(entity, SeedPlanOrderDto.class);
    }

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

    public SeedPlanOrder fromDto(SeedPlanOrderDto dto) {
        return modelMapper.map(dto, SeedPlanOrder.class);
    }
}
