package com.sw.mes.production.controller;

import com.alibaba.fastjson.JSON;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.exception.BusinessException;
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.BeanUtil;
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.production.dto.FormulaProductSchemeDetailDto;
import com.sw.mes.production.dto.FormulaProductSchemeDto;
import com.sw.mes.production.entity.FormulaProductScheme;
import com.sw.mes.production.entity.FormulaProductSchemeDetail;
import com.sw.mes.production.entity.FormulaProductSchemeWeightDetail;
import com.sw.mes.production.service.FormulaProductSchemeDetailService;
import com.sw.mes.production.service.FormulaProductSchemeService;
import com.sw.mes.production.service.FormulaProductSchemeWeightDetailService;
import io.swagger.annotations.*;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
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.util.Assert;
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;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/formulaProductScheme")
@Slf4j
@Api(tags = "产品方案接口")
public class FormulaProductSchemeController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FormulaProductSchemeService formulaProductSchemeService;

    @Autowired
    private FormulaProductSchemeDetailService productSchemeDetailService;

    @Autowired
    private FormulaProductSchemeWeightDetailService productSchemeWeightDetailService;

    @ApiOperation(value = "分页查询产品方案列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Long", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<FormulaProductSchemeDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<FormulaProductScheme> specification = DynamicSpecifications.bySearchFilter(request, FormulaProductScheme.class);
        Page<FormulaProductScheme> page = formulaProductSchemeService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<FormulaProductSchemeDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        // 补充方案详情
        for (FormulaProductSchemeDto dto : dtos) {
            List<FormulaProductSchemeWeightDetail> weightDetailList = productSchemeWeightDetailService.getListByFpsId(dto.getId());
            for (FormulaProductSchemeWeightDetail weightDetail : weightDetailList) {
                List<FormulaProductSchemeDetail> schemeDetailList = productSchemeDetailService.getListByFpsIdAndWsId(dto.getId(), weightDetail.getWeightSchemeId());
                weightDetail.setSchemeDetailList(schemeDetailList);
            }
            dto.setWeightDetailList(weightDetailList);
        }
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有产品方案")
    @GetMapping("/listAll")
    public Result<List<FormulaProductSchemeDto>> listAll(ServletRequest request) {
        Specification<FormulaProductScheme> specification = DynamicSpecifications.bySearchFilter(request, FormulaProductScheme.class);
        List<FormulaProductScheme> formulaProductSchemes = formulaProductSchemeService.findByExampleSort(specification, null);
        List<FormulaProductSchemeDto> formulaProductSchemeDtos = formulaProductSchemes.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(formulaProductSchemeDtos);
    }

    @ApiOperation(value = "产品方案详细信息")
    @GetMapping("/{id}")
    public Result<FormulaProductSchemeDto> get(@PathVariable @ApiParam(value = "产品方案id") Long id) {
        FormulaProductScheme formulaProductScheme = formulaProductSchemeService.get(id);
        if (null == formulaProductScheme)
            return ResultGenerator.fail("该产品方案不存在");
        FormulaProductSchemeDto dto = toEagerDto(formulaProductScheme);
        List<FormulaProductSchemeWeightDetail> weightDetailList = productSchemeWeightDetailService.getListByFpsId(dto.getId());
        for (FormulaProductSchemeWeightDetail weightDetail : weightDetailList) {
            List<FormulaProductSchemeDetail> schemeDetailList = productSchemeDetailService.getListByFpsIdAndWsId(dto.getId(), weightDetail.getWeightSchemeId());
            weightDetail.setSchemeDetailList(schemeDetailList);
        }
        dto.setWeightDetailList(weightDetailList);
        return ResultGenerator.success(dto);
    }

    @ApiOperation(value = "创建产品方案")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "产品方案对象") FormulaProductSchemeDto formulaProductSchemeDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        FormulaProductScheme formulaProductScheme = formulaProductSchemeService.findByEquipmentCodeAndProductModeCode(formulaProductSchemeDto.getEquipmentCode(),
                formulaProductSchemeDto.getProductModeCode());
        Assert.isNull(formulaProductScheme, "该设备下已存在该产品的配方方案，请不要重复添加");

        try{
            formulaProductSchemeService.create(formulaProductSchemeDto);
        }catch (Exception e){
            log.error("创建产品方案", e);
            return ResultGenerator.fail(e.getMessage());
        }

        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建产品方案-批量")
    @PostMapping("/creates")
    public Result creates(@RequestBody @Valid @ApiParam(value = "产品方案对象") List<FormulaProductSchemeDto> formulaProductSchemeDtos, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            return ResultGenerator.success(formulaProductSchemeService.createsV2(formulaProductSchemeDtos));
        }catch (Exception e){
            log.error("创建产品方案-批量", e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "创建产品方案-批量V2")
    @PostMapping("/createBatch")
    public Result createBatch(@RequestBody @Valid @ApiParam(value = "产品方案对象") FormulaProductSchemeDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            formulaProductSchemeService.createBatch(dto);
        }catch (Exception e){
            log.error("创建产品方案-批量V2", e);
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新产品方案")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "产品方案") FormulaProductSchemeDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        FormulaProductScheme entity = formulaProductSchemeService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        FormulaProductScheme entityCheck = formulaProductSchemeService.findByEquipmentCodeAndProductModeCode(dto.getEquipmentCode(),dto.getProductModeCode());
        Assert.isTrue(entityCheck == null || entityCheck.getId().equals(dto.getId()), "该设备下已存在该产品的配方方案，请不要重复添加");
        // 检查配方
        List<FormulaProductSchemeWeightDetail> weightDetailList = dto.getWeightDetailList();
        Assert.notEmpty(weightDetailList, "设备【"+dto.getEquipmentCode()+"】料号【"+dto.getProductModeCode()+"】拆桶方案不能为空");
        for (FormulaProductSchemeWeightDetail weightDetail : weightDetailList) {
            List<FormulaProductSchemeDetail> schemeDetailList = weightDetail.getSchemeDetailList();
            Assert.notEmpty(schemeDetailList, "设备【"+dto.getEquipmentCode()+"】料号【"+dto.getProductModeCode()+"】拆桶方案【"+weightDetail.getWeightSchemeName()+"】配方方案不能为空");
            String checkAgainNumMsg = formulaProductSchemeService.checkAgainNum(schemeDetailList);
            if (StringUtil.isNotBlank(checkAgainNumMsg)){
                return ResultGenerator.fail("设备【"+dto.getEquipmentCode()+"】料号【"+dto.getProductModeCode()+"】拆桶方案【"+weightDetail.getWeightSchemeName()+"】" + checkAgainNumMsg);
            }
        }
        try {
            formulaProductSchemeService.update(dto, entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error("更新产品方案", e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除产品方案")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            formulaProductSchemeService.delete(id);
            productSchemeDetailService.deleteByFpsId(id);
        }
        return ResultGenerator.success();
    }


    public FormulaProductSchemeDto toLazyDto(FormulaProductScheme entity) {
        return modelMapper.map(entity, FormulaProductSchemeDto.class);
    }

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

    public FormulaProductScheme fromDto(FormulaProductSchemeDto dto) {
        return modelMapper.map(dto, FormulaProductScheme.class);
    }




}
