package com.muyu.enterprise.controller;

import com.muyu.common.core.domain.Result;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.WarnRule;
import com.muyu.enterprise.cache.AllWarnRuleCacheService;
import com.muyu.enterprise.cache.WarnRuleCacheService;
import com.muyu.enterprise.service.WarnRuleService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/rule")
public class WarnRuleController {
    @Autowired
    private WarnRuleService warnRuleService;

    @Autowired
    private WarnRuleCacheService warnRuleCacheService;

    //存列表
    @Autowired
    private AllWarnRuleCacheService allWarnRuleCacheServicel;

    /**
     * 规则列表
     * @return
     */
    @RequestMapping(path = "/ruleList",method = RequestMethod.POST)
    @Operation(summary = "规则列表", description = "获取所有规则列表")
    public Result<List<WarnRule>> ruleList(){
        List<WarnRule> list = warnRuleService.list();
        for (WarnRule warnRule : list) {
            allWarnRuleCacheServicel.put(warnRule.getRuleName(),warnRule);
        }
        return Result.success(list);
    }

    /**
     * 根据ID查询规则
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID来查询数据", description = "根据ID来查询数据")
    public Result<WarnRule> getById(@PathVariable("id")Long id){
        return Result.success(warnRuleService.getById(id));
    }

    /**
     * 添加规则
     * @param warnRule
     * @return
     */
    @RequestMapping(path = "ruleAdd",method = RequestMethod.POST)
    @Operation(summary = "添加规则", description = "添加规则")
    public Result ruleAdd(@Validated @RequestBody WarnRule warnRule){
        boolean save = warnRuleService.save(warnRule);
        //获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //获取租户唯一标识
        String databaseName = loginUser.getSysUser().getDatabaseName();
        warnRuleCacheService.put(databaseName+warnRule.getRuleName(),warnRule);
        return Result.success(save);
    }

    /**
     * 修改规则
     * @param warnRule
     * @param id
     * @return
     */
    @RequestMapping(path = "/{id}",method = RequestMethod.POST)
    @Operation(summary = "修改规则", description = "修改规则")
    public Result ruleUpdate(@Validated @RequestBody WarnRule warnRule, @PathVariable("id")Long id){
        return Result.success(warnRuleService.updateById(WarnRule.updateBuilder(warnRule,() -> id)));
    }

    /**
     * 删除规则
     * @param id
     * @return
     */
    @RequestMapping(path = "/{id}",method = RequestMethod.DELETE)
    @Operation(summary = "删除规则", description = "删除规则")
    public Result ruleDelete(@PathVariable("id")Long id){
        return Result.success(warnRuleService.removeById(id));
    }

}
