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

import com.sw.mes.core.annotation.TokenNotValidation;
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.DynamicSpecifications;
import com.sw.mes.core.utils.EasyExcelUtils;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.utils.ExcelUtil;
import com.sw.mes.yb.report.dto.ScheduleProductionConfigDto;
import com.sw.mes.yb.report.entity.ScheduledProductionConfig;
import com.sw.mes.yb.report.service.ScheduleProductionConfigService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
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 org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

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

/**
 * @author JS107742
 */
@RestController
@RequestMapping("/scheduledProductionConfig")
@Slf4j
@Api(description = "计划产量维护")
public class ScheduledProductionConfigController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private ScheduleProductionConfigService scheduleProductionConfigService;


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

    @ApiOperation(value = "计划产量录入")
    @PostMapping("/add")
    public Result addScheduledProductionConfig(@RequestBody @Valid @ApiParam(value = "计划产量录入") ScheduleProductionConfigDto scheduleProductionConfigDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        List<ScheduledProductionConfig> collect = getScheduledProductionConfigs(scheduleProductionConfigDto);
        scheduleProductionConfigService.saveAll(collect);
        return ResultGenerator.success("操作成功");
    }

    @ApiOperation(value = "计划产量更新")
    @PostMapping("/update")
    public Result updateScheduledProductionConfig(@RequestBody @Valid @ApiParam(value = "更新计划产量信息") List<ScheduleProductionConfigDto> scheduleProductionConfigDtos, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }

        for (ScheduleProductionConfigDto scheduleProductionConfigDto : scheduleProductionConfigDtos) {
            if (scheduleProductionConfigDto.getId() == null) {
                return ResultGenerator.fail("id不能为空");
            }
            ScheduledProductionConfig entity = scheduleProductionConfigService.get(scheduleProductionConfigDto.getId());
            if (entity == null) {
                return ResultGenerator.fail("原信息不存在");
            }
            List<ScheduledProductionConfig> collect = getScheduledProductionConfigs(scheduleProductionConfigDto);
            scheduleProductionConfigService.saveOrUpdate(collect.get(0));
        }

        return ResultGenerator.success("操作成功");
    }

    @ApiOperation(value = "删除计划产量数据")
    @PostMapping("/delete")
    public Result deleteScheduledProductionConfig(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        if (null != ids && ids.length > 0) {
            for (Long id : ids) {
                ScheduledProductionConfig seedTest = scheduleProductionConfigService.get(id);
                if (null != seedTest) {
                    scheduleProductionConfigService.delete(id);
                } else {
                    continue;
                }
            }
            return ResultGenerator.success("删除成功");
        }
        return ResultGenerator.success("id不能为空");
    }


    /**
     * 导入计划产量数据
     *
     * @param file
     */
    @ApiOperation(value = "导入籽晶检验数据")
    @PostMapping("/import")
    public Result seedTestDto(MultipartFile file) {
        Object objList = EasyExcelUtils.readExcel(file, new ScheduleProductionConfigDto(), 1, 1);
        if (objList != null) {
            List<ScheduleProductionConfigDto> scheduleProductionConfigDtoList = (List<ScheduleProductionConfigDto>) objList;
            List<ScheduledProductionConfig> scheduleProductionConfigList = scheduleProductionConfigService.plannedInitialization(scheduleProductionConfigDtoList);
            StringBuilder failMessage = new StringBuilder();
            int successCount = 0, failCount = 0;
            for (ScheduledProductionConfig scheduledProductionConfig : scheduleProductionConfigList) {
                try {
                    scheduleProductionConfigService.saveOrUpdate(scheduledProductionConfig);
                } catch (Exception e) {
                    failCount++;
                    failMessage.append(scheduledProductionConfig.getOrderNo()).append("导入失败【").append(e.getMessage()).append("】；\\n");
                }
                successCount++;
            }
            if (successCount > 0) {
                return ResultGenerator.success("共【" + successCount + failCount + "】条，成功【" + successCount + "】条；\\n"
                        + "失败【" + failCount + "】：" + failMessage);
            } else {
                return ResultGenerator.fail("共【" + successCount + failCount + "】条，全部失败：" + failMessage);
            }
        } else {
            return ResultGenerator.fail("导入数据为空");
        }
    }

    @ApiOperation(value = "导出计划产量数据")
    @GetMapping("/export")
    public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
        try {
            Specification<ScheduledProductionConfig> specification = DynamicSpecifications.bySearchFilter(request, ScheduledProductionConfig.class);
            List<ScheduledProductionConfig> seedTests = scheduleProductionConfigService.findByExampleSort(specification, null);
            List<ScheduleProductionConfigDto> seedTestDtos = seedTests.stream()
                    .map(backCutRule -> toLazyDto(backCutRule))
                    .collect(Collectors.toList());
            EasyExcelUtils.write(response, ScheduleProductionConfigDto.class, "导出计划产量数据", "导出计划产量数据", seedTestDtos);
        } catch (Exception e) {
            throw new RuntimeException("计划产量导出失败，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation(value = "模板文件下载")
    @PostMapping("/download")
    @TokenNotValidation
    public void download(HttpServletResponse response) {
        String path = "template/计划产量维护.xlsx";
        ExcelUtil.download1(path, response);
    }

    private List<ScheduledProductionConfig> getScheduledProductionConfigs(ScheduleProductionConfigDto scheduleProductionConfigDto) {
        List<ScheduleProductionConfigDto> list = new ArrayList<>();
        list.add(scheduleProductionConfigDto);
        List<ScheduledProductionConfig> scheduleProductionConfigList = scheduleProductionConfigService.plannedInitialization(list);
        return scheduleProductionConfigList;
    }

    public ScheduleProductionConfigDto toLazyDto(ScheduledProductionConfig entity) {
        return modelMapper.map(entity, ScheduleProductionConfigDto.class);
    }
}
