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.Charge;
import com.lightinit.hsdatagateway.modules.gateway.service.ChargeService;
import com.lightinit.hsdatagateway.modules.sys.utils.UserUtils;
import com.google.common.base.Strings;
import com.lightinit.hsdatagateway.modules.foreign.model.ReturnResult;
import com.lightinit.hsdatagateway.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName: ChargeApiController
 * @Description: 计费api
 * @Author  yangrui
 * @Date 2019/3/7 上午10:44
 * @Version V1.0
 **/
@RequestMapping("${adminPath}/api/charge")
@RestController
public class ChargeApiController extends BaseController {

    @Autowired
    ChargeService chargeService;

    @GetMapping("/list")
    public ReturnResult list(Charge charge) {

        ReturnResult result = new ReturnResult();

        List<Charge> charges = chargeService.findListByApi(charge);
        result.setResult(charges);

        return result;
    }

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

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

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

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

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

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

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

        result = buildResult(result, message, code);

        return result;
    }

    @DeleteMapping("delete")
    public ReturnResult delete(Charge charge) {
        ReturnResult result = new ReturnResult();

        charge.setDeletedBy(UserUtils.getUser().getName());

        chargeService.delete(charge);
        return result;
    }
}
