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

import com.alibaba.excel.EasyExcel;
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.yb.alloy.dto.*;
import com.sw.mes.yb.alloy.entity.CorrectingRecord;
import com.sw.mes.yb.alloy.entity.InspectionList;
import com.sw.mes.yb.alloy.service.CorrectingRecordService;
import com.sw.mes.yb.alloy.service.InspectionListService;
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.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.sw.mes.yb.alloy.entity.AlloyMasterAlloy;
import com.sw.mes.yb.alloy.service.AlloyMasterAlloyService;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/alloyMasterAlloy")
@Slf4j
@Api(description = "母合金接口")
public class AlloyMasterAlloyController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private AlloyMasterAlloyService alloyMasterAlloyService;

    @Autowired
    private CorrectingRecordService correctingRecordService;

    @Autowired
    private InspectionListService inspectionListService;

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

    @ApiOperation(value = "获取所有母合金")
    @GetMapping("/listAll")
    public Result<List<AlloyMasterAlloyDto>> listAll(ServletRequest request) {
        Specification<AlloyMasterAlloy> specification = DynamicSpecifications.bySearchFilter(request, AlloyMasterAlloy.class);
        List<AlloyMasterAlloy> alloyMasterAlloys = alloyMasterAlloyService.findByExampleSort(specification, null);
        List<AlloyMasterAlloyDto> alloyMasterAlloyDtos = alloyMasterAlloys.stream()
                .map(alloyMasterAlloy -> toLazyDto(alloyMasterAlloy))
                .collect(Collectors.toList());
        setList(alloyMasterAlloyDtos);
        return ResultGenerator.success(alloyMasterAlloyDtos);
    }

    @ApiOperation(value = "母合金详细信息")
    @GetMapping("/{id}")
    public Result<AlloyMasterAlloyDto> get(@PathVariable @ApiParam(value = "母合金id") Integer id) {
        AlloyMasterAlloy alloyMasterAlloy = alloyMasterAlloyService.get(id);
        if (null == alloyMasterAlloy) {
            return ResultGenerator.fail("该母合金不存在");
        }
        AlloyMasterAlloyDto alloyMasterAlloyDto = toEagerDto(alloyMasterAlloy);
        List<CorrectingRecord> correctingRecordList = correctingRecordService.findByAlloyMaterAlloyId(alloyMasterAlloy.getId());
        if (!CollectionUtils.isEmpty(correctingRecordList)) {
            List<CorrectingRecordDto> dtoList = toLazyDto1(correctingRecordList);
            alloyMasterAlloyDto.setCorrectingRecordDtoList(dtoList);
        }
        List<InspectionList> inspectionList = inspectionListService.findByAlloyMaterAlloyId(alloyMasterAlloy.getId());
        if (!CollectionUtils.isEmpty(inspectionList)) {
            List<InspectionListDto> inspectionListDtos = toLazyDto2(inspectionList);
            alloyMasterAlloyDto.setInspectionListDtoList(inspectionListDtos);
        }
        return ResultGenerator.success(alloyMasterAlloyDto);
    }

    @ApiOperation(value = "创建母合金")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "母合金对象") AlloyMasterAlloyDto alloyMasterAlloyDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        alloyMasterAlloyService.save(alloyMasterAlloyDto);
        return ResultGenerator.success();
    }

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

    @ApiOperation(value = "删除母合金")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id", type = "query") @RequestParam Integer id) {
        alloyMasterAlloyService.deleteById(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据炉台号查询相关信息")
    @GetMapping("/findByLotNo")
    public Result<FurnaceBedDto> findByCode(@RequestParam @ApiParam(value = "炉台号") String furnaceCode) {
        return ResultGenerator.success(alloyMasterAlloyService.findByCode(furnaceCode));
    }

    @ApiOperation(value = "计算母合金")
    @PostMapping("/calculationBaseAlloy")
    public Result<Float> calculationBaseAlloy(@RequestBody @ApiParam(value = "母合金") AlloyMasterAlloyDto dto) {
        Float baseAlloyWeight = alloyMasterAlloyService.calculationBaseAlloy(dto);
        return ResultGenerator.success(baseAlloyWeight);
    }

    @ApiOperation(value = "导出母合金记录")
    @GetMapping("/export")
    public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
        try {
            requestPage.setRows(Integer.MAX_VALUE);
            Specification<AlloyMasterAlloy> specification = DynamicSpecifications.bySearchFilter(request, AlloyMasterAlloy.class);
            Page<AlloyMasterAlloy> page = alloyMasterAlloyService.findByExample(specification, PageUtil.createPageable(requestPage));
            List<AlloyMasterAlloyExportDto> dtos = page.getContent().stream()
                    .map(this::toExportDto)
                    .collect(Collectors.toList());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("母合金记录", String.valueOf(StandardCharsets.UTF_8)).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AlloyMasterAlloyExportDto.class)
                    .sheet("母合金导出")
                    .doWrite(dtos);
        } catch (Exception e) {
            throw new RuntimeException("母合金记录导出失败，错误信息：" + e.getMessage());
        }
    }

    private AlloyMasterAlloyExportDto toExportDto(AlloyMasterAlloy entity) {
        AlloyMasterAlloyExportDto map = modelMapper.map(entity, AlloyMasterAlloyExportDto.class);
//        if (entity.getIsEnd()==0){
//            map.setIsEnd("是");
//        }else {
//            map.setIsEnd("否");
//        }

        if (entity.getIsCorrecting()==0){
            map.setIsCorrecting("是");
        }else {
            map.setIsCorrecting("否");
        }
        return map;
    }

//    @ApiOperation(value = "根据炉台号查询复投次数")
//    @GetMapping("/findByFurnaceCode")
//    public Result<FurnaceCodeDto> findAgainNumByCode(@RequestParam @ApiParam(value = "炉台号") String furnaceCode) {
//        return ResultGenerator.success(alloyMasterAlloyService.findAgainNumByCode(furnaceCode));
//    }

//    @ApiOperation(value = "母合金加料确认")
//    @PostMapping("/feedingConfirmation")
//    public Result feedingConfirmation(@RequestBody @Valid @ApiParam(value = "母合金加料对象") FeedingConfirmationDto feedingConfirmationDto, BindingResult bindingResult) {
//        if (bindingResult.hasErrors()) {
//            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
//        }
//        alloyMasterAlloyService.feedingConfirmation(feedingConfirmationDto);
//        return ResultGenerator.success();
//    }

    private void setList(List<AlloyMasterAlloyDto> dtos) {
        List<CorrectingRecord> correctingRecordList = correctingRecordService.findAll();
        List<InspectionList> inspectionListList = inspectionListService.findAll();
        Map<Integer, List<CorrectingRecord>> map = correctingRecordList.stream().collect(Collectors.groupingBy(CorrectingRecord::getAlloyMasterAlloyId));
        Map<Integer, List<InspectionList>> listMap = inspectionListList.stream().collect(Collectors.groupingBy(InspectionList::getAlloyMasterAlloyId));
        for (AlloyMasterAlloyDto dto : dtos) {
            List<CorrectingRecord> correctingRecords = map.get(dto.getId());
            List<InspectionList> inspectionList = listMap.get(dto.getId());
            if (!CollectionUtils.isEmpty(correctingRecords)) {
                List<CorrectingRecordDto> dtoList = toLazyDto1(correctingRecords);
                dto.setCorrectingRecordDtoList(dtoList);
            }
            if (!CollectionUtils.isEmpty(inspectionList)) {
                List<InspectionListDto> dtoList = toLazyDto2(inspectionList);
                dto.setInspectionListDtoList(dtoList);
            }
        }
    }

    public AlloyMasterAlloyDto toLazyDto(AlloyMasterAlloy entity) {
        return modelMapper.map(entity, AlloyMasterAlloyDto.class);
    }

    public AlloyMasterAlloyDto toEagerDto(AlloyMasterAlloy entity) {
        return modelMapper.map(entity, AlloyMasterAlloyDto.class);
    }

    private List<CorrectingRecordDto> toLazyDto1(List<CorrectingRecord> correctingRecords) {
        ArrayList<CorrectingRecordDto> recordDtoArrayList = new ArrayList<>();
        for (CorrectingRecord correctingRecord : correctingRecords) {
            CorrectingRecordDto map = modelMapper.map(correctingRecord, CorrectingRecordDto.class);
            recordDtoArrayList.add(map);
        }
        return recordDtoArrayList;
    }

    private List<InspectionListDto> toLazyDto2(List<InspectionList> inspectionLists) {
        ArrayList<InspectionListDto> list = new ArrayList<>();
        for (InspectionList inspectionList : inspectionLists) {
            InspectionListDto map = modelMapper.map(inspectionList, InspectionListDto.class);
            list.add(map);
        }
        return list;
    }

    public AlloyMasterAlloy fromDto(AlloyMasterAlloyDto dto) {
        return modelMapper.map(dto, AlloyMasterAlloy.class);
    }


}
