package com.lightinit.hsdatagateway.modules.api.gateway;

import com.lightinit.hsdatagateway.common.web.BaseController;
import com.lightinit.hsdatagateway.modules.foreign.model.ReturnResult;
import com.lightinit.hsdatagateway.modules.gateway.entity.Auth;
import com.lightinit.hsdatagateway.modules.gateway.service.AuthService;
import com.google.common.base.Strings;
import com.lightinit.hsdatagateway.modules.foreign.model.ReturnResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName: AuthApiController
 * @Description: 鉴权对外api接口
 * @Author: yangrui
 * @Date 2019/3/7 上午9:44
 * @Version V1.0
 **/
@RequestMapping(value = "${adminPath}/api/auth")
@RestController
public class AuthApiController extends BaseController {

    @Autowired
    AuthService authService;

    @GetMapping("/list")
    public ReturnResult list(Auth auth) {

        ReturnResult result = new ReturnResult();

        List<Auth> authList = authService.findListByApi(auth);

        result.setResult(authList);
        return result;
    }

    @PostMapping("/add")
    public ReturnResult add(@RequestBody Auth auth) {
        String message = auth.ifNotNull(auth);

        if (!Strings.isNullOrEmpty(message)) {
            return new ReturnResult("500", message);
        }

        boolean isAdd = authService.isRepetition(auth);
        if (!isAdd) {
            return new ReturnResult("500","用户Id、路由Id、应用Id重复，添加失败！");
        }
        authService.save(auth);

        return new ReturnResult();
    }

    @PutMapping("update")
    public ReturnResult update(@RequestBody Auth auth) {
        String message = auth.ifNotNull(auth);
        String code = "";

        if (!Strings.isNullOrEmpty(message)) {
            code = "500";
            return new ReturnResult(code, message);
        }

        boolean isUpdate = authService.isRepetition(auth);
        if (isUpdate) {
            code = "500";
            return new ReturnResult(code, "用户Id、路由Id、应用Id不存在，修改失败！");
        }

        int resultInt = authService.updateByApi(auth);
        if (resultInt < 1) {
            code = "500";
            message = "修改失败！";
        }
        ReturnResult result = new ReturnResult();

        result = buildResult(result, message, code);

        return result;
    }

    @DeleteMapping("delete")
    public ReturnResult delete(Auth auth) {
        if (auth.getId() == null) {
            return new ReturnResult("500", "Id不可为空");
        }

        auth = authService.get(auth.getId());
        if (auth == null) {
            return new ReturnResult("500", "记录不存在");
        }

        authService.delete(auth);
        return new ReturnResult();
    }

}
