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

import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.*;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.yb.production.dto.ProductionResistivityDto;
import com.sw.mes.yb.production.entity.ProductionResistivity;
import com.sw.mes.yb.production.service.ProductionResistivityService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/productionResistivity")
@Slf4j
@Api(description = "电阻率维护接口")
public class ProductionResistivityController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private ProductionResistivityService productionResistivityService;

    @Autowired
    private EquipmentService equipmentService;

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

    @ApiOperation(value = "获取所有电阻率配置数据")
    @GetMapping("/listAll")
    public Result<List<ProductionResistivityDto>> listAll(ServletRequest request) {
        Specification<ProductionResistivity> specification = DynamicSpecifications.bySearchFilter(request, ProductionResistivity.class);
        List<ProductionResistivity> productionResistivities = productionResistivityService.findByExampleSort(specification, null);
        List<ProductionResistivityDto> ProductionResistivitys = productionResistivities.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(ProductionResistivitys);
    }

    @ApiOperation(value = "电阻率配置数据详细信息")
    @GetMapping("/{id}")
    public Result<ProductionResistivityDto> get(@PathVariable @ApiParam(value = "productionResistivityServiceid") Integer id) {
        ProductionResistivity productionResistivity = productionResistivityService.get(id);
        if (null == productionResistivity)
            return ResultGenerator.fail("该条数据不存在");
        return ResultGenerator.success(toEagerDto(productionResistivity));
    }

    @ApiOperation(value = "新增电阻率配置数据")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "ProductionResistivity对象") ProductionResistivityDto resistivity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        String[] split = resistivity.getEquipmentCode().split(",");
        for (String equipmentCode : split) {
            if (!StringUtils.isBlank(equipmentCode)) {
                Result result = saveConfig(resistivity, equipmentCode);
                if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                    return result;
                }
            }
        }
        return ResultGenerator.success();
    }

    private Result saveConfig(ProductionResistivityDto resistivity, String equipmentCode) {
        resistivity.setSeries(equipmentCode.substring(0, 1));
        Equipment equipment = equipmentService.findByCode(equipmentCode);
        if (null != equipment) {
            resistivity.setModule(equipment.getArea());
            resistivity.setEquipmentCode(equipmentCode);
            ProductionResistivity productionResistivity = fromDto(resistivity);
            if(StringUtils.isBlank(productionResistivity.getAgainNum())){
                productionResistivity.setAgainNum(null);
            }
            List<ProductionResistivity> list = productionResistivityService.findByEquipmentCodeAndAgainNum(equipmentCode, resistivity.getAgainNum());
            if (null != list && list.size() > 0) {
                return ResultGenerator.fail("设备号：" + list.get(0).getEquipmentCode() +
                        ",复投次数：" + list.get(0).getAgainNum() + "配置重复");
            }
            productionResistivityService.saveOrUpdate(productionResistivity);
            return ResultGenerator.success();
        }
        return ResultGenerator.fail("未查询到" + equipmentCode + "设备信息");
    }

    @ApiOperation(value = "更新电阻率配置数据")
    @PostMapping("/update")
    public Result<Object> update(@RequestBody @Valid @ApiParam(value = "ProductionResistivity") ProductionResistivityDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        ProductionResistivity entityfromFto = fromDto(dto);
        ProductionResistivity entity = productionResistivityService.get(entityfromFto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {

            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            if(StringUtils.isBlank(entity.getAgainNum())){
                entity.setAgainNum(null);
            }
            productionResistivityService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除电阻率配置数据")
    @PostMapping("/delete")
    public Result<String> remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (Integer id : ids) {
            productionResistivityService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "导出电阻率配置数据")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse resp) {
        try {
            Specification<ProductionResistivity> specification = DynamicSpecifications.bySearchFilter(request, ProductionResistivity.class);
            List<ProductionResistivity> byExampleSort = productionResistivityService.findByExampleSort(specification, null);
            EasyExcelUtils.write(resp, ProductionResistivityDto.class, "电阻率配置数据", "电阻率配置数据", byExampleSort);
        } catch (Exception e) {
            throw new RuntimeException("电阻率配置数据导出失败，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation(value = "导入电阻率配置数据")
    @PostMapping("/importExcel")
    public Result importGrade(MultipartFile file) {
        Object objList = EasyExcelUtils.readExcel(file, new ProductionResistivityDto(), 1, 1);
        if (objList != null) {
            List<ProductionResistivityDto> productionResistivityDtoList = (List<ProductionResistivityDto>) objList;
            StringBuilder failMessage = new StringBuilder();
            int successCount = 0, failCount = 0;
            for (ProductionResistivityDto productionResistivityDto : productionResistivityDtoList) {
                try {
                    ProductionResistivity measConfig = new ProductionResistivity();
                    BeanUtils.copyProperties(productionResistivityDto, measConfig);
                    productionResistivityService.saveOrUpdate(measConfig);
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                    failMessage.append(productionResistivityDto.getEquipmentCode()).append("导入失败【").append(e.getMessage()).append("】；\\n");
                }
            }
            if (successCount > 0) {
                return ResultGenerator.success("共【" + productionResistivityDtoList.size() + "】条，成功【" + successCount + "】条；\\n"
                        + "失败【" + failCount + "】：" + failMessage);
            } else {
                return ResultGenerator.fail("共【" + successCount + failCount + "】条，全部失败：" + failMessage);
            }
        } else {
            return ResultGenerator.fail("导入数据为空");
        }
    }

    public ProductionResistivityDto toLazyDto(ProductionResistivity entity) {
        return modelMapper.map(entity, ProductionResistivityDto.class);
    }

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

    public ProductionResistivity fromDto(ProductionResistivityDto dto) {
        return modelMapper.map(dto, ProductionResistivity.class);
    }
}
