package com.sw.mes.yb.check.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.enumvalue.EnumValuesServer;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.check.dto.CrystallonDataDto;
import com.sw.mes.yb.check.dto.LineDetailDto;
import com.sw.mes.yb.check.entity.CrystallonData;
import com.sw.mes.yb.check.service.CrystallonDataService;
import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/CrystallonData")
@Slf4j
@Api(description = "籽晶检验记录接口")
public class CrystallonDataController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private CrystallonDataService crystallonDataService;

    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;

    @Autowired
    private YbInspectDataService ybInspectDataService;

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

    @ApiOperation(value = "获取所有籽晶检验记录")
    @GetMapping("/listAll")
    public Result<List<CrystallonDataDto>> listAll(ServletRequest request) {
        Specification<CrystallonData> specification = DynamicSpecifications.bySearchFilter(request, CrystallonData.class);
        List<CrystallonData> crystallonDatas = crystallonDataService.findByExampleSort(specification, null);
        List<CrystallonDataDto> crystallonDataDtos = crystallonDatas.stream()
                .map(crystallonData -> toLazyDto(crystallonData))
                .collect(Collectors.toList());
        return ResultGenerator.success(crystallonDataDtos);
    }

    @ApiOperation(value = "籽晶检验记录详细信息")
    @GetMapping("/{id}")
    public Result<CrystallonDataDto> get(@PathVariable @ApiParam(value = "籽晶检验记录id") Integer id) {
        CrystallonData crystallonData = crystallonDataService.get(id);
        if (null == crystallonData) {
            return ResultGenerator.fail("该籽晶检验记录不存在");
        }
        return ResultGenerator.success(toEagerDto(crystallonData));
    }

    @ApiOperation(value = "创建籽晶检验记录")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "籽晶检验记录对象") List<CrystallonDataDto> crystallonDataDtoList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }

        List<CrystallonData> crystallonDataList = new ArrayList<>();
//        // 圆棒长度
//        double length = 0D;
//        // 累计长度
//        double sum = 0D;
        for (CrystallonDataDto crystallonDataDto : crystallonDataDtoList) {


            CrystallonData crystallonData = fromDto(crystallonDataDto);
//            sum += crystallonData.getCrystallonLength().doubleValue();
//            length = crystallonData.getLength().doubleValue();
            crystallonData.setCreateTime(new Date());
            //班次
            String classNo = BaseContextHandler.getUserClassNo();
            crystallonData.setClassNo(classNo);
            //班组
            String classGroup = BaseContextHandler.getUserTeamGroup();
            crystallonData.setOperator(BaseContextHandler.getUsername());
            crystallonData.setClassName(classGroup);
            crystallonDataList.add(crystallonData);
        }
//        if (sum > length) {
//            return ResultGenerator.fail("圆棒长度：" + length + " 籽晶累计长度：" + sum + " 异常");
//        }

        crystallonDataService.save(crystallonDataList);
        return ResultGenerator.success();
    }


    @ApiOperation(value = "根据晶段编号获取圆棒信息信息")
    @GetMapping("/getLineDetailDto")
    public Result<LineDetailDto> getLineDetailDto(String sectionNo) {
        sectionNo = StringUtils.trim(sectionNo);

        ProductionPaintingLineDetail productionPaintingLineDetail = productionPaintingLineDetailService.findBySegmentNo(sectionNo);
        if (null == productionPaintingLineDetail) {
            return ResultGenerator.fail("单晶编号不存在");
        }
        if (EnumValuesServer.LineType.回收料.getKey() == productionPaintingLineDetail.getType() ||
                EnumValuesServer.LineType.直径异常回收料.getKey() == productionPaintingLineDetail.getType() ||
                EnumValuesServer.LineType.孪晶回收料.getKey() == productionPaintingLineDetail.getType() ||
                EnumValuesServer.LineType.头回收料.getKey() == productionPaintingLineDetail.getType() ||
                EnumValuesServer.LineType.尾回收料.getKey() == productionPaintingLineDetail.getType()
        ) {
            LineDetailDto lineDetailDto = new LineDetailDto();
            BeanUtil.copyBeanPropWithNullValue(lineDetailDto, productionPaintingLineDetail, "id");

            YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(sectionNo);
            if (null != ybInspectData) {
                // 规格
                lineDetailDto.setProductTypeSecond(ybInspectData.getProductTypeSecond());
            }

            return ResultGenerator.success(lineDetailDto);
        }
        return ResultGenerator.fail("此单晶不是回收料");

    }

    @ApiOperation(value = "根据籽晶编号获取籽晶检验记录")
    @GetMapping("/findByCrystallonNo")
    public Result<CrystallonDataDto> findByCrystallonNo(String crystallonNo) {
        crystallonNo = StringUtils.trim(crystallonNo);
        CrystallonData crystallonData = crystallonDataService.findByCrystallonNo(crystallonNo);
        if (null == crystallonData) {
            return ResultGenerator.fail("籽晶编号不存在：" + crystallonNo);
        }
        CrystallonDataDto crystallonDataDto = toEagerDto(crystallonData);
        return ResultGenerator.success(crystallonDataDto);
    }

    @ApiOperation(value = "导出籽晶检验记录Excel")
    @GetMapping("/exportExcel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        crystallonDataService.exportExcel(request, resp);
    }

    @ApiOperation(value = "更新籽晶检验记录")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "籽晶检验记录") CrystallonDataDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        CrystallonData entity = crystallonDataService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            CrystallonData entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entity.setUpdateTime(new Date());
            crystallonDataService.saveOrUpdate(entity);
            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 Integer[] ids) {
        for (Integer id : ids) {
            crystallonDataService.delete(id);
        }
        return ResultGenerator.success();
    }

    public CrystallonDataDto toLazyDto(CrystallonData entity) {
        return modelMapper.map(entity, CrystallonDataDto.class);
    }

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

    public CrystallonData fromDto(CrystallonDataDto dto) {
        return modelMapper.map(dto, CrystallonData.class);
    }


}
