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

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.inspect.entity.YbInspectData;
import com.sw.mes.yb.pad.entity.SectionNoDetail;
import com.sw.mes.yb.pad.service.SectionNoDetailService;
import com.sw.mes.yb.pc.dto.DataInspectLogDto;
import com.sw.mes.yb.pc.dto.InspectDataBaseDto;
import com.sw.mes.yb.pc.entity.DataInspectLog;
import com.sw.mes.yb.pc.service.DataInspectLogService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.validation.Valid;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description： 圆棒检验数据库创建记录
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/dataInspectLog")
@Slf4j
@Api(description = "DataInspectLog接口")
public class DataInspectLogController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private DataInspectLogService dataInspectLogService;

    @Autowired
    private SectionNoDetailService sectionNoDetailService;

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

    @ApiOperation(value = "获取所有DataInspectLog")
    @GetMapping("/listAll")
    public Result<List<DataInspectLogDto>> listAll(ServletRequest request) {
        Specification<DataInspectLog> specification = DynamicSpecifications.bySearchFilter(request, DataInspectLog.class);
        List<DataInspectLog> dataInspectLogs = dataInspectLogService.findByExampleSort(specification, null);
        List<DataInspectLogDto> dataInspectLogDtos = dataInspectLogs.stream()
                .map(dataInspectLog -> toLazyDto(dataInspectLog))
                .collect(Collectors.toList());
        return ResultGenerator.success(dataInspectLogDtos);
    }

    @ApiOperation(value = "DataInspectLog详细信息")
    @GetMapping("/{id}")
    public Result<DataInspectLogDto> get(@PathVariable @ApiParam(value = "DataInspectLogid") Long id) {
        DataInspectLog dataInspectLog = dataInspectLogService.get(id);
        if (null == dataInspectLog)
            return ResultGenerator.fail("该DataInspectLog不存在");
        return ResultGenerator.success(toEagerDto(dataInspectLog));
    }

    @ApiOperation(value = "创建DataInspectLog")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "DataInspectLog对象") DataInspectLogDto dataInspectLogDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        DataInspectLog dataInspectLog = fromDto(dataInspectLogDto);
        dataInspectLogService.saveOrUpdate(dataInspectLog);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新DataInspectLog")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "DataInspectLog") DataInspectLogDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        DataInspectLog entity = dataInspectLogService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            DataInspectLog entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            dataInspectLogService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

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


    @ApiOperation(value = "圆棒检验数据记录信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_sectionNo", value = "晶段编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_crystalNo", value = "晶棒编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_inspector", value = "检验人", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_levelTime", value = "检验开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_levelTime", value = "检验结束时间", dataType = "string", paramType = "query")})
    @GetMapping("/getListPage")
    public Result<ResponsePage<InspectDataBaseDto>> getCutRecordListPage(String search_EQ_sectionNo, String search_EQ_crystalNo, String search_EQ_inspector,
                                                                         String search_GTE_levelTime, String search_LT_levelTime,
                                                                         @ApiIgnore RequestPage requestPage) {
        requestPage.setOrderField(null);
        search_EQ_sectionNo = StringUtils.isBlank(search_EQ_sectionNo) ? null : search_EQ_sectionNo;
        search_EQ_crystalNo = StringUtils.isBlank(search_EQ_crystalNo) ? null : search_EQ_crystalNo;
        search_EQ_inspector = StringUtils.isBlank(search_EQ_inspector) ? null : search_EQ_inspector;
        search_GTE_levelTime = StringUtils.isBlank(search_GTE_levelTime) ? null : search_GTE_levelTime;
        search_LT_levelTime = StringUtils.isBlank(search_LT_levelTime) ? null : search_LT_levelTime;
        ResponsePage<InspectDataBaseDto> responsePage = dataInspectLogService.getListPageInfo(search_EQ_sectionNo, search_EQ_crystalNo, search_EQ_inspector,
                search_GTE_levelTime,search_LT_levelTime,
                PageUtil.createPageable(requestPage));
        return ResultGenerator.success(responsePage);
    }

//    @ApiOperation(value = "圆棒检验数据记录信息导出")
//    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
//            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
//            @ApiImplicitParam(name = "search_EQ_sectionNo", value = "晶段编号", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "search_EQ_crystalNo", value = "晶棒编号", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "search_EQ_inspector", value = "检验人", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "search_GTE_levelTime", value = "检验开始时间", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "search_LT_levelTime", value = "检验结束时间", dataType = "string", paramType = "query")})
//    @GetMapping("/export")
//    public void cutExport(String search_EQ_sectionNo, String search_EQ_crystalNo, String search_EQ_inspector,
//                          String search_GTE_levelTime, String search_LT_levelTime,
//                          @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
//        try {
//            requestPage.setOrderField(null);
//            search_EQ_sectionNo = StringUtils.isBlank(search_EQ_sectionNo) ? null : search_EQ_sectionNo;
//            search_EQ_crystalNo = StringUtils.isBlank(search_EQ_crystalNo) ? null : search_EQ_crystalNo;
//            search_EQ_inspector = StringUtils.isBlank(search_EQ_inspector) ? null : search_EQ_inspector;
//            search_GTE_levelTime = StringUtils.isBlank(search_GTE_levelTime) ? null : search_GTE_levelTime;
//            search_LT_levelTime = StringUtils.isBlank(search_LT_levelTime) ? null : search_LT_levelTime;
//            List<InspectDataBaseDto> list1 = dataInspectLogService.getListInfo(search_EQ_sectionNo, search_EQ_crystalNo, search_EQ_inspector,
//                    search_GTE_levelTime,search_LT_levelTime);
//            EasyExcelUtils.write(response, InspectDataBaseDto.class, "圆棒检验数据记录信息", "圆棒检验数据记录信息", list1);
//        } catch (Exception e) {
//            throw new RuntimeException("圆棒检验数据记录信息导出失败，错误信息：" + e.getMessage());
//        }
//    }

    @ApiModelProperty("通过晶段编号查询圆棒检验记录")
    @GetMapping("/getDataInspectLogBySectionNo")
    public Result<List<DataInspectLogDto>> getDataInspectLogBySectionNo(String sectionNo){
        List<DataInspectLog> list = dataInspectLogService.getDataInspectLogBySectionNo(sectionNo);
        List<DataInspectLogDto> dtos = list.stream().map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @ApiModelProperty("通过晶段编号查询圆棒检验记录")
    @GetMapping("/getDataInspectLog")
    public Result<List<DataInspectLogDto>> getDataInspectLog(String sectionNo){
        List<DataInspectLog> list = dataInspectLogService.getDataInspectLog(sectionNo);
        List<DataInspectLogDto> dtos = list.stream().map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    public DataInspectLogDto toLazyDto(DataInspectLog entity) {
        DataInspectLogDto map = modelMapper.map(entity, DataInspectLogDto.class);
        SectionNoDetail detail = sectionNoDetailService.findBySectionNo(entity.getSectionNo());
        map.setProductType(Optional.ofNullable(detail).map(SectionNoDetail::getProductType).orElse(""));
        return map;
    }

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

    public DataInspectLog fromDto(DataInspectLogDto dto) {
        return modelMapper.map(dto, DataInspectLog.class);
    }


}
