package com.sw.mes.production.controller;

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
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.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.*;
import com.sw.mes.production.entity.FormulaScheme;
import com.sw.mes.production.entity.FormulaSchemeDetail;
import com.sw.mes.production.service.FormulaSchemeDetailService;
import com.sw.mes.production.service.FormulaSchemeOutService;
import com.sw.mes.production.service.FormulaSchemeService;
import com.sw.mes.yb.mcs.service.YbMesToMcsService;
import io.swagger.annotations.*;
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.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


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

    @Autowired
    private FormulaSchemeService formulaSchemeService;

    @Autowired
    private FormulaSchemeDetailService formulaSchemeDetailService;

    @Autowired
    private FormulaSchemeOutService formulaSchemeOutService;

    @Autowired
    private YbMesToMcsService mesToMcsService;

    @ApiOperation(value = "分页查询配方方案列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Long", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<FormulaSchemeDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<FormulaScheme> specification = DynamicSpecifications.bySearchFilter(request, FormulaScheme.class);
        Page<FormulaScheme> page = formulaSchemeService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<FormulaSchemeDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "测试")
    @GetMapping("/test")
    public Result<FormulaSchemeData> test(DecompositionSchemeParam decompositionSchemeParam) {
       FormulaSchemeData formulaSchemeDatas;
       try {
           formulaSchemeDatas = formulaSchemeOutService.decompositionScheme(decompositionSchemeParam);
       }catch (Exception e){
           log.error("配方测试：", e);
          return ResultGenerator.fail(e.getMessage());
       }
        return ResultGenerator.success(formulaSchemeDatas);
    }


    @ApiOperation(value = "获取所有配方方案")
    @GetMapping("/listAll")
    public Result<List<FormulaSchemeDto>> listAll(ServletRequest request) {
        Specification<FormulaScheme> specification = DynamicSpecifications.bySearchFilter(request, FormulaScheme.class);
        List<FormulaScheme> formulaSchemes = formulaSchemeService.findByExampleSort(specification, null);
        List<FormulaSchemeDto> formulaSchemeDtos = formulaSchemes.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(formulaSchemeDtos);
    }

    @ApiOperation(value = "配方方案详细信息")
    @GetMapping("/{id}")
    public Result<FormulaSchemeDto> get(@PathVariable @ApiParam(value = "配方方案id") Long id) {
        FormulaScheme formulaScheme = formulaSchemeService.get(id);
        if (null == formulaScheme)
            return ResultGenerator.fail("该配方方案不存在");
        return ResultGenerator.success(toEagerDto(formulaScheme));
    }

    @ApiOperation(value = "复制配方方案")
    @GetMapping("/copy/{id}")
    public Result<FormulaSchemeDto> copy(@PathVariable @ApiParam(value = "配方方案id") Long id) {
        FormulaScheme formulaScheme = formulaSchemeService.get(id);
        if (null == formulaScheme)
            return ResultGenerator.fail("该配方方案不存在");
        FormulaSchemeDto formulaSchemeDto = toEagerDto(formulaScheme);
        formulaSchemeDto.setId(null);
        formulaSchemeDto.getFormulaSchemeDetailDtos().forEach(formulaSchemeDetailDto -> {
            formulaSchemeDetailDto.setId(null);
            formulaSchemeDetailDto.setFormulaSchemeId(null);
        });
        return ResultGenerator.success(formulaSchemeDto);
    }

    @ApiOperation(value = "验证配方方案")
    @PostMapping("/validate")
    public Result<ValidateResult> validate(@RequestBody @Valid @ApiParam(value = "配方方案验证对象") ValidateScheme validateScheme, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        ValidateResult validateResult = formulaSchemeService.validate(validateScheme);
        return ResultGenerator.success(validateResult);
    }

    @ApiOperation(value = "发布配方方案")
    @PostMapping("/release/{id}")
    public Result<FormulaSchemeDto> release(@PathVariable @ApiParam(value = "配方方案id") Long id) {
        FormulaScheme formulaScheme = formulaSchemeService.get(id);
        if (null == formulaScheme) {
            return ResultGenerator.fail("该配方方案不存在");
        }
        Assert.isTrue(!formulaScheme.getStatus(), "该配方方案已发布");
        Assert.isTrue(formulaScheme.getValidating(), "该配方方案验证不通过，不允许发布");
        formulaScheme.setStatus(true);
        formulaSchemeService.saveOrUpdate(formulaScheme);
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_AUTOMATION, "CanningMaterial", false)) {
            //配方方案下发 装罐料下发
            mesToMcsService.formulaSchemeToMcs(formulaScheme.getId());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "关闭配方方案")
    @PostMapping("/close/{id}")
    public Result<FormulaSchemeDto> close(@PathVariable @ApiParam(value = "配方方案id") Long id) {
        FormulaScheme formulaScheme = formulaSchemeService.get(id);
        if (null == formulaScheme) {
            return ResultGenerator.fail("该配方方案不存在");
        }
        Assert.isTrue(formulaScheme.getStatus(), "该配方方案已失效");
        formulaScheme.setStatus(false);
        formulaSchemeService.saveOrUpdate(formulaScheme);
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_AUTOMATION, "CanningMaterial", false)) {
            //配方方案下发 装罐料下发
            mesToMcsService.formulaSchemeToMcs(formulaScheme.getId());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建配方方案")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "配方方案对象") FormulaSchemeDto formulaSchemeDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        formulaSchemeDto.setVersion(formulaSchemeService.getMaxVersion(formulaSchemeDto.getCode()) + 1);
        FormulaScheme formulaScheme = fromDto(formulaSchemeDto);
        List<FormulaSchemeDetail> formulaSchemeDetails = formulaSchemeDto.getFormulaSchemeDetailDtos().stream().map(formulaSchemeDetailDto -> {
            FormulaSchemeDetail formulaSchemeDetail = new FormulaSchemeDetail();
            BeanUtils.copyProperties(formulaSchemeDetailDto, formulaSchemeDetail);
            return formulaSchemeDetail;
        }).collect(Collectors.toList());
        if(formulaScheme.getValidating() == null){
            formulaScheme.setValidating(false);
        }
        if(formulaScheme.getStatus() == null){
            formulaScheme.setStatus(false);
        }
        formulaScheme.setGmtCreate(new Date());
        formulaScheme.setUserCreate(BaseContextHandler.getUsername());
        formulaSchemeService.saveOrUpdate(formulaScheme, formulaSchemeDetails);
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_AUTOMATION, "CanningMaterial", false)) {
            //配方方案下发 装罐料下发
            mesToMcsService.formulaSchemeToMcs(formulaScheme.getId());
        }
        return ResultGenerator.success(formulaScheme.getId());
    }

    @ApiOperation(value = "更新配方方案")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "配方方案") FormulaSchemeDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        FormulaScheme entity = formulaSchemeService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            FormulaScheme entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entity.setGmtUpdate(new Date());
            entity.setUserUpdate(BaseContextHandler.getUsername());
            formulaSchemeService.saveOrUpdate(entity);
            if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_AUTOMATION, "CanningMaterial", false)) {
                //配方方案下发 装罐料下发
                mesToMcsService.formulaSchemeToMcs(entity.getId());
            }
            return ResultGenerator.success();
        } catch (Exception 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) {
            formulaSchemeService.delete(id);
        }
        return ResultGenerator.success();
    }

    public FormulaSchemeDto toLazyDto(FormulaScheme entity) {
        return modelMapper.map(entity, FormulaSchemeDto.class);
    }

    public FormulaSchemeDto toEagerDto(FormulaScheme entity) {
        FormulaSchemeDto dto = modelMapper.map(entity, FormulaSchemeDto.class);
        dto.setFormulaSchemeDetailDtos(formulaSchemeDetailService.findByFormulaSchemeId(entity.getId()).stream()
                .map(formulaSchemeDetail -> {
                    return modelMapper.map(formulaSchemeDetail, FormulaSchemeDetailDto.class);
                })
                .collect(Collectors.toList()));
        return dto;
    }

    public FormulaScheme fromDto(FormulaSchemeDto dto) {
        return modelMapper.map(dto, FormulaScheme.class);
    }
}
