package com.xydl.cac.controller;

import com.xydl.cac.entity.Rptparamindex;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.model.BindDetail;
import com.xydl.cac.model.BindingModel;
import com.xydl.cac.model.Response;
import com.xydl.cac.service.ParamIndexService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;

@RestController
@Api(tags = {"rptparam相关接口"})
@RequestMapping("rptparam")
@Slf4j
public class ParamIndexController extends BasicController {

    @Resource
    ParamIndexService service;

    @GetMapping("listRpt")
    @ApiOperation("查询可用rptparam")
    public Response<List<Rptparamindex>> listRpt(String param) throws Exception {
        if (param == null) {
            throw new BusinessException("param不能为空!");
        }
        List<Rptparamindex> result = service.listRpt(param);
        return Response.success(result);
    }

    @GetMapping("getRpt")
    @ApiOperation("查询绑定信息")
    public Response<BindDetail> getRpt(@Validated @NotNull(message = "sensorId不能为空!") @Param("sensorId") Integer sensorId) throws Exception {
        if (sensorId == null) {
            throw new BusinessException("sensorId不能为空!");
        }
        BindDetail result = service.getRpt(sensorId);
        return Response.success(result);
    }

    @PostMapping("updateRpt")
    @ApiOperation("绑定")
    public Response<String> updateRpt(@Validated @RequestBody BindingModel item) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        for (Rptparamindex rpt : item.getRptList()) {
            if (StringUtils.isNotBlank(rpt.getParamindex())) {
                if (map.containsKey(rpt.getParamindex())) {
                    throw new BusinessException("不能有相同的" + rpt.getParamindex());
                } else {
                    map.put(rpt.getParamindex(), "");
                }
            }
        }
        service.updateRpt(item);
        return Response.success("OK");
    }

    @PostMapping("clearParamindex")
    @ApiOperation("清空rptparamindex表数据")
    public Response<String> clearParamindex() throws Exception {
        service.clearAll();
        return Response.success("OK");
    }

}
