package com.sw.mes.jip.controller;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

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.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.annotation.Jinko;
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.jip.dto.JipHeaderConfigDto;
import com.sw.mes.jip.dto.JipParamsDto;
import com.sw.mes.jip.entity.JipHeaderConfig;
import com.sw.mes.jip.service.JipHeaderConfigService;
import com.sw.mes.jip.utils.JipRestUtils;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 晶科JIP接口配置信息Controller
 * 
 * @author liru
 * @date 2024-01-01
 */
@RestController
@Jinko(value="晶科JIP接口配置信息Controller",author = "liru")
@RequestMapping("/mes/config")
public class JipHeaderConfigController
{
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private JipHeaderConfigService jipHeaderConfigService;

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

    @ApiOperation(value = "获取所有数据")
    @GetMapping("/listAll")
    public Result<List<JipHeaderConfigDto>> listAll(ServletRequest request) {
        Specification<JipHeaderConfig> specification = DynamicSpecifications.bySearchFilter(request, JipHeaderConfig.class);
        List<JipHeaderConfig> JipHeaderConfigs = jipHeaderConfigService.findByExampleSort(specification, null);
        List<JipHeaderConfigDto> JipHeaderConfigDtos = JipHeaderConfigs.stream()
                .map(JinkoJipHeaderConfig -> toLazyDto(JinkoJipHeaderConfig))
                .collect(Collectors.toList());
        return ResultGenerator.success(JipHeaderConfigDtos);
    }

    @ApiOperation(value = "根据id获取详细信息")
    @GetMapping("/{id}")
    public Result<JipHeaderConfigDto> get(@PathVariable @ApiParam(value="JinkoJipHeaderConfigid") Long id) {
        JipHeaderConfig JipHeaderConfig = jipHeaderConfigService.get(id);
        if (null == JipHeaderConfig)
            return ResultGenerator.fail("该记录不存在");
        return ResultGenerator.success(toEagerDto(JipHeaderConfig));
    }

    @ApiOperation(value = "创建数据")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "JinkoJipHeaderConfig对象") JipHeaderConfigDto JipHeaderConfigDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        JipHeaderConfig JipHeaderConfig = fromDto(JipHeaderConfigDto);
        jipHeaderConfigService.saveOrUpdate(JipHeaderConfig);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "JipHeaderConfig") JipHeaderConfigDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        JipHeaderConfig entity = jipHeaderConfigService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            JipHeaderConfig entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            jipHeaderConfigService.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) {
            jipHeaderConfigService.delete(id);
            
        }
        return ResultGenerator.success();
    }
    
    /**
     * 实现单服务器请求JIP
     * @param params
     * @return
     */
    @ApiOperation(value = "发送SAP请求")
    @PostMapping("/sendRequest")
    public synchronized JSONObject sendRequest(@RequestBody JipParamsDto params) {
    	JSONObject result = JipRestUtils.post(params.getUrl(), params.getJson(), params.getToken());
    	return result;
    }

    public JipHeaderConfigDto toLazyDto(JipHeaderConfig entity) {
        return modelMapper.map(entity, JipHeaderConfigDto.class);
    }

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

    public JipHeaderConfig fromDto(JipHeaderConfigDto dto) {
        return modelMapper.map(dto, JipHeaderConfig.class);
    }
}
