package com.sptg.ad.biz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.ad.api.entity.ThresholdConfig;
import com.sptg.ad.api.feigns.ThresholdConfigFeign;
import com.sptg.ad.biz.service.ThresholdConfigService;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

/**
 *            
 *               
 * description:
 */
@RestController
@RequiredArgsConstructor
public class ThresholdConfigController implements ThresholdConfigFeign {

    private final ThresholdConfigService thresholdConfigService;


    @Override
    @PostMapping(value = "/threshold_config/pageingQuery")
    public Page<ThresholdConfig> pagingQuery(@RequestBody PageBean<ThresholdConfig, ThresholdConfig> pageBean) {
        ThresholdConfig dto = pageBean.getDto();
        Wrapper<ThresholdConfig> wrapper = new EntityWrapper<>();
        if (null != dto.getOrgId()){
            wrapper.eq("org_id",dto.getOrgId());
        }
        if (null != dto.getType()){
            wrapper.eq("type",dto.getType());
        }
        return this.thresholdConfigService.selectPage(pageBean,wrapper);
    }

    @Override
    @PostMapping(value = "/threshold_config/add")
    public ResultBean addConfig(@RequestBody ThresholdConfig config) {
        //  判断是否已存在配置
        ThresholdConfig conf = this.thresholdConfigService.selectByRegionCode(config.getOrgId(), config.getType(), config.getRegionCode());
        Assert.isNull(conf,"该城市的配置已存在");
        this.thresholdConfigService.insert(config);
        return ResultBean.ok();
    }

    @Override
    @GetMapping(value = "/threshold_config/get/{id}")
    public ThresholdConfig getById(@PathVariable(value = "id") Long id) {
        return this.thresholdConfigService.selectById(id);
    }

    @Override
    @PostMapping(value = "/threshold_config/edit")
    public ResultBean editConfig(@RequestBody ThresholdConfig config) {
        ThresholdConfig dbConfig = this.thresholdConfigService.selectById(config.getId());
        Assert.notNull(dbConfig,"Id不存在");
        dbConfig.setValue(config.getValue());
        if (this.thresholdConfigService.updateById(dbConfig)){
            return ResultBean.ok();
        }
        return new ResultBean(ResultEnum.ERROR);
    }

    @Override
    @GetMapping(value = "/threshold_config/delete/{id}")
    public ResultBean deleteConfig(@PathVariable(value = "id") Long id) {
        boolean isDelete = this.thresholdConfigService.deleteById(id);
        Assert.isTrue(isDelete,"Id不存在");
        return ResultBean.ok();
    }
}
