package com.sw.mes.yb.deviceCheck.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.yb.deviceCheck.dto.DeviceCheckDto;
import com.sw.mes.yb.deviceCheck.dto.SpotCheckItemDto;
import com.sw.mes.yb.deviceCheck.entity.DeviceCheck;
import com.sw.mes.yb.deviceCheck.entity.SpotCheckItem;
import com.sw.mes.yb.deviceCheck.service.DeviceCheckService;
import com.sw.mes.yb.deviceCheck.service.SpotCheckItemService;
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.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/deviceCheck")
@Slf4j
@Api(description = "设备点检接口")
public class DeviceCheckController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private DeviceCheckService deviceCheckService;

    @Autowired
    private SpotCheckItemService spotCheckItemService;

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

    @ApiOperation(value = "获取所有设备点检信息")
    @GetMapping("/listAll")
    public Result<List<DeviceCheckDto>> listAll(ServletRequest request) {
        Specification<DeviceCheck> specification = DynamicSpecifications.bySearchFilter(request, DeviceCheck.class);
        List<DeviceCheck> deviceChecks = deviceCheckService.findByExampleSort(specification, null);
        List<DeviceCheckDto> artBagItemDtos = deviceChecks.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(artBagItemDtos);
    }

    @ApiOperation(value = "设备点检详细信息")
    @GetMapping("/{id}")
    public Result<DeviceCheckDto> get(@PathVariable @ApiParam(value = "设备点检id") Integer id) {
        DeviceCheck deviceCheck = deviceCheckService.get(id);
        if (null == deviceCheck)
            return ResultGenerator.fail("该设备点检不存在");
        List<SpotCheckItem> spotCheckItems = spotCheckItemService.findAllOrderByPriority();
        Map<String, SpotCheckItem> spotCheckMap = new HashMap<>();
        for (SpotCheckItem item : spotCheckItems) {
            spotCheckMap.put(item.getId().toString(), item);
        }

        List<SpotCheckItemDto> spotCheckItemDtos = new ArrayList<>();

        String[] results = deviceCheck.getResults().split(";");
        if (results.length > 0) {
            for (String result : results) {
                if (result.split(":").length == 2) {
                    String[] value = result.split(":");
                    String idValue = value[0];
                    String res = value[1];
                    if (spotCheckMap.containsKey(idValue)) {
                        SpotCheckItemDto spotCheckItemDto = toLazyDto(spotCheckMap.get(idValue));
                        String[] r = res.split(",");
                        if (r.length == 3) {
                            spotCheckItemDto.setResult1("1".equals(r[0]));
                            spotCheckItemDto.setResult2("1".equals(r[1]));
                            spotCheckItemDto.setResult3("1".equals(r[2]));
                        }
                        spotCheckItemDtos.add(spotCheckItemDto);
                    }
                }
            }
        }
        DeviceCheckDto deviceCheckDto = toLazyDto(deviceCheck);
        deviceCheckDto.setSpotCheckItemDtos(spotCheckItemDtos);

        return ResultGenerator.success(deviceCheckDto);
    }

    @ApiOperation(value = "创建设备点检信息")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "设备点检对象") DeviceCheckDto deviceCheckDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        DeviceCheck deviceCheck = fromDto(deviceCheckDto);
        deviceCheckService.saveOrUpdate(deviceCheck);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新设备点检信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "设备点检") DeviceCheckDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        DeviceCheck entity = deviceCheckService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            DeviceCheck entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            deviceCheckService.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) {
            deviceCheckService.delete(id);
        }
        return ResultGenerator.success();
    }

    public DeviceCheckDto toLazyDto(DeviceCheck entity) {
        return modelMapper.map(entity, DeviceCheckDto.class);
    }

    public SpotCheckItemDto toLazyDto(SpotCheckItem entity) {
        return modelMapper.map(entity, SpotCheckItemDto.class);
    }

    public DeviceCheck fromDto(DeviceCheckDto dto) {
        return modelMapper.map(dto, DeviceCheck.class);
    }

}
